• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0

Preetham sky for 2D - wicked colors. Sample images and video.

4 posts in this topic

Hello all, I'm new to the forum. Even though what I'm trying to achieve is not game related, I've found the most useful resources (and knowledge) here while trying to solve my problem.


For some time now I've been wanting to make a 2D representation of the sky for a given location at any date/time of day. I found the Preetham paper and followed through it, looked for several examples online and made my own implementation. Along the way I came across a couple of (as of now, very old) threads from here as well (http://www.gamedev.net/topic/100346-having-trouble-implementing-a-sky-colouring-algorithm and http://www.gamedev.net/topic/184552-preethams-daylight-paper-problem-50k-of-images/). I must say that, before doing this, I had no experience whatsoever in color management/theories, nor do I have any kind of knowledge on 3D programming.


After a couple of weeks I finished my implementation, but the colors are way off. I produced a series of images, from midnight to midnight for today at my current location. The image sequence is on my Dropbox (https://www.dropbox.com/sh/rklgyfvfhh2knij/AABRe_7V2OhT3Bprwj9yAMuga) and I also produced a video of it (https://www.dropbox.com/s/ispwejh3otf4zba/sunsky.mp4).


My current C code (also on pastebin: http://pastebin.com/EctzJFmF)

#define M_PI 3.14159265358979323846264338327950288
#define radians(x) ((x) / 180.f * M_PI)

typedef struct {
    double A, B, C, D, E;
} PerezCoefficient;

typedef struct {
    PerezCoefficient Y, x, y;
} PerezYxyCoefficients;

typedef struct {
    float red, green, blue;
} RGBColor;

typedef struct {
    double Y, y, x;
} YyxColor;

double getJulianDayNumber(int year, int month, int day, int hour, int minute, int second, double timezone) {
    double dayDecimal, julianDay, a, b;
    double timeDecimal = ((hour - timezone) / 24.) + (minute / (60. * 24.)) + (second / (60. * 60. * 24.));
    dayDecimal = day + timeDecimal;
    if (month < 3) {
        month += 12;
    a = (int)floor(year / 100.);
    b = 2 - a + floor(a / 4.);
    julianDay = (int)floor(365.25 * (year + 4716.)) + (int)floor(30.6001 * (month + 1)) + dayDecimal + b - 1524.5;

    return julianDay;

double getDecimalTime(int hour, int minute, int second) {
    return hour + ((double)minute / 60.) + ((double)second / 3600.);

double getSolarTime(double julianDayNumber, double decimalTime, double timezone, double longitude) {
    return decimalTime + .17f*sin(4.*M_PI*((julianDayNumber - 80) / 373)) - .129f*sin(2.*M_PI*((julianDayNumber - 8) / 355.)) - ((15*timezone - longitude) / 15.);

double getSolarDeclination(double julianDayNumber) {
    return .4093f * sin((2*M_PI * (julianDayNumber - 81)) / 368.);

double getSolarAltitude(double solarDeclination, double solarTime, double latitude) {
    return asin(sin(radians(latitude)) * sin(solarDeclination) - cos (radians(latitude)) * cos (solarDeclination) * cos (M_PI * solarTime / 12.));

double getSolarAzimuth(double solarDeclination, double solarTime, double latitude) {
    return atan((-cos(solarDeclination) * sin(M_PI * solarTime / 12.)) / (cos(radians(latitude)) * sin(solarDeclination) - sin(radians(latitude)) * cos(solarDeclination) * cos(M_PI * solarTime / 12.)));

double getPerezLuminance(double zenith, double gamma, PerezCoefficient coeff) {
    double cosZenith = (zenith == M_PI_2 ? .0000001f : cos(zenith));
    return (1 + coeff.A * exp(coeff.B / cosZenith)) * (1 + coeff.C * exp(coeff.D * gamma) + coeff.E * pow(cos(gamma), 2));

double getPerezGamma(float zenith, float azimuth, float solarzenith, float solarazimuth) {
    double a = sin(zenith) * sin(solarzenith) * cos(solarazimuth - azimuth) + cos(zenith) * cos(solarzenith);
    if(a > 1)
        return 0;
    if(a < -1)
        return M_PI;
    return acos(a);

PerezYxyCoefficients getPerezCoefficientsForTurbidity(double turbidity) {
    PerezCoefficient coeffY, coeffx, coeffy;
    coeffY.A = .17872f * turbidity - 1.46303f;
    coeffY.B = -.3554f * turbidity + .42749f;
    coeffY.C = -.02266f * turbidity + 5.32505f;
    coeffY.D = .12064f * turbidity - 2.57705f;
    coeffY.E = -.06696f * turbidity + .37027f;
    coeffx.A = -.01925f * turbidity - .25922f;
    coeffx.B = -.06651f * turbidity + .00081f;
    coeffx.C = -.00041f * turbidity + .21247f;
    coeffx.D = -.06409f * turbidity + .89887f;
    coeffx.E = -.00325f * turbidity + .04517f;
    coeffy.A = -.01669f * turbidity - .26078f;
    coeffy.B = -.09495f * turbidity + .00921f;
    coeffy.C = -.00792f * turbidity + .21023f;
    coeffy.D = -.04405f * turbidity - 1.65369f;
    coeffy.E = -.01092f * turbidity + .05291f;
    return (PerezYxyCoefficients){ .Y = coeffY, .x = coeffx, .y = coeffy };

YyxColor getYyxColorForZenithAndTurbidity(double zenith, double turbidity) {
    YyxColor color;
    double zenith2 = pow(zenith, 2);
    double zenith3 = pow(zenith, 3);
    double turbidity2 = pow(turbidity, 2);

    color.Y = ((4.0453f * turbidity - 4.971f) * tan((4.f/9.f - turbidity / 120.f) * (M_PI - 2*zenith)) - 0.2155f * turbidity + 2.4192f) * 1000.f;
    color.x = (.00165f * zenith3 - .00375f * zenith2 + .00209f * zenith + 0.f) * turbidity2 + (-0.02903f * zenith3 + .06377f * zenith2 - .03202f * zenith + .00394f) * turbidity + (.11693f * zenith3 - .21196f * zenith2 + .06052f * zenith + .25886f);
    color.y = (.00275f * zenith3 - .0061f * zenith2 + .00317f * zenith + 0.f) * turbidity2 + (-0.04214f * zenith3 + .0897f * zenith2 - .04153f * zenith + .00516f) * turbidity + (.15346f * zenith3 - .26756f * zenith2 + .0667f * zenith + .26688f);
    return color;

RGBColor getRGBColorFromYxy(YyxColor YyxColor) {
    double Y = YyxColor.Y;
    double x = YyxColor.x;
    double y = YyxColor.y;
    double X = x / y * Y;
    double Z = ((1. - x - y) / y) * Y;

    RGBColor color;
    color.red = 3.2404f * X - 1.5371f * Y - .4985f * Z;
    color.green = -.9692f * X + 1.8759f * Y + .0415f * Z;
    color.blue = .0556f * X - .2040f * Y + 1.0573f * Z;
    float expo = -(1.f / 15000.f);
    color.red = fmax(0., fmin(1., 1.f - exp(expo * color.red)));
    color.green = fmax(0., fmin(1., 1.f - exp(expo * color.green)));
    color.blue = fmax(0., fmin(1., 1.f - exp(expo * color.blue)));
    return color;

void getPixels() {
    struct timeval tv;
    struct tm *tm;
    gettimeofday(&tv, NULL);
    tm = localtime(&tv.tv_sec);

    int year = tm->tm_year + 1900;
    int month = tm->tm_mon + 1;
    int day = tm->tm_mday;
    int hour = tm->tm_hour;
    int min = tm->tm_min;
    int sec = tm->tm_sec;
    double timezone = (tm->tm_gmtoff / 3600.);

    double latitude = -33.3142516;
    double longitude = -71.4143858;

    double julianDay = getJulianDayNumber(year, month, day, hour, min, sec, timezone);
    double decimalTime = getDecimalTime(hour, min, sec);
    double solarTime = getSolarTime(julianDay, decimalTime, timezone, longitude);
    double solarDeclination = getSolarDeclination(julianDay);
    double solarAltitude = getSolarAltitude(solarDeclination, solarTime, latitude);
    double thetaS = (M_PI / 2.) - solarAltitude;
    double phiS = getSolarAzimuth(solarDeclination, solarTime, latitude);

    double T = 2.;

    PerezYxyCoefficients coeffs = getPerezCoefficientsForTurbidity(T);
    YyxColor sunYyx = getYyxColorForZenithAndTurbidity(thetaS, T);
    static const int WIDTH = 720;
    static const int HEIGHT = 180;

    for(int row = 0.; row < HEIGHT; row ++) {
        for(int col = 0.; col < WIDTH; col ++) {
            double zenith = radians((double)row / 2.);
            double azimuth = radians((double)col / 2.);
            YyxColor Yyx;
            double gamma = getPerezGamma(zenith, azimuth, thetaS, phiS);
            Yyx.Y = sunYyx.Y * getPerezLuminance(zenith, gamma, coeffs.Y) / getPerezLuminance(0, thetaS, coeffs.Y);
            Yyx.x = sunYyx.x * getPerezLuminance(zenith, gamma, coeffs.x) / getPerezLuminance(0, thetaS, coeffs.x);
            Yyx.y = sunYyx.y * getPerezLuminance(zenith, gamma, coeffs.y) / getPerezLuminance(0, thetaS, coeffs.y);
            RGBColor rgb = getRGBColorFromYxy(Yyx);


The resulting images are for a turbidity (T) value of 2. I checked the resulting values from the solar functions with an online calculator and mine seem to be fine.


Any help would be greatly appreciated.



Share this post

Link to post
Share on other sites



there are two things that attracted my attention (which are different from my code, http://nicoschertler.wordpress.com/2013/04/03/simulating-a-days-sky):


Your Yxy to RGB conversion includes an exponentiation. You should check if this is intended.


In my code I had to scale down sunYyx.Y by the maximum possible luminance. Otherwise the code would have produced out-of-range results. It's the Yz / Y0 part of the code.


I hope, one of the two things will help you.




Share this post

Link to post
Share on other sites

I finally managed to solve my issue: I had a wrongly signed value in the Perez coefficients and I replaced the atan in getSolarAzimuth with an atan2 to solve the cases where the angle was negative. I also had a problem with the color components ordering in my image algorithm...


The end result is nice but still somewhat not entirely perfect: the sky should be more red than the yellowish that appears at dawn/sunset, the horizon is a bit too red and the top of the sky a little too dark for my taste.


Nico, the Yyx->RGB includes an exposure function to better scale the values. This is similar to what you mentioned with the Yz/Y0 in your code, which in my case resulted in a very 'saturated' sun.


Video here: https://www.youtube.com/watch?v=0mo9jRbOAjg


Any tips or guidance on make the colors at dawn/dusk more real life like?


[edit: fixed code: http://pastebin.com/zVFJ8uZn]

Edited by boliva

Share this post

Link to post
Share on other sites

Thanks for the code. So basically in the Preetham sun position formulas they mixed up longitude and latitude? Are your longitude/latitude coordinates on the southern hemisphere?


edit: also thanks alot fot the atan2 hint ;)

Edited by necrowizzard

Share this post

Link to post
Share on other sites

Hi necrowizzard, I don't see where they mixed up the coordinates. Yes, I am in the southern hemisphere, that's why for my simulation the sun is always up north. Glad you could make use of the atan2.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0