VolumetricDustParticles.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. #if UNITY_5_5_OR_NEWER
  2. #define PARTICLES_SUPPORTED
  3. #endif
  4. using UnityEngine;
  5. namespace VLB
  6. {
  7. [ExecuteInEditMode]
  8. [DisallowMultipleComponent]
  9. [RequireComponent(typeof(VolumetricLightBeam))]
  10. [HelpURL(Consts.HelpUrlDustParticles)]
  11. public class VolumetricDustParticles : MonoBehaviour
  12. {
  13. /// <summary>
  14. /// Max alpha of the particles
  15. /// </summary>
  16. [Range(0f, 1f)]
  17. public float alpha = 0.5f;
  18. /// <summary>
  19. /// Max size of the particles
  20. /// </summary>
  21. [Range(0.0001f, 0.1f)]
  22. public float size = 0.01f;
  23. /// <summary>
  24. /// Direction of the particles.
  25. /// </summary>
  26. public ParticlesDirection direction = ParticlesDirection.Random;
  27. /// <summary>
  28. /// Movement speed of the particles.
  29. /// </summary>
  30. public Vector3 velocity = new Vector3(0.0f, 0.0f, 0.03f);
  31. [System.Obsolete("Use 'velocity' instead")]
  32. public float speed = 0.03f;
  33. /// <summary>
  34. /// Control how many particles are spawned. The higher the density, the more particles are spawned, the higher the performance cost is.
  35. /// </summary>
  36. public float density = 5f;
  37. /// <summary>
  38. /// The minimum distance (from the light source) where the particles are spawned.
  39. /// The higher it is, the more the particles are spawned away from the light source.
  40. /// </summary>
  41. [Range(0f, 1f)]
  42. public float spawnMinDistance = 0f;
  43. /// <summary>
  44. /// The maximum distance (from the light source) where the particles are spawned.
  45. /// The lower it is, the more the particles are gathered near the light source.
  46. /// </summary>
  47. [Range(0f, 1f)]
  48. public float spawnMaxDistance = 0.7f;
  49. /// <summary>
  50. /// Enable particles culling based on the distance to the Main Camera.
  51. /// We highly recommend to enable this feature to keep good runtime performances.
  52. /// </summary>
  53. public bool cullingEnabled = true;
  54. /// <summary>
  55. /// If culling is enabled, the particles will not be rendered if they are further than cullingMaxDistance to the Main Camera.
  56. /// </summary>
  57. public float cullingMaxDistance = 10f;
  58. /// <summary>
  59. /// Is the particle system currently culled (no visible) because too far from the main camera?
  60. /// </summary>
  61. public bool isCulled { get; private set; }
  62. #if PARTICLES_SUPPORTED
  63. public static bool isFeatureSupported = true;
  64. public bool particlesAreInstantiated { get { return m_Particles; } }
  65. public int particlesCurrentCount { get { return m_Particles ? m_Particles.particleCount : 0; } }
  66. public int particlesMaxCount { get { return m_Particles ? m_Particles.main.maxParticles : 0; } }
  67. ParticleSystem m_Particles = null;
  68. ParticleSystemRenderer m_Renderer = null;
  69. #else
  70. public static bool isFeatureSupported = false;
  71. public bool particlesAreInstantiated { get { return false; } }
  72. public int particlesCurrentCount { get { return 0; } }
  73. public int particlesMaxCount { get { return 0; } }
  74. #endif
  75. /// <summary>Cached version of Camera.main, for performance reasons</summary>
  76. public Camera mainCamera
  77. {
  78. get
  79. {
  80. if (!ms_MainCamera)
  81. {
  82. ms_MainCamera = Camera.main;
  83. if (!ms_MainCamera && !ms_NoMainCameraLogged)
  84. {
  85. Debug.LogErrorFormat(gameObject, "In order to use 'VolumetricDustParticles' culling, you must have a MainCamera defined in your scene.");
  86. ms_NoMainCameraLogged = true;
  87. }
  88. }
  89. return ms_MainCamera;
  90. }
  91. }
  92. // Cache the main camera, because accessing Camera.main at each frame is very bad performance-wise
  93. static bool ms_NoMainCameraLogged = false;
  94. static Camera ms_MainCamera = null;
  95. #if UNITY_EDITOR
  96. void OnValidate()
  97. {
  98. density = Mathf.Clamp(density, 0f, 1000f);
  99. cullingMaxDistance = Mathf.Max(cullingMaxDistance, 1f);
  100. #if PARTICLES_SUPPORTED
  101. // support instant refresh when modifying properties from inspector
  102. if (m_Particles)
  103. {
  104. SetParticleProperties(); // mandatory to update with the latest values
  105. m_Particles.Simulate(0f);
  106. m_Particles.Play();
  107. }
  108. #endif
  109. }
  110. #endif
  111. #if PARTICLES_SUPPORTED
  112. VolumetricLightBeam m_Master = null;
  113. void Start()
  114. {
  115. isCulled = false;
  116. m_Master = GetComponent<VolumetricLightBeam>();
  117. Debug.Assert(m_Master);
  118. HandleBackwardCompatibility(m_Master._INTERNAL_pluginVersion, Version.Current);
  119. InstantiateParticleSystem();
  120. SetActiveAndPlay();
  121. }
  122. void InstantiateParticleSystem()
  123. {
  124. // If we duplicate (from Editor and Playmode) the VLB, the children are also duplicated (like the dust particles)
  125. // we have to make sure to properly destroy them before creating our proper procedural particle instance.
  126. var slaves = GetComponentsInChildren<ParticleSystem>(true);
  127. for (int i = slaves.Length - 1; i >= 0; --i)
  128. DestroyImmediate(slaves[i].gameObject);
  129. m_Particles = Config.Instance.NewVolumetricDustParticles();
  130. if (m_Particles)
  131. {
  132. #if UNITY_EDITOR
  133. if (m_Master)
  134. {
  135. UnityEditor.GameObjectUtility.SetStaticEditorFlags(m_Particles.gameObject, m_Master.GetStaticEditorFlagsForSubObjects());
  136. m_Particles.gameObject.SetSameSceneVisibilityStatesThan(m_Master.gameObject);
  137. }
  138. #endif
  139. m_Particles.transform.SetParent(transform, false);
  140. m_Particles.transform.localRotation = m_Master.beamInternalLocalRotation;
  141. m_Renderer = m_Particles.GetComponent<ParticleSystemRenderer>();
  142. }
  143. }
  144. void OnEnable() { SetActiveAndPlay(); }
  145. void SetActiveAndPlay()
  146. {
  147. if (m_Particles)
  148. {
  149. m_Particles.gameObject.SetActive(true);
  150. SetParticleProperties();
  151. m_Particles.Play(true);
  152. }
  153. }
  154. void OnDisable()
  155. {
  156. if (m_Particles) m_Particles.gameObject.SetActive(false);
  157. }
  158. void OnDestroy()
  159. {
  160. if (m_Particles) DestroyImmediate(m_Particles.gameObject); // Make sure to delete the GAO
  161. m_Particles = null;
  162. }
  163. void Update()
  164. {
  165. #if UNITY_EDITOR
  166. if (!m_Particles && !Application.isPlaying)
  167. InstantiateParticleSystem();
  168. #endif
  169. if(Application.isPlaying)
  170. UpdateCulling();
  171. SetParticleProperties();
  172. }
  173. void SetParticleProperties()
  174. {
  175. if (m_Particles && m_Particles.gameObject.activeSelf)
  176. {
  177. var thickness = Mathf.Clamp01(1 - (m_Master.fresnelPow / Consts.FresnelPowMaxValue));
  178. if (spawnMinDistance > spawnMaxDistance)
  179. Utils.Swap(ref spawnMinDistance, ref spawnMaxDistance);
  180. var coneLength = m_Master.fallOffEnd * (spawnMaxDistance - spawnMinDistance);
  181. var ratePerSec = coneLength * density;
  182. int maxParticles = (int)(ratePerSec * 4);
  183. var main = m_Particles.main;
  184. var startLifetime = main.startLifetime;
  185. startLifetime.mode = ParticleSystemCurveMode.TwoConstants;
  186. startLifetime.constantMin = 4f;
  187. startLifetime.constantMax = 6f;
  188. main.startLifetime = startLifetime;
  189. var startSize = main.startSize;
  190. startSize.mode = ParticleSystemCurveMode.TwoConstants;
  191. startSize.constantMin = size * 0.9f;
  192. startSize.constantMax = size * 1.1f;
  193. main.startSize = startSize;
  194. var startColor = main.startColor;
  195. if(m_Master.usedColorMode == ColorMode.Flat)
  196. {
  197. startColor.mode = ParticleSystemGradientMode.Color;
  198. var colorMax = m_Master.color;
  199. colorMax.a *= alpha;
  200. startColor.color = colorMax;
  201. }
  202. else
  203. {
  204. startColor.mode = ParticleSystemGradientMode.Gradient;
  205. // Duplicate gradient and apply alpha
  206. var gradientRef = m_Master.colorGradient;
  207. var colorKeys = gradientRef.colorKeys;
  208. var alphaKeys = gradientRef.alphaKeys;
  209. for(int i=0; i< alphaKeys.Length; ++i)
  210. alphaKeys[i].alpha *= alpha;
  211. var newGradient = new Gradient();
  212. newGradient.SetKeys(colorKeys, alphaKeys);
  213. startColor.gradient = newGradient;
  214. }
  215. main.startColor = startColor;
  216. {
  217. var startSpeed = main.startSpeed;
  218. startSpeed.constant = (direction == ParticlesDirection.Random) ? Mathf.Abs(velocity.z) : 0.0f;
  219. main.startSpeed = startSpeed;
  220. }
  221. {
  222. var velocityOverLifetime = m_Particles.velocityOverLifetime;
  223. velocityOverLifetime.enabled = (direction != ParticlesDirection.Random);
  224. velocityOverLifetime.space = (direction == ParticlesDirection.LocalSpace) ? ParticleSystemSimulationSpace.Local : ParticleSystemSimulationSpace.World;
  225. velocityOverLifetime.xMultiplier = velocity.x;
  226. velocityOverLifetime.yMultiplier = velocity.y;
  227. velocityOverLifetime.zMultiplier = velocity.z;
  228. }
  229. main.maxParticles = maxParticles;
  230. {
  231. var shape = m_Particles.shape;
  232. shape.shapeType = ParticleSystemShapeType.ConeVolume;
  233. float coneAngle = m_Master.coneAngle * Mathf.Lerp(0.7f, 1f, thickness);
  234. shape.angle = coneAngle * 0.5f;
  235. float radiusStart = m_Master.coneRadiusStart * Mathf.Lerp(0.3f, 1.0f, thickness);
  236. float radiusEnd = Utils.ComputeConeRadiusEnd(m_Master.fallOffEnd, coneAngle);
  237. shape.radius = Mathf.Lerp(radiusStart, radiusEnd, spawnMinDistance);
  238. shape.length = coneLength;
  239. var localOffset = m_Master.fallOffEnd * spawnMinDistance;
  240. #if UNITY_2017_1_OR_NEWER
  241. shape.position = new Vector3(0f, 0f, localOffset);
  242. #else
  243. m_Particles.transform.localPosition = m_Master.beamLocalForward * localOffset;
  244. #endif
  245. shape.arc = 360f;
  246. shape.randomDirectionAmount = (direction == ParticlesDirection.Random) ? 1f : 0f;
  247. }
  248. var emission = m_Particles.emission;
  249. var rate = emission.rateOverTime;
  250. rate.constant = ratePerSec;
  251. emission.rateOverTime = rate;
  252. if(m_Renderer)
  253. {
  254. m_Renderer.sortingLayerID = m_Master.sortingLayerID;
  255. m_Renderer.sortingOrder = m_Master.sortingOrder;
  256. }
  257. }
  258. }
  259. void HandleBackwardCompatibility(int serializedVersion, int newVersion)
  260. {
  261. if (serializedVersion == -1) return; // freshly new spawned entity: nothing to do
  262. if (serializedVersion == newVersion) return; // same version: nothing to do
  263. if (serializedVersion < 1880)
  264. {
  265. // Version 1880 changed the order of ParticlesDirection enum and add WorldSpace option
  266. if ((int)direction == 0) direction = (ParticlesDirection)1;
  267. else direction = (ParticlesDirection)0;
  268. #pragma warning disable 0618
  269. // Version 1880 changed from single float speed to 3D velocity vector
  270. velocity = new Vector3(0.0f, 0.0f, speed);
  271. #pragma warning restore 0618
  272. }
  273. Utils.MarkCurrentSceneDirty();
  274. }
  275. #region Culling
  276. void UpdateCulling()
  277. {
  278. if (m_Particles)
  279. {
  280. bool visible = true;
  281. if ((cullingEnabled || m_Master.isFadeOutEnabled) && m_Master.hasGeometry)
  282. {
  283. if (mainCamera)
  284. {
  285. var maxDist = cullingMaxDistance;
  286. if (m_Master.isFadeOutEnabled) maxDist = Mathf.Min(maxDist, m_Master.fadeOutEnd);
  287. var maxDistSqr = maxDist * maxDist;
  288. var distSqr = m_Master.bounds.SqrDistance(mainCamera.transform.position);
  289. visible = distSqr <= maxDistSqr;
  290. }
  291. else
  292. cullingEnabled = false;
  293. }
  294. if (m_Particles.gameObject.activeSelf != visible)
  295. {
  296. m_Particles.gameObject.SetActive(visible);
  297. isCulled = !visible;
  298. }
  299. if (visible && !m_Particles.isPlaying)
  300. m_Particles.Play();
  301. }
  302. }
  303. #endregion
  304. #endif
  305. }
  306. }