00001 #include "stage.hh"
00002 #include "worldfile.hh"
00003 using namespace Stg;
00004
00005 #include "file_manager.hh"
00006
00007 #include <errno.h>
00008
00009 Color::Color( double r, double g, double b, double a )
00010 : r(r),g(g),b(b),a(a)
00011 {}
00012
00013 Color::Color() :
00014 r(1.0), g(0.0), b(0.0), a(1.0)
00015 {}
00016
00017 bool Color::operator!=( const Color& other ) const
00018 {
00019 double epsilon = 1e-4;
00020 return( fabs(r-other.r) > epsilon ||
00021 fabs(g-other.g) > epsilon ||
00022 fabs(b-other.b) > epsilon ||
00023 fabs(a-other.a) > epsilon );
00024 }
00025
00026 Color::Color( const std::string& name) :
00027 r(1), g(0), b(0), a(1)
00028 {
00029 if( name == "" )
00030 return;
00031
00032 static FILE *file = NULL;
00033 static std::map<std::string,Color> table;
00034
00035 if( file == NULL )
00036 {
00037 std::string rgbFile = FileManager::findFile( "rgb.txt" );
00038 file = fopen( rgbFile.c_str(), "r" );
00039
00040 if( file == NULL )
00041 {
00042 PRINT_ERR1("unable to open color database: %s "
00043 "(try adding rgb.txt's location to your STAGEPATH)",
00044 strerror(errno));
00045
00046 exit(0);
00047 }
00048
00049 PRINT_DEBUG( "Success!" );
00050
00051
00052 while(1)
00053 {
00054 char line[1024];
00055 if (!fgets(line, sizeof(line), file))
00056 break;
00057
00058
00059
00060 if (line[0] == '!' || line[0] == '#' || line[0] == '%' || line[0] == '\0')
00061 continue;
00062
00063
00064 while (strchr(" \t\n", line[strlen(line)-1]))
00065 line[strlen(line)-1] = 0;
00066
00067
00068 int r, g, b;
00069 int chars_matched = 0;
00070 sscanf( line, "%d %d %d %n", &r, &g, &b, &chars_matched );
00071
00072
00073 const char* colorname = line + chars_matched;
00074
00075
00076 table[colorname] = Color( r/255.0, g/255.0, b/255.0 );
00077 }
00078 fclose(file);
00079 }
00080
00081
00082 Color& found = table[name];
00083
00084 this->r = found.r;
00085 this->g = found.g;
00086 this->b = found.b;
00087 this->a = found.a;
00088 }
00089
00090 bool Color::operator==( const Color& other ) const
00091 {
00092 return( ! ((*this) != other) );
00093 }
00094
00095 Color Color::RandomColor()
00096 {
00097 return Color( drand48(), drand48(), drand48() );
00098 }
00099
00100 void Color::Print( const char* prefix ) const
00101 {
00102 printf( "%s [%.2f %.2f %.2f %.2f]\n", prefix, r,g,b,a );
00103 }
00104
00105 const Color& Color::Load( Worldfile* wf, const int section )
00106 {
00107 if( wf->PropertyExists( section, "color" ))
00108 {
00109 const std::string& colorstr = wf->ReadString( section, "color", "" );
00110 if( colorstr != "" )
00111 {
00112 if( colorstr == "random" )
00113 {
00114 r = drand48();
00115 g = drand48();
00116 b = drand48();
00117 a = 1.0;
00118 }
00119 else
00120 {
00121 Color c = Color( colorstr );
00122 r = c.r;
00123 g = c.g;
00124 b = c.b;
00125 a = c.a;
00126 }
00127 }
00128 }
00129 else
00130 wf->ReadTuple( section, "color_rgba", 0, 4, "ffff", &r, &g, &b, &a );
00131
00132 return *this;
00133 }
00134