1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
| using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal;
public class LightingShadowOptimizer : MonoBehaviour { [Header("Optimization Settings")] public bool enableAutomaticOptimization = false; public bool enableLODForLights = true; public bool enableShadowCulling = true; public bool enableLightBakingSuggestion = true; [Header("Optimization Thresholds")] public float maxLightRangeMultiplier = 2.0f; public float minLightIntensityThreshold = 0.1f; public int maxShadowResolution = 2048; public float maxShadowDistance = 50f; public int maxAdditionalLights = 4; [Header("Performance Targets")] public float targetFrameRate = 60f; public int targetShadowCasters = 30; public int targetLights = 8; private LightDataProcessor m_LightDataProcessor; private ShadowDataProcessor m_ShadowDataProcessor; private List<OptimizationSuggestion> m_Suggestions = new List<OptimizationSuggestion>(); [System.Serializable] public class OptimizationSuggestion { public string category; public string targetName; public string issue; public string solution; public float priority; public bool isCritical; public System.Action applyAction; } [System.Serializable] public class OptimizationStats { public int totalSuggestions; public int criticalSuggestions; public int appliedSuggestions; public float performanceScore; public float estimatedFPSImprovement; public int estimatedDrawCallReduction; } public OptimizationStats stats = new OptimizationStats(); void Start() { m_LightDataProcessor = GetComponent<LightDataProcessor>(); if (m_LightDataProcessor == null) { m_LightDataProcessor = gameObject.AddComponent<LightDataProcessor>(); } m_ShadowDataProcessor = GetComponent<ShadowDataProcessor>(); if (m_ShadowDataProcessor == null) { m_ShadowDataProcessor = gameObject.AddComponent<ShadowDataProcessor>(); } if (enableAutomaticOptimization) { InvokeRepeating("RunOptimizationAnalysis", 0f, 5f); } } void RunOptimizationAnalysis() { AnalyzeOptimizationOpportunities(); if (enableAutomaticOptimization) { ApplyHighPrioritySuggestions(); } } public void AnalyzeOptimizationOpportunities() { m_Suggestions.Clear(); AnalyzeLightOptimizations(); AnalyzeShadowOptimizations(); AnalyzePerformanceOptimizations(); UpdateStats(); LogOptimizationAnalysis(); } private void AnalyzeLightOptimizations() { var lightSummary = m_LightDataProcessor.GetLightSummary(); var lightDataList = m_LightDataProcessor.GetLightAnalysisDataList(); if (lightSummary.additionalLightsCount > maxAdditionalLights) { var suggestion = new OptimizationSuggestion { category = "Light", targetName = "Scene Lights", issue = $"Too many additional lights: {lightSummary.additionalLightsCount} (max: {maxAdditionalLights})", solution = "Consider using fewer real-time lights or switching some to baked lighting", priority = 0.9f, isCritical = true, applyAction = () => ReduceAdditionalLights() }; m_Suggestions.Add(suggestion); } if (lightSummary.maxIntensity > targetFrameRate / 10f) { var suggestion = new OptimizationSuggestion { category = "Light", targetName = "High Intensity Lights", issue = $"High light intensity may impact performance: {lightSummary.maxIntensity:F2}", solution = "Reduce light intensities or use area lights instead of point lights", priority = 0.7f, isCritical = false, applyAction = () => ReduceLightIntensities() }; m_Suggestions.Add(suggestion); } foreach (var lightData in lightDataList) { if (lightData.range > 100f && lightData.intensity < 1f) { var suggestion = new OptimizationSuggestion { category = "Light", targetName = lightData.light.name, issue = $"Large range with low intensity: {lightData.range:F1} units, {lightData.intensity:F2}", solution = "Reduce range or increase intensity for better efficiency", priority = 0.5f, isCritical = false, applyAction = () => OptimizeLightRange(lightData.light) }; m_Suggestions.Add(suggestion); } } } private void AnalyzeShadowOptimizations() { var shadowSummary = m_ShadowDataProcessor.GetShadowSummary(); var shadowLightData = m_ShadowDataProcessor.GetShadowLights(); if (shadowSummary.totalShadowCasters > targetShadowCasters) { var suggestion = new OptimizationSuggestion { category = "Shadow", targetName = "Shadow Casters", issue = $"Too many shadow casting objects: {shadowSummary.totalShadowCasters} (target: {targetShadowCasters})", solution = "Change some objects to receive-only shadows or disable shadow casting", priority = 0.8f, isCritical = true, applyAction = () => ReduceShadowCasters() }; m_Suggestions.Add(suggestion); } if (shadowSummary.maxShadowResolution > 2) { var suggestion = new OptimizationSuggestion { category = "Shadow", targetName = "Shadow Resolution", issue = $"High shadow resolution may impact performance", solution = "Reduce shadow resolution in Quality Settings", priority = 0.6f, isCritical = false, applyAction = () => ReduceShadowResolution() }; m_Suggestions.Add(suggestion); } if (shadowSummary.averageShadowDistance > maxShadowDistance) { var suggestion = new OptimizationSuggestion { category = "Shadow", targetName = "Shadow Distance", issue = $"Large shadow distance: {shadowSummary.averageShadowDistance:F1}", solution = "Reduce shadow distance in Quality Settings", priority = 0.7f, isCritical = false, applyAction = () => ReduceShadowDistance() }; m_Suggestions.Add(suggestion); } } private void AnalyzePerformanceOptimizations() { var lightSummary = m_LightDataProcessor.GetLightSummary(); var shadowSummary = m_ShadowDataProcessor.GetShadowSummary(); if (lightSummary.totalLights + shadowSummary.totalShadowCasters > targetLights + targetShadowCasters) { var suggestion = new OptimizationSuggestion { category = "Performance", targetName = "Overall Scene", issue = $"Scene may be too complex for target performance", solution = "Consider using LODs, occlusion culling, or reducing scene complexity", priority = 0.8f, isCritical = true, applyAction = () => ApplySceneOptimizations() }; m_Suggestions.Add(suggestion); } } private void UpdateStats() { stats.totalSuggestions = m_Suggestions.Count; stats.criticalSuggestions = m_Suggestions.FindAll(s => s.isCritical).Count; stats.appliedSuggestions = 0; float lightScore = Mathf.Clamp01(1.0f - (m_LightDataProcessor.GetLightSummary().additionalLightsCount / (float)maxAdditionalLights)); float shadowScore = Mathf.Clamp01(1.0f - (m_ShadowDataProcessor.GetShadowSummary().totalShadowCasters / (float)targetShadowCasters)); stats.performanceScore = (lightScore + shadowScore) * 50f; stats.estimatedFPSImprovement = stats.criticalSuggestions * 5f; stats.estimatedDrawCallReduction = stats.criticalSuggestions * 10; } private void LogOptimizationAnalysis() { var log = new System.Text.StringBuilder(); log.AppendLine("=== Lighting & Shadow Optimization Analysis ==="); log.AppendLine($"Total Suggestions: {stats.totalSuggestions}"); log.AppendLine($"Critical Suggestions: {stats.criticalSuggestions}"); log.AppendLine($"Performance Score: {stats.performanceScore:F1}/100"); log.AppendLine($"Estimated FPS Improvement: {stats.estimatedFPSImprovement:F1}"); log.AppendLine($"Estimated Draw Call Reduction: {stats.estimatedDrawCallReduction}"); if (m_Suggestions.Count > 0) { log.AppendLine("\nSuggested Optimizations:"); var sortedSuggestions = new List<OptimizationSuggestion>(m_Suggestions); sortedSuggestions.Sort((a, b) => b.priority.CompareTo(a.priority)); foreach (var suggestion in sortedSuggestions) { var priorityText = suggestion.priority > 0.8f ? "HIGH" : suggestion.priority > 0.5f ? "MEDIUM" : "LOW"; log.AppendLine($"[{priorityText}] {suggestion.category}: {suggestion.targetName} - {suggestion.issue}"); log.AppendLine($" Solution: {suggestion.solution}"); } } else { log.AppendLine("\nNo optimizations suggested - current configuration appears optimal!"); } Debug.Log(log.ToString()); } public void ApplyHighPrioritySuggestions() { var highPrioritySuggestions = m_Suggestions.FindAll(s => s.priority > 0.7f && s.applyAction != null); foreach (var suggestion in highPrioritySuggestions) { if (suggestion.applyAction != null) { suggestion.applyAction(); stats.appliedSuggestions++; Debug.Log($"[Optimizer] Applied suggestion: {suggestion.issue}"); } } Invoke("AnalyzeOptimizationOpportunities", 1f); } public void ApplyAllSuggestions() { foreach (var suggestion in m_Suggestions) { if (suggestion.applyAction != null) { suggestion.applyAction(); stats.appliedSuggestions++; } } Debug.Log($"[Optimizer] Applied {stats.appliedSuggestions} suggestions"); } private void ReduceAdditionalLights() { var lights = m_LightDataProcessor.GetSceneLights(); var lightsToDisable = new List<Light>(); var additionalLights = lights.FindAll(l => l.type != LightType.Directional); additionalLights.Sort((a, b) => a.intensity.CompareTo(b.intensity)); int lightsToDisableCount = Mathf.Max(0, additionalLights.Count - maxAdditionalLights); for (int i = 0; i < lightsToDisableCount && i < additionalLights.Count; i++) { lightsToDisable.Add(additionalLights[i]); } foreach (var light in lightsToDisable) { light.enabled = false; Debug.Log($"[Optimizer] Disabled light '{light.name}' due to optimization"); } } private void ReduceLightIntensities() { var lights = m_LightDataProcessor.GetSceneLights(); foreach (var light in lights) { if (light.intensity > 2f) { light.intensity = Mathf.Clamp(light.intensity * 0.8f, minLightIntensityThreshold, light.intensity); } } } private void OptimizeLightRange(Light light) { if (light != null && light.range > 50f) { light.range = Mathf.Clamp(light.range * 0.7f, 5f, light.range); } } private void ReduceShadowCasters() { var shadowRenderers = m_ShadowDataProcessor.GetShadowCastingRenderers(); var renderersToChange = new List<Renderer>(); var rendererDataList = new List<ShadowDataProcessor.ShadowRendererData>(); foreach (var renderer in shadowRenderers) { var data = m_ShadowDataProcessor.GetShadowRendererData(renderer); if (data != null) { rendererDataList.Add(data); } } rendererDataList.Sort((a, b) => b.distanceToMainLight.CompareTo(a.distanceToMainLight)); int renderersToChangeCount = Mathf.Max(0, shadowRenderers.Count - targetShadowCasters); for (int i = 0; i < renderersToChangeCount && i < rendererDataList.Count; i++) { renderersToChange.Add(rendererDataList[i].renderer); } foreach (var renderer in renderersToChange) { renderer.shadowCastingMode = ShadowCastingMode.ShadowsOnly; Debug.Log($"[Optimizer] Changed shadow mode for '{renderer.name}'"); } } private void ReduceShadowResolution() { Debug.Log("[Optimizer] Consider reducing shadow resolution in Quality Settings for better performance"); } private void ReduceShadowDistance() { var shadowLights = m_ShadowDataProcessor.GetShadowLights(); foreach (var light in shadowLights) { if (light.shadowDistance > maxShadowDistance) { light.shadowDistance = maxShadowDistance; } } } private void ApplySceneOptimizations() { Debug.Log("[Optimizer] Applying scene-wide optimizations..."); } public List<OptimizationSuggestion> GetOptimizationSuggestions() { return new List<OptimizationSuggestion>(m_Suggestions); } public List<OptimizationSuggestion> GetSuggestionsByCategory(string category) { return m_Suggestions.FindAll(s => s.category == category); } public string GetPerformanceReport() { var report = new System.Text.StringBuilder(); report.AppendLine("=== Lighting & Shadow Performance Report ==="); report.AppendLine($"Performance Score: {stats.performanceScore:F1}/100"); report.AppendLine($"Total Issues Found: {stats.totalSuggestions}"); report.AppendLine($"Critical Issues: {stats.criticalSuggestions}"); report.AppendLine($"Applied Optimizations: {stats.appliedSuggestions}"); report.AppendLine($"Estimated Performance Gain: {stats.estimatedFPSImprovement:F1} FPS"); return report.ToString(); } }
|