New program: NaturalLightSync

Just wanted to share a program I made.

It smoothly changes the lights to match daylight color temperature. You can change the sunrise/sunset time and the max/min color temperatures. It’s called NaturalLightSync.

Hope it’s useful to someone!

Code below:

/*
  ---Program to smoothly change lights to the color temperature of natural daylight---
  
  color temp conversion code borrowed from UtilityColorTemp program


Variables to set:
  -sunrise and sunset time (24hr clock)
  -maxTemp is the color temperture when the sun is highest (higher = blue-er); default is 5700
  -minTemp is the color temperature when the sun is lowest (lower = red-er); default is 2500

after sunset/before sunrise color temp will remain at mixTemp

*/

var sunrise = 7;
var sunset = 20;
var maxTemp = (5700)/100;
var minTemp = (2500)/100;


var r,g,b;


function ctToRGB(ct){
    
    if( ct < 67 ){ 
        r = 1;
        g = 0.5313 * log(ct) - 1.2909;
        
        if( ct <= 19){
            b = 0;
        } else {
            b = 0.0223 * ct - 0.5063;
        }
    } else {
        r = 38.309 * pow(ct,-0.886);
        g = 10.771 * pow(ct,-0.588);
        b = 1;
    }
    
    r = clamp(r,0, 1);
    g = clamp(g,0, 1);
    b = clamp(b,0, 1);
}

export var ct;
export var timeOfDay;

export function beforeRender(delta) {
  timeOfDay = clockHour() + clockMinute()/60 + clockSecond()/60/60;
  
  if ((timeOfDay >= sunrise) && (timeOfDay <= sunset)) {
    var peak = ((sunset-sunrise)/2)+sunrise
    var a = (minTemp-maxTemp)/pow((sunrise-peak), 2);
    ct = (a*pow((timeOfDay-peak),2))+maxTemp;
  } else {
    ct = minTemp;
  }
  
  ctToRGB(ct);
}

export function render(index) {
  rgb(r,g,b);
}
2 Likes

@domg,
Very cool! I can picture this being really nice in a lamp or room lighting.

1 Like

Would you consider a sunset() sunrise() given lat and long?