BeamGeometry.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #if DEBUG
  2. //#define DEBUG_SHOW_MESH_NORMALS
  3. #endif
  4. #define FORCE_CURRENT_CAMERA_DEPTH_TEXTURE_MODE
  5. #if UNITY_2018_1_OR_NEWER
  6. #define VLB_SRP_SUPPORT // Comment this to disable SRP support
  7. #endif
  8. using UnityEngine;
  9. using System.Collections;
  10. #pragma warning disable 0429, 0162 // Unreachable expression code detected (because of Noise3D.isSupported on mobile)
  11. namespace VLB
  12. {
  13. [AddComponentMenu("")] // hide it from Component search
  14. [ExecuteInEditMode]
  15. [HelpURL(Consts.HelpUrlBeam)]
  16. public class BeamGeometry : MonoBehaviour, MaterialModifier.Interface
  17. {
  18. VolumetricLightBeam m_Master = null;
  19. Matrix4x4 m_ColorGradientMatrix;
  20. MeshType m_CurrentMeshType = MeshType.Shared;
  21. Material m_CustomMaterial = null;
  22. MaterialModifier.Callback m_MaterialModifierCallback = null;
  23. Coroutine m_CoFadeOut = null;
  24. public MeshRenderer meshRenderer { get; private set; }
  25. public MeshFilter meshFilter { get; private set; }
  26. public Mesh coneMesh { get; private set; }
  27. public bool visible
  28. {
  29. get { return meshRenderer.enabled; }
  30. set { meshRenderer.enabled = value; }
  31. }
  32. public int sortingLayerID
  33. {
  34. get { return meshRenderer.sortingLayerID; }
  35. set { meshRenderer.sortingLayerID = value; }
  36. }
  37. public int sortingOrder
  38. {
  39. get { return meshRenderer.sortingOrder; }
  40. set { meshRenderer.sortingOrder = value; }
  41. }
  42. public bool _INTERNAL_IsFadeOutCoroutineRunning { get { return m_CoFadeOut != null; } }
  43. float ComputeFadeOutFactor(Transform camTransform)
  44. {
  45. if (m_Master.isFadeOutEnabled)
  46. {
  47. float distanceCamToBeam = Vector3.SqrMagnitude(meshRenderer.bounds.center - camTransform.position);
  48. return Mathf.InverseLerp(m_Master.fadeOutEnd * m_Master.fadeOutEnd, m_Master.fadeOutBegin * m_Master.fadeOutBegin, distanceCamToBeam);
  49. }
  50. else
  51. {
  52. return 1.0f;
  53. }
  54. }
  55. IEnumerator CoUpdateFadeOut()
  56. {
  57. while (m_Master.isFadeOutEnabled)
  58. {
  59. ComputeFadeOutFactor();
  60. yield return null;
  61. }
  62. SetFadeOutFactorProp(1.0f);
  63. m_CoFadeOut = null;
  64. }
  65. void ComputeFadeOutFactor()
  66. {
  67. var camTransform = Config.Instance.fadeOutCameraTransform;
  68. if (camTransform)
  69. {
  70. float fadeOutFactor = ComputeFadeOutFactor(camTransform);
  71. SetFadeOutFactorProp(fadeOutFactor);
  72. }
  73. else
  74. {
  75. SetFadeOutFactorProp(1.0f);
  76. }
  77. }
  78. void SetFadeOutFactorProp(float value)
  79. {
  80. if (value > 0)
  81. {
  82. meshRenderer.enabled = true;
  83. MaterialChangeStart();
  84. SetMaterialProp(ShaderProperties.FadeOutFactor, value);
  85. MaterialChangeStop();
  86. }
  87. else
  88. {
  89. meshRenderer.enabled = false;
  90. }
  91. }
  92. public void RestartFadeOutCoroutine()
  93. {
  94. #if UNITY_EDITOR
  95. if (Application.isPlaying)
  96. #endif
  97. {
  98. if (m_CoFadeOut != null)
  99. {
  100. StopCoroutine(m_CoFadeOut);
  101. m_CoFadeOut = null;
  102. }
  103. if (m_Master && m_Master.isFadeOutEnabled)
  104. {
  105. m_CoFadeOut = StartCoroutine(CoUpdateFadeOut());
  106. }
  107. }
  108. }
  109. void Start()
  110. {
  111. // Handle copy / paste the LightBeam in Editor
  112. if (!m_Master)
  113. DestroyImmediate(gameObject);
  114. }
  115. void OnDestroy()
  116. {
  117. if (m_CustomMaterial)
  118. {
  119. DestroyImmediate(m_CustomMaterial);
  120. m_CustomMaterial = null;
  121. }
  122. }
  123. #if VLB_SRP_SUPPORT
  124. Camera m_CurrentCameraRenderingSRP = null;
  125. void OnDisable()
  126. {
  127. SRPHelper.UnregisterOnBeginCameraRendering(OnBeginCameraRenderingSRP);
  128. m_CurrentCameraRenderingSRP = null;
  129. }
  130. public static bool isCustomRenderPipelineSupported { get { return true; } }
  131. #else
  132. public static bool isCustomRenderPipelineSupported { get { return false; } }
  133. #endif
  134. bool shouldUseGPUInstancedMaterial
  135. { get {
  136. return m_Master._INTERNAL_DynamicOcclusionMode != MaterialManager.DynamicOcclusion.DepthTexture // sampler cannot be passed to shader as instanced property
  137. && Config.Instance.actualRenderingMode == RenderingMode.GPUInstancing;
  138. }}
  139. void OnEnable()
  140. {
  141. // When a GAO is disabled, all its coroutines are killed, so renable them on OnEnable.
  142. RestartFadeOutCoroutine();
  143. #if VLB_SRP_SUPPORT
  144. SRPHelper.RegisterOnBeginCameraRendering(OnBeginCameraRenderingSRP);
  145. #endif
  146. }
  147. public void Initialize(VolumetricLightBeam master)
  148. {
  149. Debug.Assert(master != null);
  150. var customHideFlags = Consts.ProceduralObjectsHideFlags;
  151. m_Master = master;
  152. transform.SetParent(master.transform, false);
  153. meshRenderer = gameObject.GetOrAddComponent<MeshRenderer>();
  154. meshRenderer.hideFlags = customHideFlags;
  155. meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  156. meshRenderer.receiveShadows = false;
  157. meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; // different reflection probes could break batching with GPU Instancing
  158. #if UNITY_5_4_OR_NEWER
  159. meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
  160. #else
  161. meshRenderer.useLightProbes = false;
  162. #endif
  163. if (!shouldUseGPUInstancedMaterial)
  164. {
  165. m_CustomMaterial = MaterialManager.NewMaterialTransient(gpuInstanced:false);
  166. ApplyMaterial();
  167. }
  168. if (SortingLayer.IsValid(m_Master.sortingLayerID))
  169. sortingLayerID = m_Master.sortingLayerID;
  170. else
  171. Debug.LogError(string.Format("Beam '{0}' has an invalid sortingLayerID ({1}). Please fix it by setting a valid layer.", Utils.GetPath(m_Master.transform), m_Master.sortingLayerID));
  172. sortingOrder = m_Master.sortingOrder;
  173. meshFilter = gameObject.GetOrAddComponent<MeshFilter>();
  174. meshFilter.hideFlags = customHideFlags;
  175. gameObject.hideFlags = customHideFlags;
  176. #if UNITY_EDITOR
  177. UnityEditor.GameObjectUtility.SetStaticEditorFlags(gameObject, master.GetStaticEditorFlagsForSubObjects());
  178. gameObject.SetSameSceneVisibilityStatesThan(master.gameObject);
  179. #endif
  180. RestartFadeOutCoroutine();
  181. }
  182. /// <summary>
  183. /// Generate the cone mesh and calls UpdateMaterialAndBounds.
  184. /// Since this process involves recreating a new mesh, make sure to not call it at every frame during playtime.
  185. /// </summary>
  186. public void RegenerateMesh()
  187. {
  188. Debug.Assert(m_Master);
  189. if (Config.Instance.geometryOverrideLayer)
  190. gameObject.layer = Config.Instance.geometryLayerID;
  191. else
  192. gameObject.layer = m_Master.gameObject.layer;
  193. gameObject.tag = Config.Instance.geometryTag;
  194. if (coneMesh && m_CurrentMeshType == MeshType.Custom)
  195. {
  196. DestroyImmediate(coneMesh);
  197. }
  198. m_CurrentMeshType = m_Master.geomMeshType;
  199. switch (m_Master.geomMeshType)
  200. {
  201. case MeshType.Custom:
  202. {
  203. coneMesh = MeshGenerator.GenerateConeZ_Radius(1f, 1f, 1f, m_Master.geomCustomSides, m_Master.geomCustomSegments, m_Master.geomCap, Config.Instance.requiresDoubleSidedMesh);
  204. coneMesh.hideFlags = Consts.ProceduralObjectsHideFlags;
  205. meshFilter.mesh = coneMesh;
  206. break;
  207. }
  208. case MeshType.Shared:
  209. {
  210. coneMesh = GlobalMesh.Get();
  211. meshFilter.sharedMesh = coneMesh;
  212. break;
  213. }
  214. default:
  215. {
  216. Debug.LogError("Unsupported MeshType");
  217. break;
  218. }
  219. }
  220. UpdateMaterialAndBounds();
  221. }
  222. Vector3 ComputeLocalMatrix()
  223. {
  224. // In the VS, we compute the vertices so the whole beam fits into a fixed 2x2x1 box.
  225. // We have to apply some scaling to get the proper beam size.
  226. // This way we have the proper bounds without having to recompute specific bounds foreach beam.
  227. var maxRadius = Mathf.Max(m_Master.coneRadiusStart, m_Master.coneRadiusEnd);
  228. transform.localScale = new Vector3(maxRadius, maxRadius, m_Master.maxGeometryDistance);
  229. transform.localRotation = m_Master.beamInternalLocalRotation;
  230. return transform.localScale;
  231. }
  232. bool isNoiseEnabled { get { return m_Master.isNoiseEnabled && m_Master.noiseIntensity > 0f && Noise3D.isSupported; } } // test Noise3D.isSupported the last
  233. #pragma warning disable 0162
  234. bool isDepthBlendEnabled { get { return BatchingHelper.forceEnableDepthBlend || m_Master.depthBlendDistance > 0f; } }
  235. #pragma warning restore 0162
  236. bool ApplyMaterial()
  237. {
  238. var colorGradient = MaterialManager.ColorGradient.Off;
  239. if (m_Master.colorMode == ColorMode.Gradient)
  240. {
  241. var precision = Utils.GetFloatPackingPrecision();
  242. colorGradient = precision == Utils.FloatPackingPrecision.High ? MaterialManager.ColorGradient.MatrixHigh : MaterialManager.ColorGradient.MatrixLow;
  243. }
  244. Debug.Assert((int)BlendingMode.Additive == (int)MaterialManager.BlendingMode.Additive);
  245. Debug.Assert((int)BlendingMode.SoftAdditive == (int)MaterialManager.BlendingMode.SoftAdditive);
  246. Debug.Assert((int)BlendingMode.TraditionalTransparency == (int)MaterialManager.BlendingMode.TraditionalTransparency);
  247. var staticProps = new MaterialManager.StaticProperties
  248. {
  249. blendingMode = (MaterialManager.BlendingMode)m_Master.blendingMode,
  250. noise3D = isNoiseEnabled ? MaterialManager.Noise3D.On : MaterialManager.Noise3D.Off,
  251. depthBlend = isDepthBlendEnabled ? MaterialManager.DepthBlend.On : MaterialManager.DepthBlend.Off,
  252. colorGradient = colorGradient,
  253. dynamicOcclusion = m_Master._INTERNAL_DynamicOcclusionMode_Runtime,
  254. meshSkewing = m_Master.hasMeshSkewing ? MaterialManager.MeshSkewing.On : MaterialManager.MeshSkewing.Off,
  255. shaderAccuracy = (m_Master.shaderAccuracy == ShaderAccuracy.Fast) ? MaterialManager.ShaderAccuracy.Fast : MaterialManager.ShaderAccuracy.High
  256. };
  257. Material mat = null;
  258. if (!shouldUseGPUInstancedMaterial)
  259. {
  260. mat = m_CustomMaterial;
  261. if(mat)
  262. staticProps.ApplyToMaterial(mat);
  263. }
  264. else
  265. {
  266. mat = MaterialManager.GetInstancedMaterial(m_Master._INTERNAL_InstancedMaterialGroupID, staticProps);
  267. }
  268. meshRenderer.material = mat;
  269. return mat != null;
  270. }
  271. public void SetMaterialProp(int nameID, float value)
  272. {
  273. if (m_CustomMaterial)
  274. m_CustomMaterial.SetFloat(nameID, value);
  275. else
  276. MaterialManager.materialPropertyBlock.SetFloat(nameID, value);
  277. }
  278. public void SetMaterialProp(int nameID, Vector4 value)
  279. {
  280. if (m_CustomMaterial)
  281. m_CustomMaterial.SetVector(nameID, value);
  282. else
  283. MaterialManager.materialPropertyBlock.SetVector(nameID, value);
  284. }
  285. public void SetMaterialProp(int nameID, Color value)
  286. {
  287. if (m_CustomMaterial)
  288. m_CustomMaterial.SetColor(nameID, value);
  289. else
  290. MaterialManager.materialPropertyBlock.SetColor(nameID, value);
  291. }
  292. public void SetMaterialProp(int nameID, Matrix4x4 value)
  293. {
  294. if (m_CustomMaterial)
  295. m_CustomMaterial.SetMatrix(nameID, value);
  296. else
  297. MaterialManager.materialPropertyBlock.SetMatrix(nameID, value);
  298. }
  299. public void SetMaterialProp(int nameID, Texture value)
  300. {
  301. if (m_CustomMaterial)
  302. m_CustomMaterial.SetTexture(nameID, value);
  303. else
  304. Debug.LogError("Setting a Texture property to a GPU instanced material is not supported");
  305. }
  306. void MaterialChangeStart()
  307. {
  308. if (m_CustomMaterial == null)
  309. meshRenderer.GetPropertyBlock(MaterialManager.materialPropertyBlock);
  310. }
  311. void MaterialChangeStop()
  312. {
  313. if (m_CustomMaterial == null)
  314. meshRenderer.SetPropertyBlock(MaterialManager.materialPropertyBlock);
  315. }
  316. public void SetDynamicOcclusionCallback(string shaderKeyword, MaterialModifier.Callback cb)
  317. {
  318. m_MaterialModifierCallback = cb;
  319. if (m_CustomMaterial)
  320. {
  321. m_CustomMaterial.SetKeywordEnabled(shaderKeyword, cb != null);
  322. if (cb != null)
  323. cb(this);
  324. }
  325. else
  326. UpdateMaterialAndBounds();
  327. }
  328. public void UpdateMaterialAndBounds()
  329. {
  330. Debug.Assert(m_Master);
  331. if (ApplyMaterial() == false)
  332. {
  333. return;
  334. }
  335. MaterialChangeStart();
  336. {
  337. if (m_CustomMaterial == null)
  338. {
  339. if(m_MaterialModifierCallback != null)
  340. m_MaterialModifierCallback(this);
  341. }
  342. float slopeRad = (m_Master.coneAngle * Mathf.Deg2Rad) / 2; // use coneAngle (instead of spotAngle) which is more correct with the geometry
  343. SetMaterialProp(ShaderProperties.ConeSlopeCosSin, new Vector2(Mathf.Cos(slopeRad), Mathf.Sin(slopeRad)));
  344. // kMinRadius and kMinApexOffset prevents artifacts when fresnel computation is done in the vertex shader
  345. const float kMinRadius = 0.0001f;
  346. var coneRadius = new Vector2(Mathf.Max(m_Master.coneRadiusStart, kMinRadius), Mathf.Max(m_Master.coneRadiusEnd, kMinRadius));
  347. SetMaterialProp(ShaderProperties.ConeRadius, coneRadius);
  348. const float kMinApexOffset = 0.0001f;
  349. float nonNullApex = Mathf.Sign(m_Master.coneApexOffsetZ) * Mathf.Max(Mathf.Abs(m_Master.coneApexOffsetZ), kMinApexOffset);
  350. SetMaterialProp(ShaderProperties.ConeApexOffsetZ, nonNullApex);
  351. if (m_Master.usedColorMode == ColorMode.Flat)
  352. {
  353. SetMaterialProp(ShaderProperties.ColorFlat, m_Master.color);
  354. }
  355. else
  356. {
  357. var precision = Utils.GetFloatPackingPrecision();
  358. m_ColorGradientMatrix = m_Master.colorGradient.SampleInMatrix((int)precision);
  359. // pass the gradient matrix in OnWillRenderObject()
  360. }
  361. float intensityInside, intensityOutside;
  362. m_Master.GetInsideAndOutsideIntensity(out intensityInside, out intensityOutside);
  363. SetMaterialProp(ShaderProperties.AlphaInside, intensityInside);
  364. SetMaterialProp(ShaderProperties.AlphaOutside, intensityOutside);
  365. SetMaterialProp(ShaderProperties.AttenuationLerpLinearQuad, m_Master.attenuationLerpLinearQuad);
  366. SetMaterialProp(ShaderProperties.DistanceFallOff, new Vector3(m_Master.fallOffStart, m_Master.fallOffEnd, m_Master.maxGeometryDistance));
  367. SetMaterialProp(ShaderProperties.DistanceCamClipping, m_Master.cameraClippingDistance);
  368. SetMaterialProp(ShaderProperties.FresnelPow, Mathf.Max(0.001f, m_Master.fresnelPow)); // no pow 0, otherwise will generate inf fresnel and issues on iOS
  369. SetMaterialProp(ShaderProperties.GlareBehind, m_Master.glareBehind);
  370. SetMaterialProp(ShaderProperties.GlareFrontal, m_Master.glareFrontal);
  371. SetMaterialProp(ShaderProperties.DrawCap, m_Master.geomCap ? 1 : 0);
  372. SetMaterialProp(ShaderProperties.TiltVector, m_Master.tiltFactor);
  373. SetMaterialProp(ShaderProperties.AdditionalClippingPlaneWS, m_Master.additionalClippingPlane);
  374. if (isDepthBlendEnabled)
  375. {
  376. SetMaterialProp(ShaderProperties.DepthBlendDistance, m_Master.depthBlendDistance);
  377. }
  378. if (isNoiseEnabled)
  379. {
  380. Noise3D.LoadIfNeeded();
  381. var noiseVelocity = m_Master.noiseVelocityUseGlobal ? Config.Instance.globalNoiseVelocity : m_Master.noiseVelocityLocal;
  382. var noiseScale = m_Master.noiseScaleUseGlobal ? Config.Instance.globalNoiseScale : m_Master.noiseScaleLocal;
  383. SetMaterialProp(ShaderProperties.NoiseVelocityAndScale, new Vector4(
  384. noiseVelocity.x,
  385. noiseVelocity.y,
  386. noiseVelocity.z,
  387. noiseScale));
  388. SetMaterialProp(ShaderProperties.NoiseParam, new Vector2(
  389. m_Master.noiseIntensity,
  390. m_Master.noiseMode == NoiseMode.WorldSpace ? 0f : 1f));
  391. }
  392. var localScale = ComputeLocalMatrix(); // compute matrix before sending it to the shader
  393. if (m_Master.hasMeshSkewing)
  394. {
  395. var localForwardDirectionNormalized = m_Master.skewingLocalForwardDirectionNormalized;
  396. SetMaterialProp(ShaderProperties.LocalForwardDirection, localForwardDirectionNormalized);
  397. if (coneMesh != null) // coneMesh can be null few frames with Dynamic Occlusion & GPU Instancing
  398. {
  399. var localForwardDirectionN = localForwardDirectionNormalized;
  400. localForwardDirectionN /= localForwardDirectionN.z;
  401. localForwardDirectionN *= m_Master.fallOffEnd;
  402. localForwardDirectionN.x /= localScale.x;
  403. localForwardDirectionN.y /= localScale.y;
  404. var bounds = MeshGenerator.ComputeBounds(1f, 1f, 1f);
  405. var min = bounds.min;
  406. var max = bounds.max;
  407. if (localForwardDirectionN.x > 0.0f) max.x += localForwardDirectionN.x;
  408. else min.x += localForwardDirectionN.x;
  409. if (localForwardDirectionN.y > 0.0f) max.y += localForwardDirectionN.y;
  410. else min.y += localForwardDirectionN.y;
  411. bounds.min = min;
  412. bounds.max = max;
  413. coneMesh.bounds = bounds;
  414. }
  415. }
  416. #if VLB_SRP_SUPPORT
  417. // This update is to make QA test 'ReflectionObliqueProjection' pass
  418. UpdateMatricesPropertiesForGPUInstancingSRP();
  419. #endif
  420. }
  421. MaterialChangeStop();
  422. #if DEBUG_SHOW_MESH_NORMALS
  423. for (int vertexInd = 0; vertexInd < coneMesh.vertexCount; vertexInd++)
  424. {
  425. var vertex = coneMesh.vertices[vertexInd];
  426. // apply modification done inside VS
  427. vertex.x *= Mathf.Lerp(coneRadius.x, coneRadius.y, vertex.z);
  428. vertex.y *= Mathf.Lerp(coneRadius.x, coneRadius.y, vertex.z);
  429. vertex.z *= m_Master.fallOffEnd;
  430. var cosSinFlat = new Vector2(vertex.x, vertex.y).normalized;
  431. var normal = new Vector3(cosSinFlat.x * Mathf.Cos(slopeRad), cosSinFlat.y * Mathf.Cos(slopeRad), -Mathf.Sin(slopeRad)).normalized;
  432. vertex = transform.TransformPoint(vertex);
  433. normal = transform.TransformDirection(normal);
  434. Debug.DrawRay(vertex, normal * 0.25f);
  435. }
  436. #endif
  437. }
  438. #if VLB_SRP_SUPPORT
  439. void UpdateMatricesPropertiesForGPUInstancingSRP()
  440. {
  441. if (SRPHelper.IsUsingCustomRenderPipeline() && Config.Instance.actualRenderingMode == RenderingMode.GPUInstancing)
  442. {
  443. SetMaterialProp(ShaderProperties.LocalToWorldMatrix, transform.localToWorldMatrix);
  444. SetMaterialProp(ShaderProperties.WorldToLocalMatrix, transform.worldToLocalMatrix);
  445. }
  446. }
  447. #if UNITY_2019_1_OR_NEWER
  448. void OnBeginCameraRenderingSRP(UnityEngine.Rendering.ScriptableRenderContext context, Camera cam)
  449. #else
  450. void OnBeginCameraRenderingSRP(Camera cam)
  451. #endif
  452. {
  453. m_CurrentCameraRenderingSRP = cam;
  454. }
  455. #endif
  456. void OnWillRenderObject()
  457. {
  458. Camera currentCam = null;
  459. #if VLB_SRP_SUPPORT
  460. if (SRPHelper.IsUsingCustomRenderPipeline())
  461. {
  462. currentCam = m_CurrentCameraRenderingSRP;
  463. }
  464. else
  465. #endif
  466. {
  467. currentCam = Camera.current;
  468. }
  469. OnWillCameraRenderThisBeam(currentCam);
  470. }
  471. void OnWillCameraRenderThisBeam(Camera cam)
  472. {
  473. if (m_Master && cam)
  474. {
  475. if (
  476. #if UNITY_EDITOR
  477. Utils.IsEditorCamera(cam) || // make sure to call UpdateCameraRelatedProperties for editor scene camera
  478. #endif
  479. cam.enabled) // prevent from doing stuff when we render from a previous DynamicOcclusionDepthBuffer's DepthCamera, because the DepthCamera are disabled
  480. {
  481. Debug.Assert(cam.GetComponentInParent<VolumetricLightBeam>() == null);
  482. UpdateCameraRelatedProperties(cam);
  483. m_Master._INTERNAL_OnWillCameraRenderThisBeam(cam);
  484. }
  485. }
  486. }
  487. void UpdateCameraRelatedProperties(Camera cam)
  488. {
  489. if (cam && m_Master)
  490. {
  491. MaterialChangeStart();
  492. {
  493. var camPosOS = m_Master.transform.InverseTransformPoint(cam.transform.position);
  494. var camForwardVectorOSN = transform.InverseTransformDirection(cam.transform.forward).normalized;
  495. float camIsInsideBeamFactor = cam.orthographic ? -1f : m_Master.GetInsideBeamFactorFromObjectSpacePos(camPosOS);
  496. SetMaterialProp(ShaderProperties.CameraParams, new Vector4(camForwardVectorOSN.x, camForwardVectorOSN.y, camForwardVectorOSN.z, camIsInsideBeamFactor));
  497. #if VLB_SRP_SUPPORT
  498. // This update is to be able to move beams without trackChangesDuringPlaytime enabled with SRP & GPU Instancing
  499. UpdateMatricesPropertiesForGPUInstancingSRP();
  500. #endif
  501. if (m_Master.usedColorMode == ColorMode.Gradient)
  502. {
  503. // Send the gradient matrix every frame since it's not a shader's property
  504. SetMaterialProp(ShaderProperties.ColorGradientMatrix, m_ColorGradientMatrix);
  505. }
  506. }
  507. MaterialChangeStop();
  508. #if FORCE_CURRENT_CAMERA_DEPTH_TEXTURE_MODE
  509. if (m_Master.depthBlendDistance > 0f)
  510. cam.depthTextureMode |= DepthTextureMode.Depth;
  511. #endif
  512. }
  513. }
  514. #if UNITY_EDITOR
  515. public bool _EDITOR_IsUsingCustomMaterial { get { return m_CustomMaterial != null; } }
  516. #endif
  517. }
  518. }