ColorUtils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { MathUtils, SRGBColorSpace } from 'three';
  2. /**
  3. * @module ColorUtils
  4. * @three_import import * as ColorUtils from 'three/addons/utils/ColorUtils.js';
  5. */
  6. /**
  7. * Sets the given color from a color temperature in Kelvin.
  8. *
  9. * Converts a correlated color temperature (CTT) to an approximate sRGB color
  10. * using Tanner Helland's algorithm. Useful for physically-based lighting
  11. * setups — e.g. candle flame (~1900K), tungsten bulb (~3200K), daylight
  12. * (~6500K), or clear blue sky (~10000K). Values outside [1000, 40000] are
  13. * clamped.
  14. *
  15. * Reference: https://tannerhelland.com/2012/09/18/convert-temperature-rgb-algorithm-code.html
  16. *
  17. * @param {Color} color - The color to set.
  18. * @param {number} kelvin - Color temperature in Kelvin. Clamped to [1000, 40000].
  19. * @return {Color} The updated color.
  20. */
  21. function setKelvin( color, kelvin ) {
  22. // Algorithm by Tanner Helland (2012). Inputs are divided by 100.
  23. const temp = MathUtils.clamp( kelvin, 1000, 40000 ) / 100;
  24. let r, g, b;
  25. // Red channel
  26. if ( temp <= 66 ) {
  27. r = 255;
  28. } else {
  29. r = 329.698727446 * Math.pow( temp - 60, - 0.1332047592 );
  30. }
  31. // Green channel
  32. if ( temp <= 66 ) {
  33. g = 99.4708025861 * Math.log( temp ) - 161.1195681661;
  34. } else {
  35. g = 288.1221695283 * Math.pow( temp - 60, - 0.0755148492 );
  36. }
  37. // Blue channel
  38. if ( temp >= 66 ) {
  39. b = 255;
  40. } else if ( temp <= 19 ) {
  41. b = 0;
  42. } else {
  43. b = 138.5177312231 * Math.log( temp - 10 ) - 305.0447927307;
  44. }
  45. return color.setRGB(
  46. MathUtils.clamp( r, 0, 255 ) / 255,
  47. MathUtils.clamp( g, 0, 255 ) / 255,
  48. MathUtils.clamp( b, 0, 255 ) / 255,
  49. SRGBColorSpace
  50. );
  51. }
  52. export { setKelvin };
粤ICP备19079148号