using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using PlaygroundSplines;
using System.Threading;
namespace ParticlePlayground {
///
/// The PlaygroundC class is the Playground Manager which runs all Particle Playground systems and is containing all Global Manipulators.
/// The Playground Manager acts as a wrapper class for common operations and contain functions for creating and altering particle systems.
/// You will also find the global event delegates (particleEventBirth, particleEventDeath, particleEventCollision and particleEventTime) for any particle systems broadcasting events with "Send To Manager" enabled.
///
[ExecuteInEditMode()]
public class PlaygroundC : MonoBehaviour {
/*************************************************************************************************************************************************
Playground counters
*************************************************************************************************************************************************/
public static int meshQuantity;
public static int particlesQuantity;
public static float version = 3.03f;
public static string specialVersion = " ";
/*************************************************************************************************************************************************
Playground settings
*************************************************************************************************************************************************/
// Time variables
///
/// The global time.
///
public static float globalTime;
///
/// Time when globalTime last updated.
///
public static float lastTimeUpdated;
///
/// Delta time for globalTime (globalTime-lastTimeUpdated).
///
public static float globalDeltaTime;
///
/// Scaling of globalTime.
///
public static float globalTimescale = 1.0f;
// Misc settings
///
/// Initial spawn position when particle is not set to rebirth.
///
public static Vector3 initialTargetPosition = new Vector3(0,-999.99f,0);
///
/// Update rate for finding vertices in skinned meshes (1 = Every frame, 2 = Every second frame...).
///
public static int skinnedUpdateRate = 1;
///
/// Let a PlaygroundParticleWindow repaint the scene.
///
public static bool triggerSceneRepaint = true;
///
/// Minimum velocity of a particle before it goes to rest on collision.
///
public static float collisionSleepVelocity = .01f;
///
/// Determines how many frames are unsafe before initiating automatic thread bundling.
///
public static int unsafeAutomaticThreadFrames = 20;
///
/// The frustum planes of the Main Camera. This is used to disable or enable calculation on particle systems when having PlaygroundParticlesC.pauseCalculationWhenInvisible enabled.
///
public static Plane[] frustumPlanes;
/*************************************************************************************************************************************************
Playground global event delegates (receives event particles sent from a particle system)
*************************************************************************************************************************************************/
///
/// The event of a particle birthing. This require that you are using Event Listeners and set your desired particle system(s) to broadcast the event by enabling PlaygroundEventC.sendToManager.
///
public static event OnPlaygroundParticle particleEventBirth;
static bool particleEventBirthInitialized = false;
///
/// The event of a particle dying. This require that you are using Event Listeners and set your desired particle system(s) to broadcast the event by enabling PlaygroundEventC.sendToManager.
///
public static event OnPlaygroundParticle particleEventDeath;
static bool particleEventDeathInitialized = false;
///
/// The event of a particle colliding. This require that you are using Event Listeners and set your desired particle system(s) to broadcast the event by enabling PlaygroundEventC.sendToManager.
///
public static event OnPlaygroundParticle particleEventCollision;
static bool particleEventCollisionInitialized = false;
///
/// The event of a particle sent by timer. This require that you are using Event Listeners and set your desired particle system(s) to broadcast the event by enabling PlaygroundEventC.sendToManager.
///
public static event OnPlaygroundParticle particleEventTime;
static bool particleEventTimeInitialized = false;
///
/// Sends the particle event birth.
///
/// Event particle.
public static void SendParticleEventBirth (PlaygroundEventParticle eventParticle) {
if (particleEventBirthInitialized)
particleEventBirth(eventParticle);
}
///
/// Sends the particle event death.
///
/// Event particle.
public static void SendParticleEventDeath (PlaygroundEventParticle eventParticle) {
if (particleEventDeathInitialized)
particleEventDeath(eventParticle);
}
///
/// Sends the particle event collision.
///
/// Event particle.
public static void SendParticleEventCollision (PlaygroundEventParticle eventParticle) {
if (particleEventCollisionInitialized)
particleEventCollision(eventParticle);
}
///
/// Sends the particle event time.
///
/// Event particle.
public static void SendParticleEventTime (PlaygroundEventParticle eventParticle) {
if (particleEventTimeInitialized)
particleEventTime(eventParticle);
}
/*************************************************************************************************************************************************
Playground cache
*************************************************************************************************************************************************/
///
/// Static reference to the Playground Manager script.
///
public static PlaygroundC reference;
///
/// Static reference to the Playground Manager Transform.
///
public static Transform referenceTransform;
///
/// Static reference to the Playground Manager GameObject.
///
public static GameObject referenceGameObject;
/*************************************************************************************************************************************************
Playground public variables
*************************************************************************************************************************************************/
///
/// The particle systems controlled by this Playground Manager.
///
[SerializeField]
public List particleSystems = new List();
///
/// The manipulators controlled by this Playground Manager.
///
[SerializeField]
public List manipulators = new List();
///
/// Maximum amount of emission positions in a PaintObject.
///
[HideInInspector] public int paintMaxPositions = 10000;
///
/// Calculate forces on PlaygroundParticlesC objects.
///
[HideInInspector] public bool calculate = true;
///
/// Color filtering mode.
///
[HideInInspector] public PIXELMODEC pixelFilterMode = PIXELMODEC.Pixel32;
///
/// Automatically parent a PlaygroundParticlesC object to Playground if it has no parent.
///
[HideInInspector] public bool autoGroup = true;
///
/// Turn this on if you want to build particles from 0 alpha pixels into states.
///
[HideInInspector] public bool buildZeroAlphaPixels = false;
///
/// Draw gizmos for manipulators and other particle system helpers in Scene View.
///
[HideInInspector] public bool drawGizmos = true;
///
/// Draw gizmos for source positions in Scene View.
///
[HideInInspector] public bool drawSourcePositions = false;
///
/// Should the Shuriken particle system component be visible? (This is just a precaution as editing Shuriken can lead to unexpected behavior).
///
[HideInInspector] public bool showShuriken = false;
///
/// Show toolbox in Scene View when Source is set to Paint on PlaygroundParticlesC objects.
///
[HideInInspector] public bool paintToolbox = true;
///
/// Scale of collision planes.
///
[HideInInspector] public float collisionPlaneScale = .1f;
///
/// Should snapshots be visible in the Hieararchy? (Enable this if you want to edit snapshots).
///
[HideInInspector] public bool showSnapshotsInHierarchy = false;
///
/// Should wireframes be rendered around particles in Scene View?
///
[HideInInspector] public bool drawWireframe = false;
///
/// Determines to draw previews of Playground Splines in Scene View.
///
[HideInInspector] public bool drawSplinePreview = true;
///
/// Determines if Time.timeScale should affect the particle systems simulation time. If disabled you can keep simulating particles in normal speed detached from the scene's time scale.
///
[HideInInspector] public bool globalTimeScale = true;
///
/// The thread pool method determines which thread pooling should be used.
/// ThreadPoolMethod.ThreadPool will use the .NET managed ThreadPool class (standard in Particle Playground in versions prior to 3).
/// ThreadPoolMethod.PlaygroundPool will use the self-managed PlaygroundQueue which queues tasks on reused threads (standard in Particle Playground 3 and up).
///
[HideInInspector] public ThreadPoolMethod threadPoolMethod = ThreadPoolMethod.PlaygroundPool;
///
/// The multithreading method Particle Playground should use. This determines how particle systems calculate over the CPU. Keep in mind each thread will generate memory garbage which will be collected at some point.
/// Selecting ThreadMethod.NoThreads will make particle systems calculate on the main-thread.
/// ThreadMethod.OnePerSystem will create one thread per particle system each frame.
/// ThreadMethod.OneForAll will bundle all calculations into one single thread.
/// ThreadMethod.Automatic will distribute all particle systems evenly bundled along available CPUs/cores. This is the recommended setting for most user cases.
///
[HideInInspector] public ThreadMethod threadMethod = ThreadMethod.Automatic;
[HideInInspector] public ThreadMethodComponent skinnedMeshThreadMethod = ThreadMethodComponent.InsideParticleCalculation;
[HideInInspector] public ThreadMethodComponent turbulenceThreadMethod = ThreadMethodComponent.InsideParticleCalculation;
///
/// The maximum amount of threads that can be created. The amount of created threads will never exceed available CPUs.
///
[HideInInspector] public int maxThreads = 8;
#if UNITY_WSA && !UNITY_EDITOR
#else
///
/// The Particle Playground-managed thread pool. The maxThreads value will determine how many threads will be available in the pool.
///
public static PlaygroundQueue playgroundPool;
#endif
bool isDoneThread = true;
bool isDoneThreadLocal = true;
bool isDoneThreadSkinned = true;
bool isDoneThreadTurbulence = true;
int threads;
int _prevMaxThreadCount;
static int processorCount;
static int activeThreads = 0;
static bool hasReference = false;
static bool hasPlaygroundPool = false;
/*************************************************************************************************************************************************
Playground private variables
*************************************************************************************************************************************************/
static System.Random random = new System.Random();
static object locker = new object();
private object lockerLocal = new object();
/*************************************************************************************************************************************************
Playground wrapper
*************************************************************************************************************************************************/
///
/// Creates a PlaygroundParticlesC object by standard prefab
///
public static PlaygroundParticlesC Particle () {
PlaygroundParticlesC playgroundParticles = ResourceInstantiate("Particle Playground System").GetComponent();
return playgroundParticles;
}
///
/// Creates an empty PlaygroundParticlesC object by script
///
/// The particle system instance.
public static PlaygroundParticlesC ParticleNew () {
PlaygroundParticlesC playgroundParticles = PlaygroundParticlesC.CreateParticleObject("Particle Playground System "+particlesQuantity,Vector3.zero,Quaternion.identity,1f,new Material(Shader.Find("Playground/Vertex Color")));
playgroundParticles.particleCache = new ParticleSystem.Particle[playgroundParticles.particleCount];
PlaygroundParticlesC.OnCreatePlaygroundParticles(playgroundParticles);
return playgroundParticles;
}
///
/// Creates a PlaygroundParticlesC object with an image state.
///
/// Image.
/// Name.
/// Position.
/// Rotation.
/// Offset.
/// Particle size.
/// Scale.
/// Material.
public static PlaygroundParticlesC Particle (Texture2D image, string name, Vector3 position, Quaternion rotation, Vector3 offset, float particleSize, float scale, Material material) {
return PlaygroundParticlesC.CreatePlaygroundParticles(new Texture2D[]{image},name,position,rotation,offset,particleSize,scale,material);
}
///
/// Creates a PlaygroundParticlesC object with an image state.
///
/// The particle system instance.
public static PlaygroundParticlesC Particle (Texture2D image) {
return PlaygroundParticlesC.CreatePlaygroundParticles(new Texture2D[]{image},"Particle Playground System "+particlesQuantity,Vector3.zero,Quaternion.identity,Vector3.zero,1f,1f,new Material(Shader.Find("Playground/Vertex Color")));
}
///
/// Creates a PlaygroundParticlesC object with several image states.
///
/// Images.
/// Name.
/// Position.
/// Rotation.
/// Offset.
/// Particle size.
/// Scale.
/// Material.
public static PlaygroundParticlesC Particle (Texture2D[] images, string name, Vector3 position, Quaternion rotation, Vector3 offset, float particleSize, float scale, Material material) {
return PlaygroundParticlesC.CreatePlaygroundParticles(images,name,position,rotation,offset,particleSize,scale,material);
}
///
/// Creates a PlaygroundParticlesC object with several image states.
///
/// Images.
public static PlaygroundParticlesC Particle (Texture2D[] images) {
return PlaygroundParticlesC.CreatePlaygroundParticles(images,"Particle Playground System "+particlesQuantity,Vector3.zero,Quaternion.identity,Vector3.zero,1f,1f,new Material(Shader.Find("Playground/Vertex Color")));
}
///
/// Creates a PlaygroundParticlesC object with a mesh state.
///
/// Mesh.
/// Texture.
/// Name.
/// Position.
/// Rotation.
/// Particle scale.
/// Offset.
/// Material.
public static PlaygroundParticlesC Particle (Mesh mesh, Texture2D texture, string name, Vector3 position, Quaternion rotation, float particleScale, Vector3 offset, Material material) {
return MeshParticles.CreateMeshParticles(new Mesh[]{mesh},new Texture2D[]{texture},null,name,position,rotation,particleScale,new Vector3[]{offset},material);
}
///
/// Creates a PlaygroundParticlesC object with a mesh state.
///
/// Mesh.
/// Texture.
public static PlaygroundParticlesC Particle (Mesh mesh, Texture2D texture) {
return MeshParticles.CreateMeshParticles(new Mesh[]{mesh},new Texture2D[]{texture},null,"Particle Playground System "+particlesQuantity,Vector3.zero,Quaternion.identity,1f,new Vector3[]{Vector3.zero},new Material(Shader.Find("Playground/Vertex Color")));
}
///
/// Creates a PlaygroundParticlesC object with several mesh states.
///
/// Meshes.
/// Textures.
/// Name.
/// Position.
/// Rotation.
/// Particle scale.
/// Offsets.
/// Material.
public static PlaygroundParticlesC Particle (Mesh[] meshes, Texture2D[] textures, string name, Vector3 position, Quaternion rotation, float particleScale, Vector3[] offsets, Material material) {
return MeshParticles.CreateMeshParticles(meshes,textures,null,name,position,rotation,particleScale,offsets,material);
}
///
/// Creates a PlaygroundParticlesC object with several mesh states.
///
/// Meshes.
/// Textures.
public static PlaygroundParticlesC Particle (Mesh[] meshes, Texture2D[] textures) {
return MeshParticles.CreateMeshParticles(meshes,textures,null,"Particle Playground System "+particlesQuantity,Vector3.zero,Quaternion.identity,1f,new Vector3[meshes.Length],new Material(Shader.Find("Playground/Vertex Color")));
}
///
/// Emits next particle - using the particle system as a pool (note that you need to set scriptedEmission-variables on beforehand using this method). Returns emitted particle number.
///
/// Playground particles.
public static int Emit (PlaygroundParticlesC playgroundParticles) {
return playgroundParticles.Emit(playgroundParticles.scriptedEmissionPosition,playgroundParticles.scriptedEmissionVelocity,playgroundParticles.scriptedEmissionColor);
}
///
/// Emits next particle while setting scriptedEmission data - using the particle system as a pool. Returns emitted particle number.
///
/// Playground particles.
/// Position.
/// Normal.
/// Color.
public static int Emit (PlaygroundParticlesC playgroundParticles, Vector3 position, Vector3 normal, Color color) {
return playgroundParticles.Emit(position,normal,color);
}
///
/// Sets emission on/off.
///
/// Playground particles.
/// If set to true set emission.
public static void Emit (PlaygroundParticlesC playgroundParticles, bool setEmission) {
playgroundParticles.Emit(setEmission);
}
///
/// Gets vertices and normals from a skinned world object in Vector3[] format (notice that the array is modified by reference).
///
/// Skinned World Object.
/// If set to true update normals.
public static void GetPosition (SkinnedWorldObject particleStateWorldObject, bool updateNormals) {
PlaygroundParticlesC.GetPosition(particleStateWorldObject, updateNormals);
}
///
/// Gets vertices from a world object in Vector3[] format (notice that the array is modified by reference).
///
/// Vertices.
///
public static void GetPosition (Vector3[] vertices, WorldObject particleStateWorldObject) {
PlaygroundParticlesC.GetPosition(vertices,particleStateWorldObject);
}
///
/// Gets normals from a world object in Vector3[] format (notice that the array is modified by reference).
///
/// Normals.
/// World Object.
public static void GetNormals (Vector3[] normals, WorldObject particleStateWorldObject) {
PlaygroundParticlesC.GetNormals(normals,particleStateWorldObject);
}
///
/// Sets alpha of particles instantly.
///
/// Playground particles.
/// Alpha.
public static void SetAlpha (PlaygroundParticlesC playgroundParticles, float alpha) {
PlaygroundParticlesC.SetAlpha(playgroundParticles,alpha);
}
///
/// Sets particle size.
///
/// Playground particles.
/// Size.
public static void SetSize (PlaygroundParticlesC playgroundParticles, float size) {
PlaygroundParticlesC.SetSize(playgroundParticles,size);
}
///
/// Translates all particles in Particle System.
///
/// Playground particles.
/// Direction.
public static void Translate (PlaygroundParticlesC playgroundParticles, Vector3 direction) {
PlaygroundParticlesC.Translate(playgroundParticles,direction);
}
///
/// Adds a single state.
///
/// Playground particles.
/// State.
public static void Add (PlaygroundParticlesC playgroundParticles, ParticleStateC state) {
PlaygroundParticlesC.Add(playgroundParticles,state);
}
///
/// Adds a single state image.
///
/// Playground particles.
/// Image.
/// Scale.
/// Offset.
/// State name.
public static void Add (PlaygroundParticlesC playgroundParticles, Texture2D image, float scale, Vector3 offset, string stateName) {
PlaygroundParticlesC.Add(playgroundParticles,image,scale,offset,stateName,null);
}
///
/// Adds a single state image with transform.
///
/// Playground particles.
/// Image.
/// Scale.
/// Offset.
/// State name.
/// State transform.
public static void Add (PlaygroundParticlesC playgroundParticles, Texture2D image, float scale, Vector3 offset, string stateName, Transform stateTransform) {
PlaygroundParticlesC.Add(playgroundParticles,image,scale,offset,stateName,stateTransform);
}
///
/// Adds a single state image with depthmap.
///
/// Playground particles.
/// Image.
/// Depthmap.
/// Depthmap strength.
/// Scale.
/// Offset.
/// State name.
public static void Add (PlaygroundParticlesC playgroundParticles, Texture2D image, Texture2D depthmap, float depthmapStrength, float scale, Vector3 offset, string stateName) {
PlaygroundParticlesC.Add(playgroundParticles,image,depthmap,depthmapStrength,scale,offset,stateName,null);
}
///
/// Adds single state image with depthmap and transform.
///
/// Playground particles.
/// Image.
/// Depthmap.
/// Depthmap strength.
/// Scale.
/// Offset.
/// State name.
/// State transform.
public static void Add (PlaygroundParticlesC playgroundParticles, Texture2D image, Texture2D depthmap, float depthmapStrength, float scale, Vector3 offset, string stateName, Transform stateTransform) {
PlaygroundParticlesC.Add(playgroundParticles,image,depthmap,depthmapStrength,scale,offset,stateName,stateTransform);
}
///
/// Adds a single state mesh.
///
/// Playground particles.
/// Mesh.
/// Scale.
/// Offset.
/// State name.
public static void Add (PlaygroundParticlesC playgroundParticles, Mesh mesh, float scale, Vector3 offset, string stateName) {
MeshParticles.Add(playgroundParticles,mesh,scale,offset,stateName,null);
}
///
/// Adds a single state mesh with transform.
///
/// Playground particles.
/// Mesh.
/// Scale.
/// Offset.
/// State name.
/// State transform.
public static void Add (PlaygroundParticlesC playgroundParticles, Mesh mesh, float scale, Vector3 offset, string stateName, Transform stateTransform) {
MeshParticles.Add(playgroundParticles,mesh,scale,offset,stateName,stateTransform);
}
///
/// Adds a single state mesh with texture.
///
/// Playground particles.
/// Mesh.
/// Texture.
/// Scale.
/// Offset.
/// State name.
public static void Add (PlaygroundParticlesC playgroundParticles, Mesh mesh, Texture2D texture, float scale, Vector3 offset, string stateName) {
MeshParticles.Add(playgroundParticles,mesh,texture,scale,offset,stateName,null);
}
///
/// Adds a single state mesh with texture and transform.
///
/// Playground particles.
/// Mesh.
/// Texture.
/// Scale.
/// Offset.
/// State name.
/// State transform.
public static void Add (PlaygroundParticlesC playgroundParticles, Mesh mesh, Texture2D texture, float scale, Vector3 offset, string stateName, Transform stateTransform) {
MeshParticles.Add(playgroundParticles,mesh,texture,scale,offset,stateName,stateTransform);
}
///
/// Adds a plane collider.
///
/// The PlaygroundColliderC.
/// Playground particles.
public static PlaygroundColliderC AddCollider (PlaygroundParticlesC playgroundParticles) {
PlaygroundColliderC pCollider = new PlaygroundColliderC();
playgroundParticles.colliders.Add(pCollider);
return pCollider;
}
///
/// Adds a plane collider and assign a transform.
///
/// The PlaygroundColliderC.
/// Playground particles.
/// Transform.
public static PlaygroundColliderC AddCollider (PlaygroundParticlesC playgroundParticles, Transform transform) {
PlaygroundColliderC pCollider = new PlaygroundColliderC();
pCollider.transform = transform;
playgroundParticles.colliders.Add(pCollider);
return pCollider;
}
///
/// Sets amount of particles for this Particle System.
///
/// Playground particles.
/// Amount.
public static void SetParticleCount (PlaygroundParticlesC playgroundParticles, int amount) {
PlaygroundParticlesC.SetParticleCount(playgroundParticles,amount);
}
///
/// Sets lifetime for this Particle System.
///
/// Playground particles.
/// Time.
public static void SetLifetime (PlaygroundParticlesC playgroundParticles, float time) {
PlaygroundParticlesC.SetLifetime(playgroundParticles,playgroundParticles.sorting,time);
}
///
/// Sets material for this Particle System.
///
/// Playground particles.
/// Particle material.
public static void SetMaterial (PlaygroundParticlesC playgroundParticles, Material particleMaterial) {
PlaygroundParticlesC.SetMaterial(playgroundParticles, particleMaterial);
}
///
/// Destroys the passed in Particle System.
///
/// Playground particles.
public static void Destroy (PlaygroundParticlesC playgroundParticles) {
PlaygroundParticlesC.Destroy(playgroundParticles);
}
///
/// Creates a world object reference (used for live world positioning of particles towards a mesh).
///
/// The object.
/// Mesh transform.
public static WorldObject WorldObject (Transform meshTransform) {
return PlaygroundParticlesC.NewWorldObject(meshTransform);
}
///
/// Creates a skinned world object reference (used for live world positioning of particles towards a mesh).
///
/// The world object.
/// Mesh transform.
public static SkinnedWorldObject SkinnedWorldObject (Transform meshTransform) {
return PlaygroundParticlesC.NewSkinnedWorldObject(meshTransform);
}
///
/// Creates a manipulator object.
///
/// The ManipulatorObjectC.
/// Type.
/// Affects.
/// Manipulator transform.
/// Size.
/// Strength.
public static ManipulatorObjectC ManipulatorObject (MANIPULATORTYPEC type, LayerMask affects, Transform manipulatorTransform, float size, float strength) {
return PlaygroundParticlesC.NewManipulatorObject(type,affects,manipulatorTransform,size,strength,null);
}
///
/// Creates a manipulator object by transform.
///
/// The ManipulatorObjectC.
/// Manipulator transform.
public static ManipulatorObjectC ManipulatorObject (Transform manipulatorTransform) {
LayerMask layerMask = -1;
return PlaygroundParticlesC.NewManipulatorObject(MANIPULATORTYPEC.Attractor,layerMask,manipulatorTransform,1f,1f,null);
}
///
/// Create a manipulator in a PlaygroundParticlesC object
///
/// The ManipulatorObjectC.
/// Type.
/// Affects.
/// Manipulator transform.
/// Size.
/// Strength.
/// Playground particles.
public static ManipulatorObjectC ManipulatorObject (MANIPULATORTYPEC type, LayerMask affects, Transform manipulatorTransform, float size, float strength, PlaygroundParticlesC playgroundParticles) {
return PlaygroundParticlesC.NewManipulatorObject(type,affects,manipulatorTransform,size,strength,playgroundParticles);
}
///
/// Creates a manipulator in a PlaygroundParticlesC object by transform.
///
/// The ManipulatorObjectC.
/// Manipulator transform.
/// Playground particles.
public static ManipulatorObjectC ManipulatorObject (Transform manipulatorTransform, PlaygroundParticlesC playgroundParticles) {
LayerMask layerMask = -1;
return PlaygroundParticlesC.NewManipulatorObject(MANIPULATORTYPEC.Attractor,layerMask,manipulatorTransform,1f,1f,playgroundParticles);
}
///
/// Returns a global manipulator in array position.
///
/// The ManipulatorObjectC.
/// The index.
public static ManipulatorObjectC GetManipulator (int i) {
if (reference.manipulators.Count>0 && reference.manipulators[i%reference.manipulators.Count]!=null)
return reference.manipulators[i%reference.manipulators.Count];
else return null;
}
///
/// Returns a manipulator in a PlaygroundParticlesC object in array position.
///
/// The ManipulatorObjectC.
/// The index.
/// Playground particles.
public static ManipulatorObjectC GetManipulator (int i, PlaygroundParticlesC playgroundParticles) {
if (playgroundParticles.manipulators.Count>0 && playgroundParticles.manipulators[i%playgroundParticles.manipulators.Count]!=null)
return playgroundParticles.manipulators[i%playgroundParticles.manipulators.Count];
else return null;
}
///
/// Returns all current particles within a local manipulator (in form of an Event Particle, however no event will be needed).
///
/// The manipulator particles.
/// Manipulator.
/// Playground particles.
public static List GetManipulatorParticles (int manipulator, PlaygroundParticlesC playgroundParticles) {
if (manipulator<0 || manipulator>=playgroundParticles.manipulators.Count) return null;
List particles = new List();
PlaygroundEventParticle particle = new PlaygroundEventParticle();
for (int i = 0; i
/// Returns all current particles within a global manipulator (in form of an Event Particle, however no event will be needed).
///
/// The manipulator particles.
/// Manipulator.
public static List GetManipulatorParticles (int manipulator) {
if (manipulator<0 || manipulator>=reference.manipulators.Count) return null;
List particles = new List();
PlaygroundEventParticle particle = new PlaygroundEventParticle();
for (int s = 0; s
/// Creates a new Playground Spline. The spline will be attached to a new GameObject in your scene by the name "Playground Spline".
///
/// The Playground Spline component on the created GameObject.
public static PlaygroundSpline CreateSpline () {
GameObject splineGO = new GameObject("Playground Spline", typeof(PlaygroundSpline));
return (PlaygroundSpline)splineGO.GetComponent(typeof(PlaygroundSpline));
}
///
/// Creates a new Playground Spline. The spline will be attached to a new GameObject in your scene by the name "Playground Spline" which is parented to the passed in Particle Playground system.
/// The Particle Playground system will have the source spline automatically set.
///
/// The Playground Spline component on the created GameObject.
/// Particle Playground system.
public static PlaygroundSpline CreateSpline (PlaygroundParticlesC playgroundParticles) {
PlaygroundSpline spline = CreateSpline();
spline.Reset();
if (playgroundParticles.splines.Count==1 && playgroundParticles.splines[0]==null)
playgroundParticles.splines[0] = spline;
else
playgroundParticles.splines.Add (spline);
spline.transform.parent = playgroundParticles.particleSystemTransform;
spline.transform.localPosition = Vector3.zero;
spline.name += " "+playgroundParticles.splines.Count.ToString();
spline.AddUser(playgroundParticles.particleSystemTransform);
return spline;
}
public static PlaygroundSpline CreateSpline (ManipulatorPropertyC manipulatorProperty) {
PlaygroundSpline spline = CreateSpline();
spline.Reset();
manipulatorProperty.splineTarget = spline;
return spline;
}
///
/// Creates an empty event.
///
/// The event.
public static PlaygroundEventC CreateEvent () {
return new PlaygroundEventC();
}
///
/// Creates an event into passed particle system.
///
/// The event.
/// Particle Playground system.
public static PlaygroundEventC CreateEvent (PlaygroundParticlesC playgroundParticles) {
if (playgroundParticles==null) return null;
if (playgroundParticles.events==null)
playgroundParticles.events = new List();
playgroundParticles.events.Add (new PlaygroundEventC());
return playgroundParticles.events[playgroundParticles.events.Count-1];
}
///
/// Returns an event from PlaygroundParticlesC object in array position.
///
/// The event.
/// The index.
/// Particle Playground system.
public static PlaygroundEventC GetEvent (int i, PlaygroundParticlesC playgroundParticles) {
if (playgroundParticles.events.Count>0 && playgroundParticles.events[i%playgroundParticles.events.Count]!=null)
return playgroundParticles.events[i%playgroundParticles.events.Count];
else return null;
}
///
/// Removes the event.
///
/// The index.
/// Playground particles.
public static void RemoveEvent (int i, PlaygroundParticlesC playgroundParticles) {
i = i%playgroundParticles.events.Count;
if (playgroundParticles.events.Count>0 && playgroundParticles.events[i]!=null) {
if (playgroundParticles.events[i].target!=null) {
for (int x = 0; x
/// Returns a Particle Playground System in array position.
///
/// The particles.
/// The index.
public static PlaygroundParticlesC GetParticles (int i) {
if (reference.particleSystems.Count>0 && reference.particleSystems[i%reference.particleSystems.Count]!=null)
return reference.particleSystems[i%reference.particleSystems.Count];
else return null;
}
///
/// Creates a projection object reference.
///
/// The projection.
/// Playground particles.
public static ParticleProjectionC ParticleProjection (PlaygroundParticlesC playgroundParticles) {
return PlaygroundParticlesC.NewProjectionObject(playgroundParticles);
}
///
/// Creates a paint object reference.
///
/// The object.
/// Playground particles.
public static PaintObjectC PaintObject (PlaygroundParticlesC playgroundParticles) {
return PlaygroundParticlesC.NewPaintObject(playgroundParticles);
}
///
/// Live paints into a PlaygroundParticlesC PaintObject's positions.
///
/// Playground particles.
/// Position.
/// Normal.
/// Parent.
/// Color.
public static int Paint (PlaygroundParticlesC playgroundParticles, Vector3 position, Vector3 normal, Transform parent, Color32 color) {
return playgroundParticles.paint.Paint(position,normal,parent,color);
}
///
/// Live paints into a PaintObject's positions directly.
///
/// Paint object.
/// Position.
/// Normal.
/// Parent.
/// Color.
public static void Paint (PaintObjectC paintObject, Vector3 position, Vector3 normal, Transform parent, Color32 color) {
paintObject.Paint(position,normal,parent,color);
}
///
/// Live erases into a PlaygroundParticlesC PaintObject's positions, returns true if position was erased.
///
/// Playground particles.
/// Position.
/// Radius.
public static bool Erase (PlaygroundParticlesC playgroundParticles, Vector3 position, float radius) {
return playgroundParticles.paint.Erase(position,radius);
}
///
/// Live erases into a PaintObject's positions directly, returns true if position was erased.
///
/// Paint object.
/// Position.
/// Radius.
public static bool Erase (PaintObjectC paintObject, Vector3 position, float radius) {
return paintObject.Erase(position,radius);
}
///
/// Live erases into a PlaygroundParticlesC PaintObject's using a specified index, returns true if position was erased.
///
/// Playground particles.
/// Index.
public static bool Erase (PlaygroundParticlesC playgroundParticles, int index) {
return playgroundParticles.paint.Erase(index);
}
///
/// Clears out paint in a PlaygroundParticlesC object.
///
/// Playground particles.
public static void ClearPaint (PlaygroundParticlesC playgroundParticles) {
if (playgroundParticles.paint!=null)
playgroundParticles.paint.ClearPaint();
}
///
/// Gets the amount of paint positions in this PlaygroundParticlesC PaintObject.
///
/// The paint position length.
/// Playground particles.
public static int GetPaintPositionLength (PlaygroundParticlesC playgroundParticles) {
return playgroundParticles.paint.positionLength;
}
///
/// Sets initial target position for this Particle System.
///
/// Playground particles.
/// Position.
public static void SetInitialTargetPosition (PlaygroundParticlesC playgroundParticles, Vector3 position) {
PlaygroundParticlesC.SetInitialTargetPosition(playgroundParticles,position, true);
}
///
/// Sets emission for this Particle System.
///
/// Playground particles.
/// If set to true emit.
public static void Emission (PlaygroundParticlesC playgroundParticles, bool emit) {
PlaygroundParticlesC.Emission(playgroundParticles,emit,false);
}
///
/// Set emission for this Particle System controlling to run rest emission
///
/// Playground particles.
/// If set to true emit.
/// If set to true rest emission.
public static void Emission (PlaygroundParticlesC playgroundParticles, bool emit, bool restEmission) {
PlaygroundParticlesC.Emission(playgroundParticles,emit,restEmission);
}
///
/// Clears out this Particle System.
///
/// Playground particles.
public static void Clear (PlaygroundParticlesC playgroundParticles) {
PlaygroundParticlesC.Clear(playgroundParticles);
}
///
/// Refreshes source scatter for this Particle System.
///
/// Playground particles.
public static void RefreshScatter (PlaygroundParticlesC playgroundParticles) {
playgroundParticles.RefreshScatter();
}
///
/// Instantiates a preset by name reference.
/// Any preset you wish to instantiate using the InstantiatePreset method needs to be in a 'Resources/Presets/' folder.
///
/// The preset as a PlaygroundParticlesC object.
/// Preset name.
public static PlaygroundParticlesC InstantiatePreset (string presetName) {
GameObject presetGo = ResourceInstantiate("Presets/"+presetName);
PlaygroundParticlesC presetParticles = presetGo.GetComponent();
if (presetParticles!=null) {
if (reference==null)
reference = PlaygroundC.ResourceInstantiate("Playground Manager").GetComponent();
if (reference) {
if (reference.autoGroup && presetParticles.particleSystemTransform.parent==null)
presetParticles.particleSystemTransform.parent = referenceTransform;
particlesQuantity++;
presetParticles.particleSystemId = particlesQuantity-1;
}
presetGo.name = presetName;
return presetParticles;
} else {
if (presetGo.name.Contains("Presets/"))
presetGo.name = presetGo.name.Remove(0, 8);
return null;
}
}
///
/// Instantiates a preset by category and name reference. The category is the name of the folder.
/// Any preset you wish to instantiate using this InstantiatePreset overload needs to be in a 'Resources/Presets/categoryName/' folder.
///
/// The preset as a PlaygroundParticlesC object.
/// Category name.
/// Preset name.
public static PlaygroundParticlesC InstantiatePreset (string categoryName, string presetName)
{
return InstantiatePreset(categoryName+"/"+presetName);
}
///
/// Determines if the Playground Manager has its reference assigned.
///
/// true if having a reference; otherwise, false.
public static bool HasReference () {
return hasReference;
}
///
/// Determines if the Playground Manager has a Playground Pool assigned.
///
/// true if having a Playground Pool; otherwise, false.
public static bool HasPlaygroundPool () {
return hasPlaygroundPool;
}
///
/// Determines whether the thread for threadMethod if set to ThreadMethod.OneForAll is finished. This is always true when any other method is selected.
///
/// true if the OneForAll thread is finished; otherwise, false.
public bool IsDoneThread () {
return isDoneThread;
}
///
/// Determines whether the thread for turbulence is done.
///
/// true if thread for turbulence is done; otherwise, false.
public bool IsDoneThreadTurbulence () {
return isDoneThreadTurbulence;
}
///
/// Determines whether the thread for skinned meshes is done.
///
/// true if the thread for skinned meshes is done; otherwise, false.
public bool IsDoneThreadSkinnedMeshes () {
return isDoneThreadSkinned;
}
///
/// Determines whether the multithreading is within the initial first unsafe frames.
///
/// true if it is the first unsafe automatic frames; otherwise, false.
public bool IsFirstUnsafeAutomaticFrames () {
return isFirstUnsafeAutomaticFrames;
}
///
/// Determines whether there is enabled global manipulators which should be calculated.
///
/// true if there is enabled global manipulators; otherwise, false.
public bool HasEnabledGlobalManipulators () {
if (manipulators.Count>0) {
for (int i = 0; i
/// Returns pixels from a texture.
///
/// The pixels.
/// Image.
public static Color32[] GetPixels (Texture2D image) {
if (image == null) return null;
if (reference && reference.pixelFilterMode==PIXELMODEC.Bilinear) {
Color32[] pixels = new Color32[image.width*image.height];
for (int y = 0; y
/// Returns a random vector3-array.
///
/// The vector3.
/// Length.
/// Minimum.
/// Max.
public static Vector3[] RandomVector3 (int length, Vector3 min, Vector3 max) {
Vector3[] v3 = new Vector3[length];
for (int i = 0; i
/// Returns a float array by random values.
///
/// The float.
/// Length.
/// Minimum.
/// Max.
public static float[] RandomFloat (int length, float min, float max) {
float[] f = new float[length];
for (int i = 0; i
/// Shuffles an existing built-in float array.
///
/// Arr.
public static void ShuffleArray (float[] arr) {
int r;
float tmp;
for (int i = arr.Length - 1; i > 0; i--) {
r = random.Next(0,i);
tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
///
/// Shuffles an existing built-in int array.
///
/// Arr.
public static void ShuffleArray (int[] arr) {
int r;
int tmp;
for (int i = arr.Length - 1; i > 0; i--) {
r = random.Next(0,i);
tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
///
/// Compares and returns the largest number in an int array.
///
/// Ints to compare.
public static int Largest (int[] compare) {
int largest = 0;
for (int i = 0; ilargest) largest = i;
return largest;
}
///
/// Counts the completely transparent pixels in a Texture2D.
///
/// The zero alphas in texture.
/// Image.
public static int CountZeroAlphasInTexture (Texture2D image) {
int alphaCount = 0;
Color32[] pixels = image.GetPixels32();
for (int x = 0; x
/// Instantiates from Resources.
///
/// The instantiate.
/// N.
public static GameObject ResourceInstantiate (string n) {
GameObject res = UnityEngine.Resources.Load(n) as GameObject;
if (!res)
return null;
GameObject go = Instantiate(res) as GameObject;
go.name = n;
return go;
}
/*************************************************************************************************************************************************
Playground Manager
*************************************************************************************************************************************************/
///
/// Reset time
///
public static void TimeReset () {
globalDeltaTime = .0f;
#if UNITY_EDITOR
if (!UnityEditor.EditorApplication.isPlaying) {
globalTime = 0f;
} else
globalTime = Time.timeSinceLevelLoad;
#else
globalTime = Time.timeSinceLevelLoad;
#endif
lastTimeUpdated = globalTime;
}
///
/// Initializes the Playground Manager.
///
public IEnumerator InitializePlayground () {
// Check for duplicates of the Playground Manager
if (reference!=null && reference!=this) {
yield return null;
Debug.Log("There can only be one instance of the Playground Manager in the scene.");
// Save all children!
foreach (Transform child in transform)
child.parent = null;
DestroyImmediate(gameObject);
yield break;
} else if (reference==null)
reference = this;
// Check events availability
CheckEvents();
// New random
random = new System.Random();
// Reset time
TimeReset();
// Remove any null particle systems
for (int i = 0; i
/// Updates the global time.
///
public static void SetTime () {
// Set time
if (!Application.isPlaying || !reference.globalTimeScale)
globalTime += (Time.realtimeSinceStartup-lastTimeUpdated)*globalTimescale;
else
globalTime += (Time.deltaTime)*globalTimescale;
// Set delta time
globalDeltaTime = globalTime-lastTimeUpdated;
// Set interval stamp
lastTimeUpdated = globalTime;
}
///
/// Sets the maximum threads allowed. When using Thread Pool Method: Playground Pool this will set the amount of reused threads.
///
/// The amount of threads.
public static void SetMaxThreads (int threadCount) {
if (!HasReference ())
return;
reference.maxThreads = Mathf.Clamp (threadCount, 1, 128);
processorCount = SystemInfo.processorCount;
reference.threads = Mathf.Clamp (processorCount>1?processorCount-1:1, 1, reference.maxThreads);
reference._prevMaxThreadCount = reference.maxThreads;
// Resize the Playground Pool if necessary
#if UNITY_WSA && !UNITY_EDITOR
#else
if (reference.threadPoolMethod == ThreadPoolMethod.PlaygroundPool && playgroundPool != null)
playgroundPool.SetThreadPool(reference.maxThreads);
#endif
}
static void CheckEvents () {
particleEventBirthInitialized = particleEventBirth!=null;
particleEventDeathInitialized = particleEventDeath!=null;
particleEventCollisionInitialized = particleEventCollision!=null;
particleEventTimeInitialized = particleEventTime!=null;
}
/*************************************************************************************************************************************************
// MonoBehaviours
*************************************************************************************************************************************************/
// Initializes the Playground Manager.
// OnEnable is called in both Edit- and Play Mode.
void OnEnable () {
// Cache the Playground reference
referenceTransform = transform;
referenceGameObject = gameObject;
// Initialize
StartCoroutine(InitializePlayground());
}
// Set initial time
void Start () {SetTime();}
///
/// LateUpdate will prepare and call for calculations on each particle system.
/// All threaded calculation is done after Update to ensure stable movement of particles.
///
void LateUpdate () {
activeThreads = 0;
if (activeSystems.Count>0)
activeSystems.Clear();
frameCount++;
isFirstUnsafeAutomaticFrames = frameCount particleSystems.Count) {
if (i>0) {
i--;
currentParticleSystemCount = particleSystems.Count;
} else {hasActiveParticleSystems=false; return;}
} else if (currentParticleSystemCount < particleSystems.Count) {
currentParticleSystemCount = particleSystems.Count;
}
if (particleSystems.Count==0 || i>=particleSystems.Count) {hasActiveParticleSystems=false; return;}
// Update the main camera frustum planes (this is used for culling particle systems)
if (!frustumPlanesSet && particleSystems[i].pauseCalculationWhenInvisible && mainCamera!=null && mainCamera.enabled) {
frustumPlanes = GeometryUtility.CalculateFrustumPlanes(mainCamera);
frustumPlanesSet = true;
}
// Update any particle system using onlySourcePositioning or onlyLifetimePositioning
if (particleSystems[i].onlySourcePositioning||particleSystems[i].onlyLifetimePositioning)
if (!particleSystems[i].UpdateSystem())
continue;
// Update any changes. Particle system may also be removed here.
if (particleSystems.Count>0 && i0 && i
/// Update will sync and put all particles into the Shuriken component of each particle system.
/// This runs before the threaded calculations as we otherwise experience teared presentation of their movement.
///
void Update () {
#if UNITY_WSA && !UNITY_EDITOR
// Playground Pool is not compatible with Windows Store/Universal, fall back to the .NET Thread Pool
threadPoolMethod = ThreadPoolMethod.ThreadPool;
#endif
int currentParticleSystemCount = particleSystems.Count;
for (int i = 0; i particleSystems.Count) {
if (i>0) {
i--;
currentParticleSystemCount = particleSystems.Count;
} else {hasActiveParticleSystems=false; return;}
} else if (currentParticleSystemCount < particleSystems.Count) {
currentParticleSystemCount = particleSystems.Count;
}
if (particleSystems.Count==0 || i>=particleSystems.Count) {hasActiveParticleSystems=false; return;}
// Update Shuriken
if (particleSystems[i]!=null &&
!particleSystems[i].onlySourcePositioning &&
!particleSystems[i].onlyLifetimePositioning &&
particleSystems[i].UpdateSystem() &&
particleSystems[i].isReadyForThreadedCalculations &&
!particleSystems[i].InTransition() &&
!particleSystems[i].IsLoading() &&
!particleSystems[i].IsSettingParticleTime() &&
particleSystems[i].IsReady() &&
!particleSystems[i].inPlayback) {
particleSystems[i].UpdateShuriken();
}
}
}
#if UNITY_EDITOR
void RefreshHieararchy () {
UnityEditor.EditorApplication.RepaintHierarchyWindow();
}
#endif
bool hasActiveParticleSystems = false;
bool hasLocalNoThreads = false;
bool hasLocalOnePerSystem = false;
bool hasLocalOneForAll = false;
bool hasActiveSkinnedMeshes = false;
bool hasActiveTurbulence = false;
bool isFirstUnsafeAutomaticFrames = true;
int threadAggregatorRuns = 0;
List activeSystems = new List();
ThreadMethod previousThreadMethod;
ThreadMethodComponent previousSkinnedMeshThreadMethod;
ThreadMethodComponent previousTurbulenceThreadMethod;
///
/// Returns the amount of current active threads created.
///
/// The thread amount.
public static int ActiveThreads () {
return activeThreads;
}
public static int ProcessorCount () {
return processorCount;
}
///
/// Controls the different methods of distributing calculation threads.
///
void ThreadAggregator () {
// Run skinned mesh calculation
if (hasActiveSkinnedMeshes) {
switch (skinnedMeshThreadMethod) {
case ThreadMethodComponent.InsideParticleCalculation:
// Skinned meshes will be prepared inside the particle system's calculation loop before its particles.
// This doesn't mean that it is calculated on the main-thread unless PlaygroundC.threadMethod is set to NoThreads or PlaygroundParticlesC.forceSkinnedMeshUpdateOnMainThread is enabled.
break;
case ThreadMethodComponent.OnePerSystem:
for(int i = 0; i{
if (isDoneThreadSkinned) return;
for(int i = 0; i{
if (isDoneThreadTurbulence) return;
for(int i = 0; i{
if (isDoneThreadLocal) return;
lock (lockerLocal) {
for(int i = 0; i{
if (isDoneThread) return;
lock (locker) {
for(int i = 0; i1?processorCount-1:1, 1, maxThreads);
// Particle systems less than processors
if (activeSystems.Count<=threads) {
for(int i = 0; i
/// Runs an action asynchrounously on a second thread. This overload is only accessible for Windows Store/Universal compatibility. Use a lambda expression to pass data to another thread.
///
/// The action.
public static void RunAsync (Action a) {
activeThreads++;
System.Threading.Tasks.Task.Run(() => a());
}
public static void RunAsync (Action a, ThreadPoolMethod threadPoolMethod) {
activeThreads++;
System.Threading.Tasks.Task.Run(() => a());
}
#else
///
/// Runs an action asynchrounously on a second thread. Use a lambda expression to pass data to another thread.
///
/// The action.
public static void RunAsync (Action a, ThreadPoolMethod threadPoolMethod) {
#if UNITY_WEBGL && !UNITY_EDITOR
a();
#elif UNITY_WSA && !UNITY_EDITOR
lock (locker)
ThreadPool.QueueUserWorkItem(RunAction, a);
#else
if (threadPoolMethod == ThreadPoolMethod.ThreadPool)
lock (locker)
ThreadPool.QueueUserWorkItem(RunAction, a);
else
RunAsyncPlaygroundPool(a);
#endif
}
public static void RunAsync (Action a) {
#if UNITY_WEBGL && !UNITY_EDITOR
a();
#elif UNITY_WSA && !UNITY_EDITOR
lock (locker)
ThreadPool.QueueUserWorkItem(RunAction, a);
#else
if (!HasReference() || reference.threadPoolMethod == ThreadPoolMethod.ThreadPool)
lock (locker)
ThreadPool.QueueUserWorkItem(RunAction, a);
else
RunAsyncPlaygroundPool(a);
#endif
}
public static void RunAsyncPlaygroundPool (Action a) {
#if UNITY_WEBGL && !UNITY_EDITOR
a();
#else
if (!HasPlaygroundPool())
{
playgroundPool = new PlaygroundQueue(HasReference()?reference.maxThreads : SystemInfo.processorCount*2, RunAction);
hasPlaygroundPool = true;
}
playgroundPool.EnqueueTask(a);
#endif
}
#endif
private static void RunAction (object a) {
try {
((Action)a)();
} catch {}
}
// Reset time when turning back to the editor
#if UNITY_EDITOR
public void OnApplicationPause (bool pauseStatus) {
if (!pauseStatus && !UnityEditor.EditorApplication.isPlaying) {
TimeReset();
foreach(PlaygroundParticlesC p in particleSystems) {
if (!p.isSnapshot && !p.IsLoading() && !p.IsYieldRefreshing()) {
p.Start();
}
}
}
}
#endif
}
#if UNITY_WSA && !UNITY_EDITOR
#else
///
/// The Playground Queue class is a self-managed thread pool which consumes actions sent into EnqueueTask(Action).
///
public class PlaygroundQueue : IDisposable where T : class
{
readonly object _locker = new object();
private List _workers;
readonly Queue _taskQueue = new Queue();
readonly Action _dequeueAction;
///
/// Initializes a new instance of the class.
///
/// The amount of worker threads.
/// The dequeue action.
public PlaygroundQueue(int workerCount, Action dequeueAction)
{
_dequeueAction = dequeueAction;
_workers = new List(workerCount);
// Create and start a separate thread for each worker
for (int i = 0; i0;
}
public bool HasTasks ()
{
return _taskQueue.Count>0;
}
public int ThreadPoolCount ()
{
return _workers.Count;
}
public int TaskCount ()
{
return _taskQueue.Count;
}
///
/// Resizes the thread pool.
///
/// The amount of available threads in the pool.
public void SetThreadPool (int amount)
{
if (amount == _workers.Count)
return;
amount = Mathf.Clamp (amount, 1, 128);
if (amount > _workers.Count)
{
for (int i = _workers.Count; i(amount);
for (int i = 0; i
/// Enqueues an asynchronous task to run on a separate thread.
///
/// The task to be run on a separate thread.
public void EnqueueTask (T task)
{
lock (_locker)
{
_taskQueue.Enqueue(task);
Monitor.Pulse(_locker);
}
}
///
/// Consumes the work in the task queue.
///
void Consume ()
{
while (true)
{
T item;
lock (_locker)
{
while (_taskQueue.Count == 0)
Monitor.Wait(_locker);
item = _taskQueue.Dequeue();
}
if (item == null)
return;
// Run the action
_dequeueAction(item);
}
}
///
/// Disposes all worker threads.
///
public void Dispose()
{
_workers.ForEach(thread => EnqueueTask(null));
_workers.ForEach(thread => thread.Join());
}
}
#endif
///
/// Holds information about a Paint source.
///
[Serializable]
public class PaintObjectC {
///
/// Position data for each origin point.
///
[HideInInspector] public List paintPositions;
///
/// The current length of position array.
///
[HideInInspector] public int positionLength;
///
/// The last painted position.
///
[HideInInspector] public Vector3 lastPaintPosition;
///
/// The collider type this PaintObject sees when painting.
///
[HideInInspector] public COLLISIONTYPEC collisionType;
///
/// Minimum depth for 2D collisions.
///
public float minDepth = -1f;
///
/// Maximum depth for 2D collisions.
///
public float maxDepth = 1f;
///
/// The required space between the last and current paint position.
///
public float spacing;
///
/// The layers this PaintObject sees when painting.
///
public LayerMask layerMask = -1;
///
/// The brush data for this PaintObject.
///
public PlaygroundBrushC brush;
///
/// Should painting stop when paintPositions is equal to maxPositions (if false paint positions will be removed from list when painting new ones).
///
public bool exceedMaxStopsPaint;
///
/// Is this PaintObject initialized yet?
///
public bool initialized = false;
///
/// Initializes a PaintObject for painting.
///
public void Initialize () {
paintPositions = new List();
brush = new PlaygroundBrushC();
lastPaintPosition = PlaygroundC.initialTargetPosition;
initialized = true;
}
///
/// Live paints into this PaintObject using a Ray and color information.
///
/// Ray.
/// Color.
public bool Paint (Ray ray, Color32 color) {
if (collisionType==COLLISIONTYPEC.Physics3D) {
RaycastHit hit;
if (Physics.Raycast(ray, out hit, brush.distance, layerMask)) {
Paint(hit.point, hit.normal, hit.transform, color);
lastPaintPosition = hit.point;
return true;
}
} else {
RaycastHit2D hitInfo2D = Physics2D.Raycast(ray.origin, ray.direction, brush.distance, layerMask, minDepth, maxDepth);
if (hitInfo2D.collider!=null) {
Paint(hitInfo2D.point, hitInfo2D.normal, hitInfo2D.transform, color);
lastPaintPosition = hitInfo2D.point;
return true;
}
}
return false;
}
///
/// Live paints into this PaintObject (single point with information about position, normal, parent and color), returns current painted index.
///
/// Position.
/// Normal.
/// Parent.
/// Color.
public int Paint (Vector3 pos, Vector3 norm, Transform parent, Color32 color) {
PaintPositionC pPos = new PaintPositionC();
if (parent) {
pPos.parent = parent;
pPos.initialPosition = parent.InverseTransformPoint(pos);
pPos.initialNormal = parent.InverseTransformDirection(norm);
} else {
pPos.initialPosition = pos;
pPos.initialNormal = norm;
}
pPos.color = color;
pPos.position = pPos.initialPosition;
paintPositions.Add(pPos);
positionLength = paintPositions.Count;
if (!exceedMaxStopsPaint && positionLength>PlaygroundC.reference.paintMaxPositions) {
paintPositions.RemoveAt(0);
positionLength = paintPositions.Count;
}
return positionLength-1;
}
///
/// Removes painted positions in this PaintObject using a position and radius, returns true if position was erased.
///
/// Position.
/// Radius.
public bool Erase (Vector3 pos, float radius) {
bool erased = false;
if (paintPositions.Count==0) return false;
for (int i = 0; i
/// Removes painted positions in this PaintObject using a specified index, returns true if position at index was found and removed.
///
/// Index.
public bool Erase (int index) {
if (index>=0 && index
/// Returns position at index of PaintObject's PaintPosition.
///
/// The position.
/// Index.
public Vector3 GetPosition (int index) {
index=index%positionLength;
return paintPositions[index].position;
}
///
/// Returns color at index of PaintObject's PaintPosition.
///
/// The color.
/// Index.
public Color32 GetColor (int index) {
index=index%positionLength;
return paintPositions[index].color;
}
///
/// Returns normal at index of PaintObject's PaintPosition.
///
/// The normal.
/// Index.
public Vector3 GetNormal (int index) {
index=index%positionLength;
return paintPositions[index].initialNormal;
}
///
/// Returns parent at index of PaintObject's PaintPosition.
///
/// The parent.
/// Index.
public Transform GetParent (int index) {
index=index%positionLength;
return paintPositions[index].parent;
}
///
/// Returns rotation of parent at index of PaintObject's PaintPosition.
///
/// The rotation.
/// Index.
public Quaternion GetRotation (int index) {
index=index%positionLength;
return paintPositions[index].parentRotation;
}
///
/// Live positioning of paintPositions regarding their parent.
/// This happens automatically in PlaygroundParticlesC.Update() - only use this if you need to set all positions at once.
///
public void Update () {
for (int i = 0; i
/// Updates specific position.
///
/// This position.
public void Update (int thisPosition) {
thisPosition = thisPosition%positionLength;
paintPositions[thisPosition].position = paintPositions[thisPosition].parent.TransformPoint(paintPositions[thisPosition].initialPosition);
paintPositions[thisPosition].parentRotation = paintPositions[thisPosition].parent.rotation;
}
///
/// Clears out all emission positions where the parent transform has been removed.
///
public void RemoveNonParented () {
for (int i = 0; i
/// Clears out emission position where the parent transform has been removed.
/// Returns true if this position didn't have a parent.
///
/// true, if non parented was removed, false otherwise.
/// This position.
public bool RemoveNonParented (int thisPosition) {
thisPosition = thisPosition%positionLength;
if (paintPositions[thisPosition].parent==null) {
paintPositions.RemoveAt(thisPosition);
return true;
}
return false;
}
///
/// Clears out the painted positions.
///
public void ClearPaint () {
paintPositions = new List();
positionLength = 0;
}
///
/// Clones this PaintObject.
///
public PaintObjectC Clone () {
PaintObjectC paintObject = new PaintObjectC();
if (paintPositions!=null && paintPositions.Count>0) {
paintObject.paintPositions = new List();
paintObject.paintPositions.AddRange(paintPositions);
}
paintObject.positionLength = positionLength;
paintObject.lastPaintPosition = lastPaintPosition;
paintObject.spacing = spacing;
paintObject.layerMask = layerMask;
paintObject.collisionType = collisionType;
if (brush!=null)
paintObject.brush = brush.Clone();
else
paintObject.brush = new PlaygroundBrushC();
paintObject.exceedMaxStopsPaint = exceedMaxStopsPaint;
paintObject.initialized = initialized;
return paintObject;
}
}
///
/// Constructor for a painted position.
///
[Serializable]
public class PaintPositionC {
///
/// Emission spot in local position of parent.
///
public Vector3 position;
///
/// Color of emission spot.
///
public Color32 color;
///
/// The parent transform.
///
public Transform parent;
///
/// The first position where this originally were painted.
///
public Vector3 initialPosition;
///
/// The first normal direction when painted.
///
public Vector3 initialNormal;
///
/// The rotation of the parent.
///
public Quaternion parentRotation;
}
///
/// Holds information about a brush used for source painting.
///
[Serializable]
public class PlaygroundBrushC {
///
/// The texture to construct this Brush from.
///
public Texture2D texture;
///
/// The scale of this Brush (measured in Units).
///
public float scale = 1f;
///
/// The detail level of this brush.
///
public BRUSHDETAILC detail = BRUSHDETAILC.High;
///
/// The distance the brush reaches.
///
public float distance = 10000;
///
/// Color data of this brush.
///
[HideInInspector] public Color32[] color;
///
/// The length of color array.
///
[HideInInspector] public int colorLength;
///
/// Sets the texture of this brush.
///
/// New texture.
public void SetTexture (Texture2D newTexture) {
texture = newTexture;
Construct();
}
///
/// Caches the color information from this brush.
///
public void Construct () {
color = PlaygroundC.GetPixels(texture);
if (color!=null)
colorLength = color.Length;
}
///
/// Returns color at index of Brush.
///
/// The color.
/// Index.
public Color32 GetColor (int index) {
index=index%colorLength;
return color[index];
}
///
/// Sets color at index of Brush.
///
/// Color.
/// Index.
public void SetColor (Color32 c, int index) {
color[index] = c;
}
///
/// Clones this PlaygroundBrush.
///
public PlaygroundBrushC Clone () {
PlaygroundBrushC playgroundBrush = new PlaygroundBrushC();
playgroundBrush.texture = texture;
playgroundBrush.scale = scale;
playgroundBrush.detail = detail;
playgroundBrush.distance = distance;
if (playgroundBrush.color!=null)
playgroundBrush.color = color.Clone() as Color32[];
playgroundBrush.colorLength = colorLength;
return playgroundBrush;
}
}
///
/// Holds information about a State source.
///
[Serializable]
public class ParticleStateC {
///
/// Color data.
///
private Color32[] color;
///
/// Position data.
///
private Vector3[] position;
///
/// Normal data.
///
private Vector3[] normals;
///
/// The texture to construct this state from (used to color each vertex if mesh is used).
///
public Texture2D stateTexture;
///
/// The texture to use as depthmap for this state. A grayscale image of the same size as stateTexture is required.
///
public Texture2D stateDepthmap;
///
/// How much the grayscale from stateDepthmap will affect z-value.
///
public float stateDepthmapStrength = 1f;
///
/// The mesh used to set this state's positions. Positions will be calculated per vertex.
///
public Mesh stateMesh;
///
/// The name of this state.
///
public string stateName;
///
/// The scale of this state (measured in units).
///
public float stateScale = 1f;
///
/// The offset of this state in world position (measured in units).
///
public Vector3 stateOffset;
///
/// The transform that act as parent to this state.
///
public Transform stateTransform;
public Matrix4x4 stateTransformMx = new Matrix4x4();
public ScaleMethod stateScaleMethod;
///
/// Is this ParticleState intialized?
///
[NonSerialized] public bool initialized = false;
///
/// The length of color array.
///
[HideInInspector] public int colorLength;
///
/// The length of position array.
///
[HideInInspector] public int positionLength;
[HideInInspector] public bool applyChromaKey;
[HideInInspector] public Color32 chromaKey;
[HideInInspector] public float chromaKeySpread;
bool isInitializing = false;
///
/// Determines whether this State is initializing. This is used for multithreading to determine if a State's Initialize() function is being executed.
///
/// true if this State is initializing; otherwise, false.
public bool IsInitializing () {
return isInitializing;
}
///
/// Initializes a ParticleState for construction.
///
public void Initialize () {
isInitializing = true;
if (stateMesh==null && stateTexture!=null) {
ConstructParticles(stateTexture, stateScale, stateOffset, stateName, stateTransform);
} else if (stateMesh!=null && stateTexture!=null) {
ConstructParticles(stateMesh, stateTexture, stateScale, stateOffset, stateName, stateTransform);
} else if (stateMesh!=null && stateTexture==null) {
ConstructParticles(stateMesh, stateScale, stateOffset, stateName, stateTransform);
} else Debug.Log("State Texture or State Mesh returned null. Please assign an object to State: "+stateName+".");
initialized = position!=null && position.Length>0;
isInitializing = false;
}
public void UpdateMatrix (bool isLocal) {
stateTransformMx.SetTRS (isLocal?Vector3.zero:stateTransform.position, isLocal?Quaternion.identity:stateTransform.rotation, stateScaleMethod == ScaleMethod.Local? stateTransform.localScale : stateTransform.lossyScale);
}
///
/// Constructs image data.
///
/// Image.
/// Scale.
/// Offset.
/// New state name.
/// New state transform.
public void ConstructParticles (Texture2D image, float scale, Vector3 offset, string newStateName, Transform newStateTransform) {
List tmpColor = new List();
List tmpPosition = new List();
color = PlaygroundC.GetPixels(image);
bool readAlpha = false;
if (PlaygroundC.reference)
readAlpha = PlaygroundC.reference.buildZeroAlphaPixels;
bool readDepthmap = stateDepthmap!=null;
Color32[] depthMapPixels = readDepthmap?PlaygroundC.GetPixels(stateDepthmap):null;
int x = 0;
int y = 0;
float depthmapRatio = stateDepthmap!=null?((depthMapPixels.Length*1f) / (color.Length*1f)):0;
byte cSpread = (byte)(chromaKeySpread*255f);
for (int i = 0; ichromaKey.r+cSpread) &&
(color[i].gchromaKey.g+cSpread) &&
(color[i].bchromaKey.b+cSpread)))
{
tmpColor.Add(color[i]);
if (readDepthmap) {
int iScaled = Mathf.FloorToInt (((i*1f) * depthmapRatio));
float z = ((((depthMapPixels[iScaled].r*1f)+(depthMapPixels[iScaled].g*1f)+(depthMapPixels[iScaled].b*1f))/3)*((depthMapPixels[iScaled].a*1f)/255)*stateDepthmapStrength)/255;
tmpPosition.Add(new Vector3(x,y,z));
} else tmpPosition.Add(new Vector3(x,y,0));
}
}
x++; x=x%image.width;
if (x==0 && i!=0) y++;
}
color = tmpColor.ToArray() as Color32[];
position = tmpPosition.ToArray() as Vector3[];
tmpColor = null;
tmpPosition = null;
normals = new Vector3[position.Length];
for (int n = 0; n0;
}
///
/// Constructs Mesh data with texture.
///
/// Mesh.
/// Texture.
/// Scale.
/// Offset.
/// New state name.
/// New state transform.
public void ConstructParticles (Mesh mesh, Texture2D texture, float scale, Vector3 offset, string newStateName, Transform newStateTransform) {
position = mesh.vertices;
normals = mesh.normals;
if (normals==null || normals.Length==0) {
normals = new Vector3[position.Length];
for (int n = 0; n0;
}
///
/// Constructs Mesh data without texture.
///
/// Mesh.
/// Scale.
/// Offset.
/// New state name.
/// New state transform.
public void ConstructParticles (Mesh mesh, float scale, Vector3 offset, string newStateName, Transform newStateTransform) {
position = mesh.vertices;
normals = mesh.normals;
if (normals==null || normals.Length==0) {
normals = new Vector3[position.Length];
for (int n = 0; n0;
}
///
/// Returns color at index of ParticleState.
///
/// The color.
/// Index.
public Color32 GetColor (int index) {
if (colorLength==0) return new Color32();
index=index%colorLength;
return color[index];
}
///
/// Returns position at index of ParticleState.
///
/// The position.
/// Index.
public Vector3 GetPosition (int index) {
if (positionLength==0) return new Vector3();
index=index%positionLength;
return (position[index]+stateOffset)*stateScale;
}
public Vector3 GetLocalPosition (int index) {
if (positionLength==0) return new Vector3();
index=index%positionLength;
return stateTransformMx.MultiplyPoint3x4((position[index]+stateOffset)*stateScale);
}
///
/// Returns normal at index of ParticleState.
///
/// The normal.
/// Index.
public Vector3 GetNormal (int index) {
if (positionLength==0) return new Vector3();
index=index%positionLength;
return normals[index];
}
public Vector3 GetLocalNormal (int index) {
if (positionLength==0) return new Vector3();
index=index%positionLength;
return stateTransformMx.MultiplyPoint3x4(normals[index]);
}
///
/// Returns colors in ParticleState.
///
/// The colors.
public Color32[] GetColors () {
return color.Clone() as Color32[];
}
///
/// Returns positions in ParticleState.
///
/// The positions.
public Vector3[] GetPositions () {
return position.Clone() as Vector3[];
}
///
/// Returns normals in ParticleState.
///
/// The normals.
public Vector3[] GetNormals () {
return normals.Clone() as Vector3[];
}
///
/// Sets color at index of ParticleState.
///
/// Index.
/// C.
public void SetColor (int index, Color32 c) {
color[index] = c;
}
///
/// Sets position at index of ParticleState.
///
/// Index.
/// V.
public void SetPosition (int index, Vector3 v) {
position[index] = v;
}
///
/// Sets normal at index of ParticleState.
///
/// Index.
/// V.
public void SetNormal (int index, Vector3 v) {
normals[index] = v;
}
///
/// Returns position from parent's TransformPoint (can only be called from main-thread).
///
/// The parented position.
/// This position.
public Vector3 GetParentedPosition (int thisPosition) {
thisPosition = thisPosition%positionLength;
return stateTransform.TransformPoint((position[thisPosition]+stateOffset)*stateScale);
}
///
/// Returns a copy of this ParticleState.
///
public ParticleStateC Clone () {
ParticleStateC particleState = new ParticleStateC();
particleState.stateName = stateName;
particleState.stateScale = stateScale;
particleState.stateTexture = stateTexture;
particleState.stateDepthmap = stateDepthmap;
particleState.stateDepthmapStrength = stateDepthmapStrength;
particleState.stateMesh = stateMesh;
particleState.stateOffset = stateOffset;
particleState.colorLength = colorLength;
particleState.positionLength = positionLength;
particleState.stateTransform = stateTransform;
particleState.applyChromaKey = applyChromaKey;
particleState.chromaKey = chromaKey;
particleState.chromaKeySpread = chromaKeySpread;
return particleState;
}
}
///
/// Holds information for Source Projection.
///
[Serializable]
public class ParticleProjectionC {
///
/// Color data.
///
[HideInInspector] private Color32[] sourceColors;
///
/// Position data.
///
[HideInInspector] private Vector3[] sourcePositions;
///
/// Projected position data.
///
[HideInInspector] private Vector3[] targetPositions;
///
/// Projected normal data.
///
[HideInInspector] private Vector3[] targetNormals;
///
/// Projection has hit surface at point.
///
[HideInInspector] private bool[] hasProjected;
///
/// Projected transforms.
///
[HideInInspector] private Transform[] targetParents;
///
/// The texture to project.
///
public Texture2D projectionTexture;
///
/// The origin offset in Units.
///
public Vector2 projectionOrigin;
///
/// Transform to project from.
///
public Transform projectionTransform;
///
/// Matrix to project from.
///
public Matrix4x4 projectionMatrix;
///
/// Position of projection source.
///
public Vector3 projectionPosition;
///
/// Direction of projection source.
///
public Vector3 projectionDirection;
///
/// Rotation of projection source.
///
public Quaternion projectionRotation;
///
/// The distance in Units the projection travels.
///
public float projectionDistance = 1000f;
///
/// The scale of projection in Units.
///
public float projectionScale = .1f;
///
/// Layers seen by projection.
///
public LayerMask projectionMask = -1;
///
/// Determines if 3d- or 2d colliders are seen by projection.
///
public COLLISIONTYPEC collisionType;
///
/// Minimum depth of 2d colliders seen by projection.
///
public float minDepth = -1f;
///
/// Maximum depth of 2d colliders seen by projection.
///
public float maxDepth = 1f;
///
/// The offset from projected surface.
///
public float surfaceOffset = 0f;
///
/// Update this projector each frame.
///
public bool liveUpdate = true;
///
/// Is this projector finished refreshing?
///
public bool hasRefreshed = false;
///
/// Is this projector ready?
///
[HideInInspector] public bool initialized = false;
///
/// The length of color array.
///
[HideInInspector] public int colorLength;
///
/// The length of position array.
///
[HideInInspector] public int positionLength;
///
/// Initializes this ParticleProjection object.
///
public void Initialize () {
if (!projectionTexture) return;
Construct(projectionTexture, projectionTransform);
if (!liveUpdate) {
UpdateSource();
Update();
}
initialized = true;
hasRefreshed = false;
}
///
/// Builds source data.
///
/// Image.
/// Transform.
public void Construct (Texture2D image, Transform transform) {
List tmpColor = new List();
List tmpPosition = new List();
sourceColors = PlaygroundC.GetPixels(image);
bool readAlpha = false;
if (PlaygroundC.reference)
readAlpha = PlaygroundC.reference.buildZeroAlphaPixels;
int x = 0;
int y = 0;
for (int i = 0; i
/// Updates source matrix.
///
public void UpdateSource () {
projectionPosition = projectionTransform.position;
projectionDirection = projectionTransform.forward;
projectionRotation = projectionTransform.rotation;
projectionMatrix.SetTRS(projectionPosition, projectionRotation, projectionTransform.localScale);
}
///
/// Projects all particle sources (only call this if you need to set all particles at once).
///
public void Update () {
for (int i = 0; i
/// Projects a single particle source position.
///
/// Index.
public void Update (int index) {
index=index%positionLength;
Vector3 sourcePosition = projectionMatrix.MultiplyPoint3x4(sourcePositions[index]+new Vector3(projectionOrigin.x, projectionOrigin.y, 0));
if (collisionType==COLLISIONTYPEC.Physics3D) {
RaycastHit hit;
if (Physics.Raycast(sourcePosition, projectionDirection, out hit, projectionDistance, projectionMask)) {
targetPositions[index] = hit.point+(hit.normal*surfaceOffset);
targetNormals[index] = hit.normal;
targetParents[index] = hit.transform;
hasProjected[index] = true;
} else {
targetPositions[index] = PlaygroundC.initialTargetPosition;
targetNormals[index] = Vector3.forward;
hasProjected[index] = false;
targetParents[index] = null;
}
} else {
RaycastHit2D hit2d = Physics2D.Raycast (sourcePosition, projectionDirection, projectionDistance, projectionMask, minDepth, maxDepth);
if (hit2d.collider!=null) {
targetPositions[index] = hit2d.point+(hit2d.normal*surfaceOffset);
targetNormals[index] = hit2d.normal;
targetParents[index] = hit2d.transform;
hasProjected[index] = true;
} else {
targetPositions[index] = PlaygroundC.initialTargetPosition;
targetNormals[index] = Vector3.forward;
hasProjected[index] = false;
targetParents[index] = null;
}
}
}
///
/// Returns color at index of ParticleProjection.
///
/// The color.
/// Index.
public Color32 GetColor (int index) {
index=index%colorLength;
return sourceColors[index];
}
///
/// Returns position at index of ParticleProjection.
///
/// The position.
/// Index.
public Vector3 GetPosition (int index) {
index=index%positionLength;
return (targetPositions[index]);
}
///
/// Returns normal at index of ParticleProjection.
///
/// The normal.
/// Index.
public Vector3 GetNormal (int index) {
index=index%positionLength;
return targetNormals[index];
}
///
/// Returns parent at index of ParticleProjection.
///
/// The parent.
/// Index.
public Transform GetParent (int index) {
index=index%positionLength;
return targetParents[index];
}
///
/// Returns projection status at index of ParticleProjection.
///
/// true if this instance has projection the specified index; otherwise, false.
/// Index.
public bool HasProjection (int index) {
index=index%positionLength;
return hasProjected[index];
}
///
/// Returns a copy of this ParticleProjectionC object.
///
public ParticleProjectionC Clone () {
ParticleProjectionC particleProjection = new ParticleProjectionC();
if (sourceColors!=null)
particleProjection.sourceColors = (Color32[])sourceColors.Clone ();
if (sourcePositions!=null)
particleProjection.sourcePositions = (Vector3[])sourcePositions.Clone ();
if (targetPositions!=null)
particleProjection.targetPositions = (Vector3[])targetPositions.Clone ();
if (targetNormals!=null)
particleProjection.targetNormals = (Vector3[])targetNormals.Clone ();
if (hasProjected!=null)
particleProjection.hasProjected = (bool[])hasProjected.Clone ();
if (targetParents!=null)
particleProjection.targetParents = (Transform[])targetParents.Clone ();
particleProjection.projectionTexture = projectionTexture;
particleProjection.projectionOrigin = projectionOrigin;
particleProjection.projectionTransform = projectionTransform;
particleProjection.projectionMatrix = projectionMatrix;
particleProjection.projectionPosition = projectionPosition;
particleProjection.projectionDirection = projectionDirection;
particleProjection.projectionRotation = projectionRotation;
particleProjection.projectionDistance = projectionDistance;
particleProjection.projectionScale = projectionScale;
particleProjection.projectionMask = projectionMask;
particleProjection.collisionType = collisionType;
particleProjection.minDepth = minDepth;
particleProjection.maxDepth = maxDepth;
particleProjection.surfaceOffset = surfaceOffset;
particleProjection.liveUpdate = liveUpdate;
particleProjection.hasRefreshed = hasRefreshed;
particleProjection.initialized = initialized;
particleProjection.colorLength = colorLength;
particleProjection.positionLength = positionLength;
return particleProjection;
}
}
///
/// Holds AnimationCurves in X, Y and Z variables.
///
[Serializable]
public class Vector3AnimationCurveC {
public AnimationCurve x; // AnimationCurve for X-axis
public AnimationCurve y; // AnimationCurve for Y-axis
public AnimationCurve z; // AnimationCurve for Z-axis
public float xRepeat = 1f; // Repetition on X
public float yRepeat = 1f; // Repetition on Y
public float zRepeat = 1f; // Repetition on Z
///
/// Evaluate the specified time.
///
/// Time.
public Vector3 Evaluate (float time) {
return Evaluate (time, 1f);
}
///
/// Evaluates the specified time and apply scale.
///
/// Time.
/// Scale.
public Vector3 Evaluate (float time, float scale) {
return new Vector3(x.Evaluate(time*(xRepeat)%1f), y.Evaluate(time*(yRepeat)%1f), z.Evaluate(time*(zRepeat)%1f))*scale;
}
///
/// Determines whether this Vector3AnimationCurveC has keys in X, Y or Z AnimationCurves.
///
/// true if this instance has keys; otherwise, false.
public bool HasKeys () {
CheckNull();
return x.keys.Length>0||y.keys.Length>0||z.keys.Length>0;
}
///
/// Sets the key values.
///
/// X, Y and Z key.
/// Value as float.
public void SetKeyValues (int key, float value) {
SetKeyValues(key, new Vector3(value, value, value), 0, 0);
}
///
/// Sets the key values.
///
/// X, Y and Z key.
/// Value as Vector3.
public void SetKeyValues (int key, Vector3 value, float inTangent, float outTangent) {
CheckNull();
Keyframe[] xKeys = x.keys;
Keyframe[] yKeys = y.keys;
Keyframe[] zKeys = z.keys;
if (key
/// Resets this instance with value of 0.
///
public void Reset () {
CheckNull();
Keyframe[] reset = new Keyframe[2];
reset[0].time = 0;
reset[1].time = 1f;
x.keys = reset;
y.keys = reset;
z.keys = reset;
xRepeat = 1f;
yRepeat = 1f;
zRepeat = 1f;
}
///
/// Resets this instance with value of 1.
///
public void Reset1 () {
CheckNull();
Keyframe[] reset = new Keyframe[2];
reset[0].time = 0;
reset[0].value = 1f;
reset[1].time = 1f;
reset[1].value = 1f;
x.keys = reset;
y.keys = reset;
z.keys = reset;
xRepeat = 1f;
yRepeat = 1f;
zRepeat = 1f;
}
///
/// Resets this instance with three keyframes.
///
public void ResetWithMidKey () {
CheckNull();
Keyframe[] reset = new Keyframe[3];
reset[0].time = 0;
reset[1].time = .5f;
reset[2].time = 1f;
x.keys = reset;
y.keys = reset;
z.keys = reset;
xRepeat = 1f;
yRepeat = 1f;
zRepeat = 1f;
}
public void CheckNull () {
if (x==null) x = new AnimationCurve();
if (y==null) y = new AnimationCurve();
if (z==null) z = new AnimationCurve();
}
///
/// Returns a copy of this Vector3AnimationCurve.
///
public Vector3AnimationCurveC Clone () {
Vector3AnimationCurveC vector3AnimationCurveClone = new Vector3AnimationCurveC();
vector3AnimationCurveClone.x = new AnimationCurve(x.keys);
vector3AnimationCurveClone.y = new AnimationCurve(y.keys);
vector3AnimationCurveClone.z = new AnimationCurve(z.keys);
vector3AnimationCurveClone.xRepeat = xRepeat;
vector3AnimationCurveClone.yRepeat = yRepeat;
vector3AnimationCurveClone.zRepeat = zRepeat;
return vector3AnimationCurveClone;
}
}
///
/// Extended class for World Objects and Skinned World Objects.
///
[Serializable]
public class WorldObjectBaseC {
///
/// The GameObject of this World Object.
///
public GameObject gameObject;
///
/// The Transform of this World Object.
///
[HideInInspector] public Transform transform;
///
/// The Rigidbody of this World Object.
///
[HideInInspector] public Rigidbody rigidbody;
///
/// The mesh filter of this World Object (will be null for skinned meshes).
///
[HideInInspector] public MeshFilter meshFilter;
///
/// The mesh of this World Object.
///
[HideInInspector] public Mesh mesh;
///
/// The vertices of this World Object.
///
[HideInInspector] public Vector3[] vertexPositions;
///
/// The normals of this World Object.
///
[HideInInspector] public Vector3[] normals;
///
/// Determines if normals should update.
///
[HideInInspector] public bool updateNormals = false;
///
/// The id of this World Object (used to keep track when this object changes).
///
[NonSerialized] public int cachedId;
///
/// Determines if this World Object is initialized.
///
[NonSerialized] public bool initialized = false;
///
/// The transform matrix of this World Object. All source positions is calculated based on this matrix.
///
[HideInInspector] public Matrix4x4 transformMatrix = new Matrix4x4();
///
/// The scale method to use when updating the transform matrix.
///
[HideInInspector] public ScaleMethod scaleMethod;
public void UpdateMatrix (bool isLocal) {
transformMatrix.SetTRS(isLocal?Vector3.zero:transform.position, isLocal?Quaternion.identity:transform.rotation, scaleMethod == ScaleMethod.Local? transform.localScale : transform.lossyScale);
}
}
///
/// Holds information about a World object.
///
[Serializable]
public class WorldObject : WorldObjectBaseC {
[HideInInspector] public Renderer renderer;
///
/// Initializes this WorldObject and prepares it for extracting the mesh data.
///
public void Initialize () {
gameObject = transform.gameObject;
rigidbody = gameObject.GetComponent();
renderer = transform.GetComponentInChildren();
meshFilter = transform.GetComponentInChildren();
if (meshFilter!=null) {
mesh = meshFilter.sharedMesh;
if (mesh!=null) {
vertexPositions = mesh.vertices;
normals = mesh.normals;
initialized = true;
} else {
initialized = false;
}
}
cachedId = gameObject.GetInstanceID();
}
///
/// Updates this WorldObject.
///
public void Update () {
if (mesh!=null) {
vertexPositions = mesh.vertices;
if (updateNormals)
normals = mesh.normals;
}
}
///
/// Returns a copy of this WorldObject.
///
public WorldObject Clone () {
WorldObject worldObject = new WorldObject();
worldObject.gameObject = gameObject;
worldObject.transform = transform;
worldObject.rigidbody = rigidbody;
worldObject.renderer = renderer;
worldObject.meshFilter = meshFilter;
worldObject.mesh = mesh;
worldObject.updateNormals = updateNormals;
return worldObject;
}
}
///
/// Holds information about a Skinned world object. Consider to NOT use Optimize Game Objects at the skinned mesh's Import Settings for best performance of extracting its vertices.
///
[Serializable]
public class SkinnedWorldObject : WorldObjectBaseC {
///
/// Downresolution will skip vertices to set fewer target positions in a SkinnedWorldObject.
///
public int downResolution = 1;
///
/// The renderer of this SkinnedWorldObject.
///
[HideInInspector] public SkinnedMeshRenderer renderer;
///
/// The bones of this SkinnedWorldObject.
///
private Transform[] boneTransforms;
///
/// The weights of this SkinnedWorldObject.
///
private BoneWeight[] weights;
///
/// The binding poses of this SkinnedWorldObject.
///
private Matrix4x4[] bindPoses;
///
/// The bone matrices of this SkinnedWorldObject.
///
private Matrix4x4[] boneMatrices;
///
/// The calculated world vertices of this SkinnedWorldObject.
///
private Vector3[] vertices;
///
/// The local vertices to calculate upon of this SkinnedWorldObject.
///
private Vector3[] localVertices;
///
/// Determines if the thread for this skinned world object is ready. This is used when Skinned Mesh Thread Method is set to One Per System.
///
[HideInInspector] public bool isDoneThread = true;
private Mesh bakedMesh;
private Matrix4x4 vertexMatrix = new Matrix4x4();
///
/// Initializes this Skinned World Object and prepares it for extracting the mesh data.
///
public void Initialize () {
gameObject = transform.gameObject;
cachedId = gameObject.GetInstanceID();
rigidbody = gameObject.GetComponent();
renderer = transform.GetComponentInChildren();
mesh = renderer.sharedMesh;
if (mesh!=null) {
normals = mesh.normals;
vertices = new Vector3[mesh.vertices.Length];
localVertices = mesh.vertices;
weights = mesh.boneWeights;
boneTransforms = renderer.bones;
bindPoses = mesh.bindposes;
boneMatrices = new Matrix4x4[boneTransforms.Length];
vertexPositions = vertices;
initialized = true;
Update();
} else {
Debug.Log ("No mesh could be found in the assigned Skinned World Object. Make sure a mesh is assigned to your Skinned Mesh Renderer, if so - make sure the hierarchy under only have one Skinned Mesh Renderer component.", gameObject);
}
}
///
/// Updates the mesh.
///
public void MeshUpdate () {
if (initialized) {
if (boneMatrices!=null && boneMatrices.Length>0)
localVertices = mesh.vertices;
if (updateNormals)
normals = mesh.normals;
}
}
///
/// Updates the bones. If no bones are found (using Optimize Game Objects) a snapshot of the skinned mesh will be computed instead. Enabling Optimize Game Objects will be a lot slower, consider disabling this for your skinned meshes calculated by a Particle Playground system.
///
public void BoneUpdate () {
if (initialized) {
if (boneMatrices!=null && boneMatrices.Length>0) {
for (int i = 0; i
/// Updates this Skinned World Object.
///
public void Update () {
if (initialized) {
for (int i = 0; i0) {
Matrix4x4 m0 = boneMatrices[weights[i].boneIndex0];
Matrix4x4 m1 = boneMatrices[weights[i].boneIndex1];
Matrix4x4 m2 = boneMatrices[weights[i].boneIndex2];
Matrix4x4 m3 = boneMatrices[weights[i].boneIndex3];
for (int n=0; n<16; n++) {
vertexMatrix[n] =
m0[n] * weights[i].weight0 +
m1[n] * weights[i].weight1 +
m2[n] * weights[i].weight2 +
m3[n] * weights[i].weight3;
}
}
vertices[i] = vertexMatrix.MultiplyPoint3x4(localVertices[i]);
}
vertexPositions = vertices;
}
isDoneThread = true;
}
///
/// Updates this Skinned World Object on a new thread.
///
public void UpdateOnNewThread () {
if (isDoneThread) {
isDoneThread = false;
PlaygroundC.RunAsync(()=> {
if (isDoneThread) return;
Update();
});
}
}
///
/// Returns a copy of this SkinnedWorldObject.
///
public SkinnedWorldObject Clone () {
SkinnedWorldObject skinnedWorldObject = new SkinnedWorldObject();
skinnedWorldObject.downResolution = downResolution;
skinnedWorldObject.gameObject = gameObject;
skinnedWorldObject.transform = transform;
skinnedWorldObject.rigidbody = rigidbody;
skinnedWorldObject.renderer = renderer;
skinnedWorldObject.meshFilter = meshFilter;
skinnedWorldObject.mesh = mesh;
skinnedWorldObject.updateNormals = updateNormals;
return skinnedWorldObject;
}
}
///
/// Holds information about a Manipulator Object. A Manipulator can both be Global and Local and will affect all particles within range.
///
[Serializable]
public class ManipulatorObjectC {
///
/// The type of this manipulator.
///
public MANIPULATORTYPEC type;
///
/// The property settings (if type is property).
///
public ManipulatorPropertyC property = new ManipulatorPropertyC();
///
/// The combined properties (if type is combined).
///
public List properties = new List();
///
/// The layers this manipulator will affect. This only applies to Global Manipulators.
///
public LayerMask affects;
///
/// The transform of this manipulator (wrapped class for threading).
///
public PlaygroundTransformC transform = new PlaygroundTransformC();
///
/// The shape of this manipulator.
///
public MANIPULATORSHAPEC shape;
///
/// The size of this manipulator (if shape is sphere).
///
public float size;
///
/// The bounds of this manipulator (if shape is box).
///
public Bounds bounds;
///
/// The strength of this manipulator.
///
public float strength;
///
/// The scale of strength smoothing effector.
///
public float strengthSmoothing = 1f;
///
/// The scale of distance strength effector.
///
public float strengthDistanceEffect = 1f;
///
/// Determines if Particle Lifetime Strength should be applied.
///
public bool applyParticleLifetimeStrength = false;
///
/// The particle lifetime strength is defined by a normalized Animation Curve.
///
public AnimationCurve particleLifetimeStrength = new AnimationCurve(new Keyframe[]{new Keyframe(0,1f), new Keyframe(1f,1f)});
///
/// Is this manipulator enabled?
///
public bool enabled = true;
///
/// Should this manipulator be checking for particles inside or outside the shape's bounds?
///
public bool inverseBounds = false;
///
/// The id of this manipulator.
///
public int manipulatorId = 0;
///
/// Should lifetime filter determine which particles are affected?
///
public bool applyLifetimeFilter = false;
///
/// The minimum normalized lifetime of a particle that is affected by this manipulator.
///
public float lifetimeFilterMinimum = 0f;
///
/// The maximum normalized lifetime of a particle that is affected by this manipulator.
///
public float lifetimeFilterMaximum = 1f;
///
/// Should particle filter determine which particles are affected?
///
public bool applyParticleFilter = false;
///
/// The minimum normalized number in array of a particle that is affected by this manipulator.
///
public float particleFilterMinimum = 0f;
///
/// The maximum normalized number in array of a particle that is affected by this manipulator.
///
public float particleFilterMaximum = 1f;
///
/// The axis constraints for this Manipulator. This enables you to set if the calculated forces should not be applied on certain axis.
///
public PlaygroundAxisConstraintsC axisConstraints = new PlaygroundAxisConstraintsC();
public bool unfolded = false;
///
/// Should the manipulator be able to send particle events and keep track of its particles?
///
public bool trackParticles = false;
///
/// The tracking method when trackParticles is enabled.
/// Using TrackingMethod.ManipulatorId will be fast, but may not return correct when having overlapping Manipulators.
/// Using TrackingMethod.ParticleId will be slow, but will ensure correct compare of particles within any overlapping Manipulators.
///
public TrackingMethod trackingMethod = TrackingMethod.ManipulatorId;
///
/// Should enter event be sent?
///
public bool sendEventEnter = true;
///
/// Should exit event be sent?
///
public bool sendEventExit = true;
///
/// Should birth event be sent?
///
public bool sendEventBirth = true;
///
/// Should death event be sent?
///
public bool sendEventDeath = true;
///
/// Should collision event be sent?
///
public bool sendEventCollision = true;
public bool sendEventsUnfolded = false;
///
/// The entering event of a particle (when using Event Listeners).
///
public event OnPlaygroundParticle particleEventEnter;
///
/// The exit event of a particle (when using Event Listeners).
///
public event OnPlaygroundParticle particleEventExit;
///
/// The birth event of a particle (when using Event Listeners).
///
public event OnPlaygroundParticle particleEventBirth;
///
/// The death event of a particle (when using Event Listeners).
///
public event OnPlaygroundParticle particleEventDeath;
///
/// The collision event of a particle (when using Event Listeners).
///
public event OnPlaygroundParticle particleEventCollision;
///
/// The current particles inside this manipulator. This requires that you have enabled trackParticles.
///
[NonSerialized] public List particles = new List();
///
/// The particles which will not be affected by this manipulator. If possible use the Manipulator's particle filtering methods instead as they are faster to compute.
///
[NonSerialized] public List nonAffectedParticles = new List();
///
/// The cached event particle used to send into events.
///
public PlaygroundEventParticle manipulatorEventParticle = new PlaygroundEventParticle();
[NonSerialized] bool initializedEventEnter = false; // Has the enter event initialized?
[NonSerialized] bool initializedEventExit = false; // Has the exit event initialized?
[NonSerialized] bool initializedEventBirth = false; // Has the birth event initialized?
[NonSerialized] bool initializedEventDeath = false; // Has the death event initialized?
[NonSerialized] bool initializedEventCollision = false; // Has the collision event initialized?
///
/// Checks if manipulator contains position. The outcome is depending on if you use a sphere (size)- or box (bounds) as shape. The passed in position is your target (particle) position and the mPosition is the Manipulator's origin position.
///
/// Position of target.
/// Center position of Manipulator.
public bool Contains (Vector3 position, Vector3 mPosition) {
if (shape==MANIPULATORSHAPEC.Infinite) {
return true;
} else if (shape==MANIPULATORSHAPEC.Box) {
if (!inverseBounds)
return bounds.Contains(transform.inverseRotation*(position-mPosition));
else
return !bounds.Contains(transform.inverseRotation*(position-mPosition));
} else {
if (!inverseBounds)
return (Vector3.Distance(position, mPosition)<=size);
else
return (Vector3.Distance(position, mPosition)>=size);
}
}
public void SendParticleEventEnter () {
if (initializedEventEnter)
particleEventEnter(manipulatorEventParticle);
}
public void SendParticleEventExit () {
if (initializedEventExit)
particleEventExit(manipulatorEventParticle);
}
public void SendParticleEventBirth () {
if (initializedEventBirth)
particleEventBirth(manipulatorEventParticle);
}
public void SendParticleEventDeath () {
if (initializedEventDeath)
particleEventDeath(manipulatorEventParticle);
}
public void SendParticleEventCollision () {
if (initializedEventCollision)
particleEventCollision(manipulatorEventParticle);
}
///
/// Gets the particle at index. Note that the Manipulator must have trackParticles set to true.
///
/// The particle.
/// Index.
public PlaygroundEventParticle GetParticle (int index) {
if (particles==null || particles.Count==0 || index>particles.Count) return null;
return GetParticle (particles[index].particleSystemId, particles[index].particleId);
}
///
/// Gets the particle in particle system at index. Note that the Manipulator must have trackParticles set to true.
///
/// The particle.
/// Particle system identifier.
/// Particle identifier.
public PlaygroundEventParticle GetParticle (int particleSystemId, int particleId) {
PlaygroundEventParticle returnEventParticle = new PlaygroundEventParticle();
if (PlaygroundC.reference.particleSystems[particleSystemId].UpdateEventParticle(returnEventParticle, particleId))
return returnEventParticle;
else return null;
}
///
/// Gets all particles within this Manipulator. Note that the Manipulator must have trackParticles set to true.
///
/// The particles.
public List GetParticles () {
List returnEventParticles = new List();
for (int i = 0; i
/// Check if Manipulator contains particle of particle system.
///
/// true, if particle was found, false otherwise.
/// Particle system identifier.
/// Particle identifier.
public bool ContainsParticle (int particleSystemId, int particleId) {
for (int i = 0; i
/// Check if passed in id is the same as this Manipulator id. This is the fastest way to compare particles (playgroundCache.manipulatorId) to Manipulators, but will not work for overlapping areas.
///
/// true, if same id, false otherwise.
/// Id to compare with.
public bool IsSameId (int compareId) {
if (manipulatorId==compareId)
return true;
return false;
}
///
/// Adds a particle to the list of particles. Note that the Manipulator must have tracking enabled.
///
/// Particle system identifier.
/// Particle identifier.
public bool AddParticle (int particleSystemId, int particleId) {
if (particles == null)
return false;
for (int i = 0; i
/// Removes a particle from the list of particles. Note that the Manipulator must have tracking enabled.
///
/// true, if particle was removed, false otherwise.
/// Particle system identifier.
/// Particle identifier.
public bool RemoveParticle (int particleSystemId, int particleId) {
if (particles == null)
return false;
bool didRemove = false; // We must execute the full list to remove any created duplicates
for (int i = 0; i
/// Kills all particles within the Manipulator. Note that the Manipulator must have tracking enabled.
///
public void KillAllParticles () {
if (particles == null)
return;
for (int i = 0; i=particles.Count || i<0) return;
PlaygroundC.reference.particleSystems[particles[i].particleSystemId].Kill (particles[i].particleId);
particles.RemoveAt(i);
if (i>0) i--;
}
}
///
/// Check if the Manipulator contains a particle which won't be affected.
///
/// true, if non-affected particle was found, false otherwise.
/// Particle system identifier.
/// Particle identifier.
public bool ContainsNonAffectedParticle (int particleSystemId, int particleId) {
for (int i = 0; i
/// Adds a non-affected particle. The particle won't be affected by this Manipulator. If possible, use the particle filtering methods on the Manipulator instead, they are faster to compute.
///
/// Particle system identifier.
/// Particle identifier.
public void AddNonAffectedParticle (int particleSystemId, int particleId) {
nonAffectedParticles.Add (new ManipulatorParticle(particleSystemId, particleId));
}
///
/// Removes the non affected particle. If possible, use the particle filtering methods on the Manipulator instead, they are faster to compute.
///
/// true, if non affected particle was removed, false otherwise.
/// Particle system identifier.
/// Particle identifier.
public bool RemoveNonAffectedParticle (int particleSystemId, int particleId) {
for (int i = 0; i
/// Check if lifetime filter will apply.
///
/// true, if filter was lifetimed, false otherwise.
/// Life.
/// Total.
public bool LifetimeFilter (float life, float total) {
if (!applyLifetimeFilter) return true;
float normalizedLife = life/total;
return (normalizedLife>=lifetimeFilterMinimum && normalizedLife<=lifetimeFilterMaximum);
}
///
/// Check if particle filter will apply.
///
/// true, if filter was particled, false otherwise.
/// P.
/// Total.
public bool ParticleFilter (int p, int total) {
if (!applyParticleFilter) return true;
float normalizedP = (p*1f)/(total*1f);
return (normalizedP>=particleFilterMinimum && normalizedP<=particleFilterMaximum);
}
///
/// Update this Manipulator Object. This runs automatically each calculation loop.
///
public void Update () {
if (enabled) {
if (transform.Update()) {
manipulatorId = transform.instanceID;
if (trackParticles) {
initializedEventEnter = (particleEventEnter!=null);
initializedEventExit = (particleEventExit!=null);
initializedEventBirth = (particleEventBirth!=null);
initializedEventDeath = (particleEventDeath!=null);
initializedEventCollision = (particleEventCollision!=null);
} else {
if (particles.Count>0)
particles.Clear();
}
if (type==MANIPULATORTYPEC.Property || type==MANIPULATORTYPEC.Combined) {
property.Update();
property.SetLocalVelocity(transform.rotation, property.velocity);
if (property.type == MANIPULATORPROPERTYTYPEC.Math)
property.UpdateMathProperty(transform.position);
for (int i = 0; i
/// Sets a new transform to this Manipulator.
///
/// The new Transform that should be assigned to this Manipulator.
public void SetTransform (Transform transform) {
this.transform.SetFromTransform(transform);
}
public void SetLocalTargetsPosition (Transform otherTransform) {
property.SetLocalTargetsPosition(otherTransform);
for (int i = 0; i
/// Return a copy of this ManipulatorObjectC.
///
public ManipulatorObjectC Clone () {
ManipulatorObjectC manipulatorObject = new ManipulatorObjectC();
manipulatorObject.type = type;
manipulatorObject.property = property.Clone();
manipulatorObject.affects = affects;
manipulatorObject.transform = transform.Clone();
manipulatorObject.size = size;
manipulatorObject.shape = shape;
manipulatorObject.bounds = bounds;
manipulatorObject.strength = strength;
manipulatorObject.applyParticleLifetimeStrength = applyParticleLifetimeStrength;
manipulatorObject.particleLifetimeStrength = new AnimationCurve(particleLifetimeStrength.keys);
manipulatorObject.strengthSmoothing = strengthSmoothing;
manipulatorObject.strengthDistanceEffect = strengthDistanceEffect;
manipulatorObject.enabled = enabled;
manipulatorObject.applyLifetimeFilter = applyLifetimeFilter;
manipulatorObject.lifetimeFilterMinimum = lifetimeFilterMinimum;
manipulatorObject.lifetimeFilterMaximum = lifetimeFilterMaximum;
manipulatorObject.applyParticleFilter = applyParticleFilter;
manipulatorObject.particleFilterMinimum = particleFilterMinimum;
manipulatorObject.particleFilterMaximum = particleFilterMaximum;
manipulatorObject.inverseBounds = inverseBounds;
manipulatorObject.trackParticles = trackParticles;
manipulatorObject.sendEventEnter = sendEventEnter;
manipulatorObject.sendEventExit = sendEventExit;
manipulatorObject.sendEventBirth = sendEventBirth;
manipulatorObject.sendEventDeath = sendEventDeath;
manipulatorObject.sendEventCollision = sendEventCollision;
manipulatorObject.properties = new List();
manipulatorObject.axisConstraints = axisConstraints.Clone();
for (int i = 0; i
/// Holds information for a Manipulator Object's different property abilities.
///
[Serializable]
public class ManipulatorPropertyC {
///
/// The type of this manipulator property.
///
public MANIPULATORPROPERTYTYPEC type;
///
/// The transition of this manipulator property.
///
public MANIPULATORPROPERTYTRANSITIONC transition;
///
/// The math property. This can be used to apply extensive particle behaviors.
///
public MathManipulatorProperty mathProperty = new MathManipulatorProperty();
///
/// The velocity of this manipulator property.
///
public Vector3 velocity;
///
/// The local velocity of this manipulator property (set by SetLocalVelocity).
///
public Vector3 localVelocity;
///
/// The color of this manipulator property.
///
public Color color = new Color(1,1,1,1);
///
/// The lifetime color of this manipulator property.
///
public Gradient lifetimeColor;
///
/// The size of this manipulator property.
///
public float size = 1f;
///
/// The targets to position towards of this manipulator property. Each target is a single point in world space of type PlaygroundTransformC (Transform wrapper).
///
public List targets = new List();
///
/// The pointer of targets (used for calculation to determine which particle should get which target).
///
public int targetPointer;
///
/// The Mesh Target (World Object) to target particles to.
///
public WorldObject meshTarget = new WorldObject();
///
/// The Skinned Mesh Target (Skinned World Object) to target particles to.
///
public SkinnedWorldObject skinnedMeshTarget = new SkinnedWorldObject();
///
/// The mesh- or skinned mesh target is procedural and changes vertices over time.
///
public bool meshTargetIsProcedural = false;
///
/// Transform matrix for mesh targets.
///
public Matrix4x4 meshTargetMatrix = new Matrix4x4();
///
/// The State Target in the scene to target particles to.
///
public ParticleStateC stateTarget = new ParticleStateC();
///
/// The Playground Spline Target in the scene to target particles to.
///
public PlaygroundSpline splineTarget;
///
/// The method to target the Playground Spline assigned to splineTarget.
///
public SPLINETARGETMETHOD splineTargetMethod;
public float splineTimeOffset;
bool splineTargetIsReady;
///
/// Should the manipulator's transform direction be used to apply velocity?
///
public bool useLocalRotation = false;
///
/// Should the particles go back to original color when out of range?
///
public bool onlyColorInRange = true;
///
/// Should the particles keep their original color alpha?
///
public bool keepColorAlphas = true;
///
/// Should the particles stop positioning towards target when out of range?
///
public bool onlyPositionInRange = true;
///
/// Should the particles go back to original size when out of range?
///
public bool onlySizeInRange = false;
///
/// The strength to zero velocity on target positioning when using transitions.
///
public float zeroVelocityStrength = 1f;
///
/// Individual property strength.
///
public float strength = 1f;
public bool unfolded = true;
///
/// Target sorting type.
///
public TARGETSORTINGC targetSorting;
///
/// The sorted list for target positions.
///
[NonSerialized] public int[] targetSortingList;
///
/// The previous sorting type.
///
TARGETSORTINGC previousTargetSorting;
public TURBULENCETYPE turbulenceType = TURBULENCETYPE.Simplex; // The type of turbulence
public float turbulenceTimeScale = 1f; // Time scale of turbulence
public float turbulenceScale = 1f; // Resolution scale of turbulence
public bool turbulenceApplyLifetimeStrength; // Should lifetime strength apply to turbulence?
public AnimationCurve turbulenceLifetimeStrength; // The normalized lifetime strength of turbulence
public SimplexNoise turbulenceSimplex; // The Simplex Noise of this manipulator property
///
/// Updates this ManipulatorPropertyC.
///
public void Update () {
if (type==MANIPULATORPROPERTYTYPEC.Target) {
for (int i = 0; i{
skinnedMeshTarget.Update();
});
if (targetSortingList==null || targetSortingList.Length!=skinnedMeshTarget.vertexPositions.Length || previousTargetSorting!=targetSorting)
TargetSorting();
}
}
} else
if (type==MANIPULATORPROPERTYTYPEC.StateTarget) {
if (!stateTarget.initialized && (stateTarget.stateMesh!=null || stateTarget.stateTexture!=null) && stateTarget.stateTransform!=null) {
stateTarget.Initialize();
} else if (stateTarget.initialized && stateTarget.stateTransform!=null) {
stateTarget.stateTransformMx.SetTRS(stateTarget.stateTransform.position, stateTarget.stateTransform.rotation, stateTarget.stateTransform.localScale);
}
if (stateTarget.initialized && (targetSortingList==null || targetSortingList.Length!=stateTarget.positionLength || previousTargetSorting!=targetSorting))
TargetSorting();
} else
if (type==MANIPULATORPROPERTYTYPEC.SplineTarget) {
splineTargetIsReady = splineTarget!=null&&splineTarget.IsReady();
} else
if (type==MANIPULATORPROPERTYTYPEC.Turbulence) {
if (turbulenceSimplex==null)
turbulenceSimplex = new SimplexNoise();
} else
if (type==MANIPULATORPROPERTYTYPEC.Math) {
}
}
public void UpdateMathProperty (Vector3 manipulatorPosition) {
if (mathProperty==null)
mathProperty = new MathManipulatorProperty();
mathProperty.Update (manipulatorPosition);
}
///
/// Refreshes the meshTarget's mesh. Use this whenever you're working with a procedural mesh and want to assign new target vertices for your particles.
///
public void UpdateMeshTarget () {
meshTarget.Update();
}
///
/// Refreshes the skinnedMeshTarget's mesh. Use this whenever you're working with a procedural skinned mesh and want to assign new target vertices for your particles.
///
public void UpdateSkinnedMeshTarget () {
skinnedMeshTarget.Update();
}
///
/// Sets the mesh target. Whenever a new GameObject is assigned to your mesh target a refresh of the World Object will be initiated.
///
/// The GameObject to create your mesh target's World Object from. A MeshFilter- and mesh component is required on the GameObject.
public void SetMeshTarget (GameObject gameObject) {
meshTarget.gameObject = gameObject;
}
///
/// Sets the skinned mesh target. Whenever a new GameObject is assigned to your skinned mesh target a refresh of the Skinned World Object will be initiated.
///
/// The GameObject to create your skinned mesh target's Skinned World Object from. A SkinnedMeshRenderer- and mesh component is required on the GameObject.
public void SetSkinnedMeshTarget (GameObject gameObject) {
skinnedMeshTarget.gameObject = gameObject;
}
///
/// Determines if the Playground Spline Target is ready to be read.
///
/// true, if Playground Spline Target is ready, false otherwise.
public bool SplineTargetIsReady () {
return splineTargetIsReady;
}
// Sorts the particles for targeting depending on sorting method.
public void TargetSorting () {
if (type==MANIPULATORPROPERTYTYPEC.MeshTarget && !meshTarget.initialized || type==MANIPULATORPROPERTYTYPEC.SkinnedMeshTarget && !skinnedMeshTarget.initialized || type==MANIPULATORPROPERTYTYPEC.StateTarget && !stateTarget.initialized) return;
targetPointer = 0;
if (type==MANIPULATORPROPERTYTYPEC.MeshTarget)
targetSortingList = new int[meshTarget.vertexPositions.Length];
else if (type==MANIPULATORPROPERTYTYPEC.SkinnedMeshTarget)
targetSortingList = new int[skinnedMeshTarget.vertexPositions.Length];
else if (type==MANIPULATORPROPERTYTYPEC.StateTarget)
targetSortingList = new int[stateTarget.positionLength];
switch (targetSorting) {
case TARGETSORTINGC.Scrambled:
for (int i = 0; i0; i--) {
targetSortingList[x]=i;
x++;
}
break;
}
previousTargetSorting = targetSorting;
}
public void SetLocalVelocity (Quaternion rotation, Vector3 newVelocity) {
localVelocity = rotation*newVelocity;
}
public void SetLocalTargetsPosition (Transform otherTransform) {
for (int i = 0; i
/// Update a target, returns availability.
///
/// true, if target was updated, false otherwise.
/// Index.
public bool UpdateTarget (int index) {
if (targets.Count>0) {
index=index%targets.Count;
targets[index].Update();
}
return targets[index].available;
}
///
/// Return a copy of this ManipulatorPropertyC.
///
public ManipulatorPropertyC Clone () {
ManipulatorPropertyC manipulatorProperty = new ManipulatorPropertyC();
manipulatorProperty.type = type;
manipulatorProperty.transition = transition;
manipulatorProperty.velocity = velocity;
manipulatorProperty.color = color;
manipulatorProperty.lifetimeColor = lifetimeColor;
manipulatorProperty.size = size;
manipulatorProperty.useLocalRotation = useLocalRotation;
manipulatorProperty.onlyColorInRange = onlyColorInRange;
manipulatorProperty.keepColorAlphas = keepColorAlphas;
manipulatorProperty.onlyPositionInRange = onlyPositionInRange;
manipulatorProperty.zeroVelocityStrength = zeroVelocityStrength;
manipulatorProperty.strength = strength;
manipulatorProperty.targetPointer = targetPointer;
manipulatorProperty.targets = new List();
for (int i = 0; i
/// Holds information for a Math Manipulator. This can be used to apply extensive particle behaviors, such as positioning or changing sizes using sine, cosine or linear interpolation math.
///
[Serializable]
public class MathManipulatorProperty {
public MATHMANIPULATORTYPE type;
public MATHMANIPULATORPROPERTY property;
public MATHMANIPULATORCLAMP clamp;
public float clampCeil = 10f;
public float clampFloor = 0;
public float value = 1f;
public Vector3 value3 = Vector3.up;
public float rate = 1f;
public Vector3 rate3 = Vector3.up;
Vector3 value3Position;
///
/// Updates the position for this MathManipulatorProperty. This happens automatically each frame for a Math Manipulator.
///
public void Update (Vector3 position) {
value3Position = position+value3;
}
///
/// Evaluate the specified in-value and time.
/// - When using Sin or Cos a continuous time is expected (such as Time.time).
/// - Lerp expects a normalized value between 0f to 1f, the framework is using the delta time each frame (resulting in a smooth damp).
/// - Add or Subtract will scale the value with the passed in time, using it as a multiplier.
///
/// In value.
/// Time.
public Vector3 Evaluate (Vector3 inValue, float time) {
Vector3 returnValue;
if (clamp==MATHMANIPULATORCLAMP.ClampInValue)
inValue = Clamp (inValue);
switch (type) {
case MATHMANIPULATORTYPE.Sin:
returnValue = new Vector3(
value3.x!=0? ClampOut(inValue.x+Mathf.Sin (time*rate3.x)*value3.x) : inValue.x,
value3.y!=0? ClampOut(inValue.y+Mathf.Sin (time*rate3.y)*value3.y) : inValue.y,
value3.z!=0? ClampOut(inValue.z+Mathf.Sin (time*rate3.z)*value3.z) : inValue.z
);
break;
case MATHMANIPULATORTYPE.Cos:
returnValue = Clamp(new Vector3(
value3.x!=0? ClampOut(inValue.x+Mathf.Cos (time*rate3.x)*value3.x) : inValue.x,
value3.y!=0? ClampOut(inValue.y+Mathf.Cos (time*rate3.y)*value3.y) : inValue.y,
value3.z!=0? ClampOut(inValue.z+Mathf.Cos (time*rate3.z)*value3.z) : inValue.z
));
break;
case MATHMANIPULATORTYPE.Lerp:
returnValue = Clamp(new Vector3(
value3.x!=0? Mathf.Lerp (inValue.x, ClampOut(value3.x), time*rate3.x) : inValue.x,
value3.y!=0? Mathf.Lerp (inValue.y, ClampOut(value3.y), time*rate3.y) : inValue.y,
value3.z!=0? Mathf.Lerp (inValue.z, ClampOut(value3.z), time*rate3.z) : inValue.z
));
break;
case MATHMANIPULATORTYPE.Add:
returnValue = inValue+ClampOut((Vector3.Scale (value3, rate3)*time));
break;
case MATHMANIPULATORTYPE.Subtract:
returnValue = inValue-ClampOut((Vector3.Scale (value3, rate3)*time));
break;
default:
returnValue = inValue;
break;
}
return returnValue;
}
///
/// Evaluate the specified in-value and time. This overload is specifically adapted for if you want to clamp position alongside the Manipulator's position.
/// - When using Sin or Cos a continuous time is expected (such as Time.time).
/// - Lerp expects a normalized value between 0f to 1f, the framework is using the delta time each frame (resulting in a smooth damp).
/// - Add or Subtract will scale the value with the passed in time, using it as a multiplier.
///
/// In value.
/// Time.
public Vector3 EvaluatePosition (Vector3 inValue, float time) {
Vector3 returnValue;
if (clamp==MATHMANIPULATORCLAMP.ClampInValue)
inValue = Clamp (inValue);
switch (type) {
case MATHMANIPULATORTYPE.Sin:
returnValue = ClampPosition(new Vector3(
inValue.x+(Mathf.Sin (time*rate3.x)*value3.x),
inValue.y+(Mathf.Sin (time*rate3.y)*value3.y),
inValue.z+(Mathf.Sin (time*rate3.z)*value3.z)
));
break;
case MATHMANIPULATORTYPE.Cos:
returnValue = ClampPosition(new Vector3(
inValue.x+Mathf.Cos (time*rate3.x)*value3.x,
inValue.y+Mathf.Cos (time*rate3.y)*value3.y,
inValue.z+Mathf.Cos (time*rate3.z)*value3.z
));
break;
case MATHMANIPULATORTYPE.Lerp:
returnValue = ClampPosition(new Vector3(
Mathf.Lerp (inValue.x, value3Position.x, time*rate3.x),
Mathf.Lerp (inValue.y, value3Position.y, time*rate3.y),
Mathf.Lerp (inValue.z, value3Position.z, time*rate3.z)
));
break;
case MATHMANIPULATORTYPE.Add:
returnValue = ClampPosition(inValue+(Vector3.Scale (value3, rate3)*time));
break;
case MATHMANIPULATORTYPE.Subtract:
returnValue = ClampPosition(inValue-(Vector3.Scale (value3, rate3)*time));
break;
default:
returnValue = inValue;
break;
}
return returnValue;
}
///
/// Evaluate the specified in-value and time.
/// - When using Sin or Cos a continuous time is expected (such as Time.time).
/// - Lerp expects a normalized value between 0f to 1f, the framework is using the delta time each frame (resulting in a smooth damp).
/// - Add or Subtract will scale the value with the passed in time, using it as a multiplier.
///
/// In value.
/// Time.
public float Evaluate (float inValue, float time) {
float returnValue;
if (clamp==MATHMANIPULATORCLAMP.ClampInValue)
inValue = Clamp (inValue);
switch (type) {
case MATHMANIPULATORTYPE.Sin:
returnValue = value!=0? ClampOut(Mathf.Sin (time*rate)*value) : inValue;
break;
case MATHMANIPULATORTYPE.Cos:
returnValue = value!=0? ClampOut(Mathf.Cos (time*rate)*value) : inValue;
break;
case MATHMANIPULATORTYPE.Lerp:
returnValue = value!=0? Mathf.Lerp (inValue, ClampOut(value), time*rate) : inValue;
break;
case MATHMANIPULATORTYPE.Add:
returnValue = ClampOut(inValue+(value*rate*time));
break;
case MATHMANIPULATORTYPE.Subtract:
returnValue = ClampOut(inValue-(value*rate*time));
break;
default:
returnValue = inValue;
break;
}
return returnValue;
}
float Clamp (float val) {
if (clamp==MATHMANIPULATORCLAMP.None) return val;
return Mathf.Clamp (val, clampFloor, clampCeil);
}
Vector3 Clamp (Vector3 val) {
if (clamp==MATHMANIPULATORCLAMP.None) return val;
val = new Vector3 (
Mathf.Clamp (val.x, clampFloor, clampCeil),
Mathf.Clamp (val.y, clampFloor, clampCeil),
Mathf.Clamp (val.z, clampFloor, clampCeil)
);
return val;
}
Vector3 ClampPosition (Vector3 val) {
if (clamp==MATHMANIPULATORCLAMP.None) return val;
val = new Vector3 (
Mathf.Clamp (val.x, value3Position.x+clampFloor, value3Position.x+clampCeil),
Mathf.Clamp (val.y, value3Position.y+clampFloor, value3Position.y+clampCeil),
Mathf.Clamp (val.z, value3Position.z+clampFloor, value3Position.z+clampCeil)
);
return val;
}
float ClampOut (float val) {
if (clamp!=MATHMANIPULATORCLAMP.ClampOutValue) return val;
return Clamp (val);
}
Vector3 ClampOut (Vector3 val) {
if (clamp!=MATHMANIPULATORCLAMP.ClampOutValue) return val;
return Clamp (val);
}
///
/// Returns a clone of this MathManipulatorProperty.
///
public MathManipulatorProperty Clone () {
MathManipulatorProperty clone = new MathManipulatorProperty();
clone.type = type;
clone.property = property;
clone.clamp = clamp;
clone.clampFloor = clampFloor;
clone.clampCeil = clampCeil;
clone.value = value;
clone.value3 = value3;
clone.rate = rate;
clone.rate3 = rate3;
return clone;
}
}
///
/// The Manipulator Particle class is a container for tracking particles in their particle system. When reaching a particle on a Manipulator the particle will convert to a PlaygroundEventParticle.
///
[Serializable]
public class ManipulatorParticle {
public int particleSystemId;
public int particleId;
public ManipulatorParticle(int setParticleSystemId, int setParticleId) {
particleSystemId = setParticleSystemId;
particleId = setParticleId;
}
}
///
/// Wrapper class for the Transform component. This is updated outside- and read inside the multithreaded environment.
///
[Serializable]
public class PlaygroundTransformC {
///
/// The Transform component the Playground Transform wrapper will base its calculation from.
///
public Transform transform;
///
/// The instance id.
///
public int instanceID;
///
/// Is this Playground Transform available for calculation?
///
public bool available;
///
/// The position in units.
///
public Vector3 position;
///
/// The local position (if parented) in units.
///
public Vector3 localPosition;
///
/// The previous calculated position.
///
public Vector3 previousPosition;
///
/// The forward axis (Transform forward).
///
public Vector3 forward;
///
/// The upwards axis (Transform up).
///
public Vector3 up;
///
/// The right axis (Transform right).
///
public Vector3 right;
///
/// The rotation of this Playground Transform.
///
public Quaternion rotation;
///
/// The inverse rotation of this Playground Transform (used for bounding boxes).
///
public Quaternion inverseRotation;
public ScaleMethod scaleMethod;
///
/// The local scale of this Playground Transform.
///
public Vector3 localScale;
///
/// The lossy scale of this Playground Transform.
///
public Vector3 lossyScale;
///
/// The transform matrix. This can be used to set and get transform coordinates from another thread.
///
public Matrix4x4 transformMatrix = new Matrix4x4();
public bool unfolded;
///
/// Update this PlaygroundTransformC, returns availability (not thread-safe).
///
public bool Update () {
if (transform!=null) {
instanceID = transform.GetInstanceID();
previousPosition = position;
position = transform.position;
forward = transform.forward;
up = transform.up;
right = transform.right;
rotation = transform.rotation;
inverseRotation = rotation;
inverseRotation.x=-inverseRotation.x;
inverseRotation.y=-inverseRotation.y;
inverseRotation.z=-inverseRotation.z;
localScale = transform.localScale;
lossyScale = transform.lossyScale;
available = true;
} else {
available = false;
}
return available;
}
///
/// Updates the transform matrix.
///
public void UpdateMatrix () {
if (available)
transformMatrix.SetTRS(position, rotation, scaleMethod == ScaleMethod.Local? localScale : lossyScale);
}
public bool IsSameAs (Transform comparer) {
return (transform==comparer);
}
public void SetZeroRotation () {
rotation = Quaternion.identity;
}
///
/// Sets data from a Transform (not thread-safe).
///
/// Other transform.
public void SetFromTransform (Transform otherTransform) {
transform = otherTransform;
Update();
}
///
/// Sets a Transform's position, rotation and scale from this wrapped Transform (not thread-safe).
///
/// Other transform.
public void GetFromTransform (Transform otherTransform) {
otherTransform.position = position;
otherTransform.rotation = rotation;
otherTransform.localScale = localScale;
}
///
/// Sets local position from another transform (not thread-safe).
///
/// Other transform.
public void SetLocalPosition (Transform otherTransform) {
if (available)
localPosition = otherTransform.InverseTransformPoint(transform.position);
}
public void SetPostitionAsLocal () {
position = localPosition;
}
///
/// Returns the instance id of this PlaygroundTransformC.
///
/// The instance id.
public int GetInstanceID () {
return instanceID;
}
///
/// Returns a copy of this PlaygroundTransformC.
///
public PlaygroundTransformC Clone () {
PlaygroundTransformC playgroundTransform = new PlaygroundTransformC();
playgroundTransform.transform = transform;
playgroundTransform.available = available;
playgroundTransform.position = position;
playgroundTransform.forward = forward;
playgroundTransform.up = up;
playgroundTransform.right = right;
playgroundTransform.rotation = rotation;
return playgroundTransform;
}
}
///
/// Holds information for a Playground Collider (infinite collision plane).
///
[Serializable]
public class PlaygroundColliderC {
///
/// Is this PlaygroundCollider enabled?
///
public bool enabled = true;
///
/// The transform that makes this PlaygroundCollider.
///
public Transform transform;
///
/// The plane of this PlaygroundCollider.
///
public Plane plane = new Plane();
///
/// The offset in world space to this plane.
///
public Vector3 offset;
///
/// Update this PlaygroundCollider's plane.
///
public void UpdatePlane () {
if (!transform) return;
plane.SetNormalAndPosition(transform.up, transform.position+offset);
}
///
/// Clone this PlaygroundColliderC.
///
public PlaygroundColliderC Clone () {
PlaygroundColliderC playgroundCollider = new PlaygroundColliderC();
playgroundCollider.enabled = enabled;
playgroundCollider.transform = transform;
playgroundCollider.plane = new Plane(plane.normal, plane.distance);
playgroundCollider.offset = offset;
return playgroundCollider;
}
}
///
/// Hold information for axis constraints in X-, Y- and Z-values. These contraints are used to annihilate forces on set axis.
///
[Serializable]
public class PlaygroundAxisConstraintsC {
///
/// The constraint on X-axis.
///
public bool x = false;
///
/// The constraint on Y-axis.
///
public bool y = false;
///
/// The constraint on Z-axis.
///
public bool z = false;
///
/// Determines whether any constraints has been enabled.
///
/// true if any constraints are enabled; otherwise, false.
public bool HasConstraints () {
return x||y||z;
}
///
/// Clone this PlaygroundAxisConstraintsC.
///
public PlaygroundAxisConstraintsC Clone () {
PlaygroundAxisConstraintsC axisConstraints = new PlaygroundAxisConstraintsC();
axisConstraints.x = x;
axisConstraints.y = y;
axisConstraints.z = z;
return axisConstraints;
}
}
///
/// Contains information for a color gradient.
///
[Serializable]
public class PlaygroundGradientC {
public Gradient gradient = new Gradient();
///
/// Copies this gradient into the passed reference (copy).
///
/// Copy.
public void CopyTo (PlaygroundGradientC copy) {
copy.gradient.SetKeys (gradient.colorKeys, gradient.alphaKeys);
}
}
///
/// Holds information for a Playground Event.
///
[Serializable]
public class PlaygroundEventC {
///
/// Is this PlaygroundEvent enabled?
///
public bool enabled = true;
///
/// Should events be sent to PlaygroundC.particleEvent?
///
public bool sendToManager = false;
///
/// Has this PlaygroundEvent initialized with its target?
///
[NonSerialized] public bool initializedTarget = false;
///
/// Does this PlaygroundEvent have any subscribers to the particleEvent?
///
[NonSerialized] public bool initializedEvent = false;
///
/// The target particle system to send events to.
///
public PlaygroundParticlesC target;
///
/// The broadcast type of this event (A PlaygroundParticlesC target and/or Event Listeners).
///
public EVENTBROADCASTC broadcastType;
///
/// The type of event.
///
public EVENTTYPEC eventType;
///
/// The event of a particle (when using Event Listeners).
///
public event OnPlaygroundParticle particleEvent;
///
/// The inheritance method of position.
///
public EVENTINHERITANCEC eventInheritancePosition;
///
/// The inheritance method of velocity.
///
public EVENTINHERITANCEC eventInheritanceVelocity;
///
/// The inheritance method of color.
///
public EVENTINHERITANCEC eventInheritanceColor;
///
/// The position to send (if inheritance is User).
///
public Vector3 eventPosition;
///
/// The velocity to send (if inheritance is User).
///
public Vector3 eventVelocity;
///
/// The color to send (if inheritance is User).
///
public Color32 eventColor = Color.white;
///
/// The time between events (if type is set to Time).
///
public float eventTime = 1f;
///
/// The magnitude threshold to trigger collision events.
///
public float collisionThreshold = 10f;
///
/// The multiplier of velocity.
///
public float velocityMultiplier = 1f;
///
/// Calculated timer to trigger timed events.
///
float timer = 0f;
///
/// Initialize this Playground Event.
///
public void Initialize () {
initializedTarget = (target!=null && target.gameObject.activeSelf && target.gameObject.activeInHierarchy && target.enabled);
initializedEvent = (particleEvent!=null);
}
///
/// Determines if this Playground Event is ready to send a time-based event.
///
/// true, if time was updated, false otherwise.
public bool UpdateTime () {
bool readyToSend = false;
timer+=PlaygroundC.globalDeltaTime;
if (timer>=eventTime) {
readyToSend = true;
timer = 0f;
}
return readyToSend;
}
///
/// Sets the timer for time-based events.
///
/// New time.
public void SetTimer (float newTime) {
timer = newTime;
}
///
/// Sends the particle event.
///
/// Event particle.
public void SendParticleEvent (PlaygroundEventParticle eventParticle) {
if (initializedEvent)
particleEvent(eventParticle);
}
///
/// Return a copy of this PlaygroundEventC.
///
public PlaygroundEventC Clone () {
PlaygroundEventC playgroundEvent = new PlaygroundEventC();
playgroundEvent.enabled = enabled;
playgroundEvent.target = target;
playgroundEvent.eventType = eventType;
playgroundEvent.eventInheritancePosition = eventInheritancePosition;
playgroundEvent.eventInheritanceVelocity = eventInheritanceVelocity;
playgroundEvent.eventInheritanceColor = eventInheritanceColor;
playgroundEvent.eventPosition = eventPosition;
playgroundEvent.eventVelocity = eventVelocity;
playgroundEvent.eventColor = eventColor;
playgroundEvent.eventTime = eventTime;
playgroundEvent.collisionThreshold = collisionThreshold;
playgroundEvent.velocityMultiplier = velocityMultiplier;
playgroundEvent.particleEvent = particleEvent;
playgroundEvent.broadcastType = broadcastType;
return playgroundEvent;
}
}
///
/// The type of Manipulator.
///
public enum MANIPULATORTYPEC {
///
/// The Manipulator will remain passive. It will still be able to track particles and send events.
///
None,
///
/// Attract particles in a funnel shape.
///
Attractor,
///
/// Attract particles with spherical gravitation.
///
AttractorGravitational,
///
/// Repel particles away from the Manipulator.
///
Repellent,
///
/// The Manipulator will alter chosen property of the affected particles.
///
Property,
///
/// Combine properties into one Manipulator call.
///
Combined,
///
/// Apply forces with vortex-like features. Manipulator's rotation will determine the direction.
///
Vortex
}
///
/// The type of Manipulator Property.
///
public enum MANIPULATORPROPERTYTYPEC {
///
/// No property will be affected. The Manipulator will still be able to track particles and send events.
///
None,
///
/// Changes the color of particles within range.
///
Color,
///
/// Sets a static velocity of particles within range.
///
Velocity,
///
/// Adds velocity over time of particles within range.
///
AdditiveVelocity,
///
/// Changes size of particles within range.
///
Size,
///
/// Sets Transform targets for particles within range.
///
Target,
///
/// Sets particles to a sooner death.
///
Death,
///
/// Attract particles in a funnel shape. This is a main feature injected as a property so you can use it inside a Combined Manipulator.
///
Attractor,
///
/// Attract particles with spherical gravitation. This is a main feature injected as a property so you can use it inside a Combined Manipulator.
///
Gravitational,
///
/// Repel particles away from the Manipulator. This is a main feature injected as a property so you can use it inside a Combined Manipulator.
///
Repellent,
///
/// Change the lifetime color of particles within range. This is a main feature injected as a property so you can use it inside a Combined Manipulator.
///
LifetimeColor,
///
/// Apply forces with vortex-like features. Manipulator's rotation will determine the direction.
///
Vortex,
///
/// Sets a mesh vertices in the scene as target.
///
MeshTarget,
///
/// Sets a skinned mesh vertices in the scene as target.
///
SkinnedMeshTarget,
///
/// Apply turbulence for particles within range.
///
Turbulence,
///
/// Sets a State in the scene as target.
///
StateTarget,
///
/// Sets a Playground Spline in the scene as target.
///
SplineTarget,
///
/// Alters particle properties by common math operations.
///
Math
}
///
/// The math operation to apply within a MathManipulatorProperty class.
///
public enum MATHMANIPULATORTYPE {
///
/// Sine algorithm.
///
Sin,
///
/// Cosine algorithm.
///
Cos,
///
/// Linear interpolation algorithm.
///
Lerp,
///
/// Addition.
///
Add,
///
/// Subtraction.
///
Subtract
}
///
/// The particle property to change within a MathManipulatorProperty class.
///
public enum MATHMANIPULATORPROPERTY {
///
/// Particle size.
///
Size,
///
/// Particle rotation.
///
Rotation,
///
/// Particle velocity.
///
Velocity,
///
/// Particle position.
///
Position
}
///
/// The clamping (minimum to maximum) value to apply within a MathManipulatorProperty class.
///
public enum MATHMANIPULATORCLAMP {
///
/// No clamping will occur.
///
None,
///
/// The particle in-data will be clamped, before any changes has been made.
///
ClampInValue,
///
/// The particle out-data will be clamped, after the changes has been made.
///
ClampOutValue
}
///
/// The type of Manipulator Property Transition.
///
public enum MANIPULATORPROPERTYTRANSITIONC {
///
/// No transition of the property will occur.
///
None,
///
/// Transition the property from current particle value to the Manipulator Property's effect using linear interpolation.
///
Lerp,
///
/// Transition the property from current particle value to the Manipulator Property's effect using MoveTowards interpolation.
///
Linear
}
///
/// The shape of a Manipulator.
///
public enum MANIPULATORSHAPEC {
///
/// Spherical shape where the Manipulator's size will determine its extents.
///
Sphere,
///
/// A bounding box shape where the Manipulator's bounds will determine its extents.
///
Box,
///
/// The size of the Manipulator will be infinite over the scene and affect all particles. This option is the most performant as particle distance/containment check won't be necessary.
///
Infinite
}
public enum PLAYGROUNDORIGINC {
TopLeft, TopCenter, TopRight,
MiddleLeft, MiddleCenter, MiddleRight,
BottomLeft, BottomCenter, BottomRight
}
///
/// The mode to read pixels in.
///
public enum PIXELMODEC {
///
/// Bilinear pixel filtering.
///
Bilinear,
///
/// Pixel32 pixel filtering.
///
Pixel32
}
///
/// The mode to set particles color source from.
///
public enum COLORSOURCEC {
///
/// Colors will extract from the source such as pixel- or painted color.
///
Source,
///
/// Colors will extract from a color gradient over lifetime.
///
LifetimeColor,
///
/// Colors will extract from a list of color gradients over lifetime.
///
LifetimeColors
}
public enum COLORMETHOD {
Lifetime,
ParticleArray
}
///
/// The mode to overflow particles with when using Overflow Offset.
///
public enum OVERFLOWMODEC {
///
/// Overflow in the direction of the set Source Transform.
///
SourceTransform,
///
/// Overflow in world space direction.
///
World,
///
/// Overflow with normal direction of Source's points.
///
SourcePoint
}
///
/// The type of transition used for Snapshots.
///
public enum TRANSITIONTYPEC {
///
/// Transition with no easing.
///
Linear,
///
/// Transition with slow start - fast finish.
///
EaseIn,
///
/// Transition with fast start - slow finish.
///
EaseOut,
}
///
/// The individual type of transition used for Snapshots.
///
public enum INDIVIDUALTRANSITIONTYPEC {
///
/// Inherit the transition type selected for all Snapshots using INDIVIDUALTRANSITIONTYPEC.Inherit.
///
Inherit,
///
/// Transition with no easing.
///
Linear,
///
/// Transition with slow start - fast finish.
///
EaseIn,
///
/// Transition with fast start - slow finish.
///
EaseOut,
}
///
/// The linear interpolition type used for Snapshots.
///
public enum LERPTYPEC {
PositionColor,
Position,
Color,
}
///
/// The Source which particle birth positions will distribute from.
///
public enum SOURCEC {
///
/// Set birth positions from a mesh vertices or a texture's pixels. Use a Transform to be able to translate, rotate and scale your State.
///
State,
///
/// Set birth positions from a single transform.
///
Transform,
///
/// Set birth positions from a mesh vertices in the scene.
///
WorldObject,
///
/// Set birth positions from a skinned mesh vertices in the scene.
///
SkinnedWorldObject,
///
/// Emission will be controlled by script using PlaygroundParticlesC.Emit().
///
Script,
///
/// Set birth positions by painting onto colliders (2d/3d) in the scene.
///
Paint,
///
/// Project birth positions onto colliders (2d/3d) in the scene by using a texture. Note that this Source distribution is not multithreaded due to the non thread-safe Raycast method.
///
Projection,
///
/// Set birth positions from a Playground Spline.
///
Spline,
}
public enum SOURCEBIRTHMETHOD {
BirthPositions,
ParticlePositions
}
///
/// The scale method. This is mainly used for Playground Transforms and determines if local- or lossy scale should be used when setting a transform matrix.
///
public enum ScaleMethod {
///
/// Use local scale.
///
Local,
///
/// Use lossy scale.
///
Lossy
}
///
/// The lifetime sorting method.
///
public enum SORTINGC {
///
/// Sort particle emission randomly over their lifetime cycle.
///
Scrambled,
///
/// Sort particle emission randomly over their lifetime cycle and ensure consistent rate.
///
ScrambledLinear,
///
/// Sort particles to emit all at once.
///
Burst,
///
/// Sort particle emission alpha to omega in their Source structure.
///
Linear,
///
/// Sort particle emission omega to alpha in their Source structure.
///
Reversed,
///
/// Sort particle emission with an origin and use alpha to omega distance.
///
NearestNeighbor,
///
/// Sort particle emission with an origin and use omega to alpha distance.
///
NearestNeighborReversed,
///
/// Sort particle emission with an AnimationCurve. The X-axis represents the normalized lifetime cycle and Y-axis the normalized emission percentage.
///
Custom
}
///
/// The brush detail level.
///
public enum BRUSHDETAILC {
///
/// Every pixel will be read (100% of existing texture pixels).
///
Perfect,
///
/// Every second pixel will be read (50% of existing texture pixels).
///
High,
///
/// Every forth pixel will be read (25% of existing texture pixels).
///
Medium,
///
/// Every sixth pixel will be read (16.6% of existing texture pixels).
///
Low
}
///
/// The collision method.
///
public enum COLLISIONTYPEC {
///
/// Uses Raycast to detect colliders in scene.
///
Physics3D,
///
/// Uses Raycast2D to detect colliders in scene.
///
Physics2D
}
///
/// The type of velocity bending.
///
public enum VELOCITYBENDINGTYPEC {
///
/// Bending will be calculated from each particle's birth position delta (previous and current frame).
///
SourcePosition,
///
/// Bending will be calculated from each particle's position delta (previous and current frame).
///
ParticleDeltaPosition
}
///
/// The method to sort targets.
///
public enum TARGETSORTINGC {
Scrambled,
Linear,
Reversed
}
///
/// The method to sort particle masking.
///
public enum MASKSORTINGC {
Linear,
Reversed,
Scrambled
}
///
/// The method to set the Lifetime Sorting: Nearest Neighbor/Reversed with.
///
public enum NEARESTNEIGHBORORIGINMETHOD {
///
/// The origin will be set with an int of a generated source point.
///
SourcePoint,
///
/// The origin will be set by a Vector3 in world space.
///
Vector3,
///
/// The origin will be set from a Transform's position in the scene.
///
Transform
}
///
/// The method to target a spline.
///
public enum SPLINETARGETMETHOD {
///
/// Match each particle linearly within the particle array with the spline's normalized time.
///
SplineTime,
///
/// Match each particle's lifetime with the normalized time of the spline.
///
ParticleTime
}
///
/// The shape of a minimum to maximum Vector3.
///
public enum MINMAXVECTOR3METHOD {
Rectangular,
RectangularLinear,
Spherical,
SphericalLinear,
//SphericalSector,
//SphericalSectorLinear
}
///
/// The type of event.
///
public enum EVENTTYPEC {
Birth,
Death,
Collision,
Time
}
///
/// The type of event broadcast.
///
public enum EVENTBROADCASTC {
Target,
EventListeners,
Both
}
///
/// The inheritance method for events.
///
public enum EVENTINHERITANCEC {
User,
Particle,
Source
}
///
/// The type of turbulence algorithm to use.
///
public enum TURBULENCETYPE {
///
/// No turbulence will apply.
///
None,
///
/// Simplex noise will produce a natural branch pattern of turbulence.
///
Simplex,
///
/// Perlin noise will produce a confined wave-like pattern of turbulence.
///
Perlin
}
///
/// The value method used for lifetime.
///
public enum VALUEMETHOD {
Constant,
RandomBetweenTwoValues
}
///
/// The method to call when a particle system has finished simulating.
///
public enum ONDONE {
///
/// The GameObject of the particle system will inactivate.
///
Inactivate,
///
/// The GameObject of the particle system will be destroyed. This will only execute in Play-mode.
///
Destroy
}
///
/// The thread pool method determines which thread pooling should be used.
/// ThreadPoolMethod.ThreadPool will use the .NET managed ThreadPool class (standard in Particle Playground in versions prior to 3).
/// ThreadPoolMethod.PlaygroundPool will use the self-managed PlaygroundQueue which queues tasks on reused threads (standard in Particle Playground 3 and up).
///
public enum ThreadPoolMethod {
///
/// Uses the .NET managed ThreadPool class (standard in Particle Playground in versions prior to 3).
///
ThreadPool,
///
/// Uses the self-managed PlaygroundQueue which queues tasks on reused threads (standard in Particle Playground 3 and up).
///
PlaygroundPool
}
///
/// Multithreading method. This determines how particle systems calculate over the CPU. Keep in mind each thread will generate memory garbage which will be collected at some point.
/// Selecting ThreadMethod.NoThreads will make particle systems calculate on the main-thread.
/// ThreadMethod.OnePerSystem will create one thread per particle system each frame.
/// ThreadMethod.OneForAll will bundle all calculations into one single thread.
/// ThreadMethod.Automatic will distribute all particle systems evenly bundled along available CPUs/cores.
///
public enum ThreadMethod {
///
/// No calculation threads will be created. This will in most cases have a negative impact on performance as Particle Playground will calculate along all other logic on the main-thread.
/// Use this for debug purposes or if you know there's no multi- or hyperthreading possibilities on your target platform.
///
NoThreads,
///
/// One calculation thread per particle system will be created. Use this when having heavy particle systems in your scene.
/// Note that this method will never bundle calculation calls unless specified in each individual particle system’s Particle Thread Method.
///
OnePerSystem,
///
/// One calculation thread for all particle systems will be created. Use this if you have other multithreaded logic which has higher performance priority than Particle Playground or your project demands strict use of garbage collection.
/// Consider using ThreadMethod.Automatic for best performance.
///
OneForAll,
///
/// Let calculation threads distribute evenly for all particle systems in your scene. This will bundle calculation calls to match the platform's SystemInfo.processorCount.
/// This is the recommended and overall fastest method to calculate particle systems.
/// Having fewer particle systems than processing units will create one thread per particle system. Having more particle systems than processing units will initiate thread bundling.
///
Automatic
}
///
/// The multithreading method for a single particle system. Use this to bypass the selected PlaygroundC.threadMethod.
/// ThreadMethodLocal.Inherit will let the particle system calculate as set by PlaygroundC.threadMethod. This is the default value.
/// ThreadMethodLocal.NoThreads will make the particle system calculate on the main-thread.
/// ThreadMethodLocal.OnePerSystem will create a new thread for this particle system.
/// ThreadMethodLocal.OneForAll will create a bundled thread for all particle systems using this setting.
///
public enum ThreadMethodLocal {
///
/// Let the particle system calculate as set by ThreadMethod. This is the default value.
///
Inherit,
///
/// The particle system will be calculated on the main-thread.
///
NoThreads,
///
/// Creates a new thread for this particle system.
///
OnePerSystem,
///
/// Bundle all particle systems using this setting into a single thread call.
///
OneForAll
}
///
/// The multithreading method for a particle system component such as tubulence and skinned meshes. This determines how the components will calculate over the CPU.
///
public enum ThreadMethodComponent {
///
/// The component will calculate inside the chosen particle system multithreading method.
///
InsideParticleCalculation,
///
/// Each component will create a new calculation thread.
///
OnePerSystem,
///
/// All components of type will create a single bundled calculation thread.
///
OneForAll
}
///
/// Tracking method determines how particles are compared within a Manipulator. This is used when tracking particles to determine if a particle exists within a Manipulator.
/// Using Manipulator id is the fastest but may not work on overlapping Manipulators. Use this method if you have plenty of particles.
/// Particle id will always return the correct compare, but requires a particle-to-particle lookup. Use this method if you have few particles with several Manipulators overlapping.
///
public enum TrackingMethod {
///
/// Using Manipulator id is fast but may not work on overlapping Manipulators. Use this method if you have plenty of particles.
///
ManipulatorId,
///
/// Particle id will always return the correct compare, but requires a particle-to-particle lookup. Use this method if you have few particles with several Manipulators overlapping.
///
ParticleId
}
///
/// Animation curve extensions.
///
public static class AnimationCurveExtensions {
///
/// Resets the AnimationCurve with two keyframes at time 0 and 1, values are 0.
///
/// Animation Curve.
public static void Reset (this AnimationCurve animationCurve) {
if (animationCurve==null)
animationCurve = new AnimationCurve();
Keyframe[] keys = new Keyframe[2];
keys[1].time = 1f;
animationCurve.keys = keys;
}
///
/// Resets the AnimationCurve with two keyframes at time 0 and 1, values are 1.
///
/// Animation Curve.
public static void Reset1 (this AnimationCurve animationCurve) {
if (animationCurve==null)
animationCurve = new AnimationCurve();
Keyframe[] keys = new Keyframe[2];
keys[1].time = 1f;
keys[0].value = 1f;
keys[1].value = 1f;
animationCurve.keys = keys;
}
public static void Reset01 (this AnimationCurve animationCurve) {
if (animationCurve==null)
animationCurve = new AnimationCurve();
Keyframe[] keys = new Keyframe[2];
keys[1].time = 1f;
keys[0].value = 0;
keys[1].value = 1f;
animationCurve.keys = keys;
}
}
///
/// Event delegate for sending a PlaygroundEventParticle to any event listeners.
///
public delegate void OnPlaygroundParticle(PlaygroundEventParticle particle);
}