GroundedSkybox.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Mesh, MeshBasicMaterial, SphereGeometry, Vector3 } from 'three';
  2. /**
  3. * A ground-projected skybox.
  4. *
  5. * By default the object is centered at the camera, so it is often helpful to set
  6. * `skybox.position.y = height` to put the ground at the origin.
  7. *
  8. * ```js
  9. * const height = 15, radius = 100;
  10. *
  11. * const skybox = new GroundedSkybox( envMap, height, radius );
  12. * skybox.position.y = height;
  13. * scene.add( skybox );
  14. * ```
  15. *
  16. * @augments Mesh
  17. * @three_import import { GroundedSkybox } from 'three/addons/objects/GroundedSkybox.js';
  18. */
  19. class GroundedSkybox extends Mesh {
  20. /**
  21. * Constructs a new ground-projected skybox.
  22. *
  23. * @param {Texture} map - The environment map to use.
  24. * @param {number} height - The height is how far the camera that took the photo was above the ground.
  25. * A larger value will magnify the downward part of the image.
  26. * @param {number} radius - The radius of the skybox. Must be large enough to ensure the scene's camera stays inside.
  27. * @param {number} [resolution=128] - The geometry resolution of the skybox.
  28. */
  29. constructor( map, height, radius, resolution = 128 ) {
  30. if ( height <= 0 || radius <= 0 || resolution <= 0 ) {
  31. throw new Error( 'GroundedSkybox height, radius, and resolution must be positive.' );
  32. }
  33. const geometry = new SphereGeometry( radius, 2 * resolution, resolution );
  34. geometry.scale( 1, 1, - 1 );
  35. const pos = geometry.getAttribute( 'position' );
  36. const tmp = new Vector3();
  37. for ( let i = 0; i < pos.count; ++ i ) {
  38. tmp.fromBufferAttribute( pos, i );
  39. if ( tmp.y < 0 ) {
  40. // Smooth out the transition from flat floor to sphere:
  41. const y1 = - height * 3 / 2;
  42. const f =
  43. tmp.y < y1 ? - height / tmp.y : ( 1 - tmp.y * tmp.y / ( 3 * y1 * y1 ) );
  44. tmp.multiplyScalar( f );
  45. tmp.toArray( pos.array, 3 * i );
  46. }
  47. }
  48. pos.needsUpdate = true;
  49. super( geometry, new MeshBasicMaterial( { map, depthWrite: false } ) );
  50. }
  51. }
  52. export { GroundedSkybox };