LodManager.qml 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (C) 2022 The Qt Company Ltd.
  2. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
  3. import QtQuick
  4. import QtQuick3D
  5. Node {
  6. id: root
  7. required property Camera camera
  8. required property var distances
  9. property real fadeDistance: 0.0
  10. onChildrenChanged: {
  11. // Add distance threshold values to instanced children
  12. var distIndex = 0; // Handle distance index separately to allow non-node children
  13. for (var i = 0; i < children.length; i++) {
  14. if (!(children[i] instanceof Model) || !children[i].instancing)
  15. continue;
  16. if (distIndex - 1 >= 0)
  17. children[i].instancingLodMin = distances[distIndex - 1];
  18. if (distances.length > distIndex)
  19. children[i].instancingLodMax = distances[distIndex];
  20. distIndex++;
  21. }
  22. }
  23. function update() {
  24. var distIndex = 0; // Handle distance index separately to allow non-node children
  25. for (var i = 0; i < root.children.length; i++) {
  26. var node = root.children[i];
  27. if (!(node instanceof Node))
  28. continue;
  29. if (node instanceof Model && node.instancing)
  30. continue;
  31. if (distIndex > distances.length)
  32. break;
  33. // Hide all nodes by default
  34. node.visible = false;
  35. var minThreshold = 0;
  36. var maxThreshold = -1;
  37. if (distIndex - 1 >= 0)
  38. minThreshold = distances[distIndex - 1] - fadeDistance;
  39. if (distances.length > distIndex)
  40. maxThreshold = distances[distIndex] + fadeDistance;
  41. // Show nodes that are inside the minimum and maximum distance thresholds
  42. var distance = node.scenePosition.minus(camera.scenePosition).length();
  43. if (distance >= minThreshold && (maxThreshold < 0 || distance < maxThreshold))
  44. node.visible = true;
  45. // Fade models by adjusting opacity if fadeDistance is set
  46. if (children[i] instanceof Model && fadeDistance > 0) {
  47. var fadeAlpha = -(minThreshold - distance) / fadeDistance;
  48. if (fadeAlpha > 1.0 && maxThreshold > 0)
  49. fadeAlpha = (maxThreshold - distance) / fadeDistance;
  50. children[i].opacity = fadeAlpha;
  51. }
  52. distIndex++;
  53. }
  54. }
  55. Component.onCompleted: {
  56. root.update()
  57. }
  58. Connections {
  59. target: root.camera
  60. function onScenePositionChanged() {
  61. root.update()
  62. }
  63. }
  64. }