Exemplo n.º 1
0
void HudGaugeRadar::initialize()
{
	int i;

	Radar_death_timer			= 0;
	Radar_static_playing		= 0;
	Radar_static_next			= 0;
	Radar_avail_prev_frame	= 1;
	Radar_calc_bright_dist_timer = timestamp(0);

	for ( i=0; i<NUM_FLICKER_TIMERS; i++ ) {
		Radar_flicker_timer[i]=timestamp(0);
		Radar_flicker_on[i]=0;
	}

	int w,h;
	gr_set_font(FONT1);

	Small_blip_string[0] = ubyte(SMALL_BLIP_CHAR);
	Small_blip_string[1] = 0;
	gr_get_string_size( &w, &h, Small_blip_string );
	Small_blip_offset_x = -w/2;
	Small_blip_offset_y = -h/2;

	Large_blip_string[0] = ubyte(LARGE_BLIP_CHAR);
	Large_blip_string[1] = 0;
	gr_get_string_size( &w, &h, Large_blip_string );
	Large_blip_offset_x = -w/2;
	Large_blip_offset_y = -h/2;

	HudGauge::initialize();
}
Exemplo n.º 2
0
int RenderWall (tFaceProps *propsP, g3sPoint **pointList, int bIsMonitor)
{
	short c, nWallNum = SEGMENTS [propsP->segNum].WallNum (propsP->sideNum);
	static tRgbaColorf cloakColor = {0, 0, 0, -1};

if (IS_WALL (nWallNum)) {
	if (propsP->widFlags & (WID_CLOAKED_FLAG | WID_TRANSPARENT_FLAG)) {
		if (!bIsMonitor) {
			if (!RenderColoredSegFace (propsP->segNum, propsP->sideNum, propsP->nVertices, pointList)) {
				c = WALLS [nWallNum].cloakValue;
				if (propsP->widFlags & WID_CLOAKED_FLAG) {
					if (c < FADE_LEVELS) {
						gameStates.render.grAlpha = GrAlpha (ubyte (c));
						G3DrawPolyAlpha (propsP->nVertices, pointList, &cloakColor, 1, propsP->segNum);		//draw as flat poly
						}
					}
				else {
					if (!gameOpts->render.color.bWalls)
						c = 0;
					if (WALLS [nWallNum].hps)
						gameStates.render.grAlpha = float (WALLS [nWallNum].hps) / float (I2X (100));
					else if (IsMultiGame && gameStates.app.bHaveExtraGameInfo [1])
						gameStates.render.grAlpha = COMPETITION ? 2.0f / 3.0f : GrAlpha (FADE_LEVELS - extraGameInfo [1].grWallTransparency);
					else
						gameStates.render.grAlpha = GrAlpha (ubyte (FADE_LEVELS - extraGameInfo [0].grWallTransparency));
					if (gameStates.render.grAlpha < 1.0f) {
						tRgbaColorf wallColor;
						
						paletteManager.Game ()->ToRgbaf ((ubyte) c, wallColor); 
						G3DrawPolyAlpha (propsP->nVertices, pointList, &wallColor, 1, propsP->segNum);	//draw as flat poly
						}
					}
				}
			gameStates.render.grAlpha = 1.0f;
			return 1;
			}
		}
	else if (gameStates.app.bD2XLevel) {
		c = WALLS [nWallNum].cloakValue;
		if (c && (c < FADE_LEVELS))
			gameStates.render.grAlpha = GrAlpha (FADE_LEVELS - c);
		}
	else if (gameOpts->render.effects.bAutoTransparency && IsTransparentFace (propsP))
		gameStates.render.grAlpha = 0.8f;
	else
		gameStates.render.grAlpha = 1.0f;
	}
return 0;
}
Exemplo n.º 3
0
void palette_load_table( char * filename )
{
	int i;
	int w, h;
	int pcx_error;

	strcpy( palette_base_filename, filename );
	char * p = strchr(palette_base_filename,'.');
	if ( p )	{
		*p = 0;
	}

	pcx_error = pcx_read_header(palette_base_filename, NULL, &w, &h, NULL, palette_org );
	if ( pcx_error != PCX_ERROR_NONE )	{
		// Read the old .256 file
		CFILE *fp;
		int fsize;
		fp = cfopen( palette_base_filename, "rb" );
		if ( fp==NULL)
			Error( LOCATION, "Can't open palette file <%s>",palette_base_filename);

		fsize	= cfilelength( fp );
		Assert( fsize == 9472 );
		cfread( palette_org, 256*3, 1, fp );
		cfclose(fp);

		for (i=0; i<768; i++ )	{	
			palette_org[i] = ubyte((palette_org[i]*255)/63);
		}
	}

	palette_base_loaded = 1;

	gr_set_palette(palette_base_filename, palette_org);
}
int FontBuilder::FTSystem::CalcWidth(FTFont *font,int size,String *str) {
	int width=0;
	int len=str->length();
	for(int i=0;i<len;i++) {
		unsigned int c=(unsigned int)ubyte(str->at(i));
		if(c==32) {
			width+=size<<1;
			continue;
		};
		FTFont::GlyphEntry *e=font->FindCharIndex(c,size);
		if(!e) {
			CacheCharacter(font,c,size,Vector3(1.0f,1.0f,1.0f));
			e=font->FindCharIndex(c,size);
			if(!e) {e=font->FindCharIndex(ubyte('?'),size);};
		};
		width+=e->advx;
	};
	return width;
};
Exemplo n.º 5
0
void HudGaugeRadar::initInfinityIcon()
{
	ubyte sc = lcl_get_font_index(font_num);
	// default to a '*' if the font has no special chars
	// nothing is really close to the infinity symbol...
	if (sc == 0) {
		Radar_infinity_icon = ubyte ('*');
	} else {
		Radar_infinity_icon = sc;
	}
}
Exemplo n.º 6
0
void radar_frame_init()
{
	radar_null_nblips();
	radx = i2fl(Radar_radius[gr_screen.res][0])/2.0f;
	rady = i2fl(Radar_radius[gr_screen.res][1])/2.0f;

	int w,h;
	gr_set_font(FONT1);

	Small_blip_string[0] = ubyte(SMALL_BLIP_CHAR);
	Small_blip_string[1] = 0;
	gr_get_string_size( &w, &h, Small_blip_string );
	Small_blip_offset_x = -w/2;
	Small_blip_offset_y = -h/2;

	Large_blip_string[0] = ubyte(LARGE_BLIP_CHAR);
	Large_blip_string[1] = 0;
	gr_get_string_size( &w, &h, Large_blip_string );
	Large_blip_offset_x = -w/2;
	Large_blip_offset_y = -h/2;
}
Exemplo n.º 7
0
void verify_stats(ubyte *table, long64 *tot_stats, struct dtz_map *map)
{
  long64 stats[256];
  long64 stats2[256];
  int i, j;
  ubyte (*inv_map)[256] = map->inv_map;

  for (i = 0; i < 256; i++)
    stats[i] = stats2[i] = 0;

  for (i = 0; i < 256 * numthreads; i++)
    thread_stats[i] = 0;
  count_stats_table = table;
  run_threaded(count_stats, work_g, 0);
  for (i = 0; i < numthreads; i++)
    for (j = 0; j < 256; j++)
      stats[j] += thread_data[i].stats[j];

  stats2[inv_map[0][0]] = tot_stats[0];
  stats2[inv_map[1][0]] = tot_stats[STAT_MATE];
  if (map->ply_accurate_win)
    for (i = 0; i < DRAW_RULE; i++)
      stats2[inv_map[0][i]] += tot_stats[i + 1];
  else
    for (i = 0; i < DRAW_RULE; i++)
      stats2[inv_map[0][i / 2]] += tot_stats[i + 1];
  if (map->ply_accurate_loss)
    for (i = 0; i < DRAW_RULE; i++)
      stats2[inv_map[1][i]] += tot_stats[STAT_MATE - 1 - i];
  else
    for (i = 0; i < DRAW_RULE; i++)
      stats2[inv_map[1][i / 2]] += tot_stats[STAT_MATE - 1 - i];
  for (i = DRAW_RULE + 1; i < MAX_PLY; i++) {
    stats2[inv_map[2][(i - DRAW_RULE - 1) / 2]] += tot_stats[i];
    stats2[inv_map[3][(i - DRAW_RULE - 1) / 2]] += tot_stats[STAT_MATE - i];
  }

  int verify_ok = 1;
  for (i = 0; i < 256; i++)
    if (stats[i] != stats2[i] && i != map->max_num) {
      printf("stats[%d] = %"PRIu64"; stats2[%d] = %"PRIu64"\n",
		    i, stats[i], i, stats2[i]);
      int j;
      for (j = 0; j < 4; j++)
	printf("map[%d][%d]=%d\n", j, i, map->map[j][i]);
      verify_ok = 0;
    }

  if (!verify_ok) {
    fprintf(stderr, "Verification of reconstructed table failed.\n");
    exit(1);
  }
}
Exemplo n.º 8
0
void RaytracingWindow::CreatePic()
{
#define XX RAYTRACING_DISPLAY_WIDTH
#define YY RAYTRACING_DISPLAY_HEIGHT
	mPic.Init(XX, YY);
	RGBAPixel* Pixels = mPic.GetPixels();
//	FractalBrownianMotion FBM(0.5f, 1.5f, 4.0f);
//	RidgedFractal FBM(0.5f, 1.5f, 4.0f, 1.0f, 1.0f);
	PerlinNoise FBM;
	Point Vector(1.0f, 0.0f, 100.0f);
	static float z = 0.0f;
	z+=0.01f;
	Vector.z = z;
	float Coeff = 0.005f;
	for(udword y=0;y<YY;y++)
	{
		for(udword x=0;x<XX;x++)
		{
			Vector.x = float(x)*Coeff;
			Vector.y = float(y)*Coeff;
			float fR = 128.0f + 128.0f * FBM.Compute(Vector);
			float fG = 128.0f + 128.0f * FBM.Compute(Vector+Point(0.0f, 0.0f, -1.0f));
			float fB = 128.0f + 128.0f * FBM.Compute(Vector+Point(0.0f, 0.0f, 1.0f));
			Pixels->R = ubyte(fR);
			Pixels->G = ubyte(fG);
			Pixels->B = ubyte(fB);
			Pixels->A = 255;
			Pixels++;
/*
			udword fR =  (udword)(200.0f - FBM.Turbulence(Vector, 32.0f) * 250.0f);
			udword fG =  (udword)(200.0f - FBM.Turbulence(Vector+Point(0.0f, 0.0f, -1.0f), 32.0f) * 250.0f);
			udword fB =  (udword)(200.0f - FBM.Turbulence(Vector+Point(0.0f, 0.0f, 1.0f), 32.0f) * 250.0f);
			Pixels->R = ubyte(fR);
			Pixels->G = ubyte(fG);
			Pixels->B = ubyte(fB);
			Pixels->A = 255;
			Pixels++;*/
		}
	}
}
void FontBuilder::CacheFace(const FontId id,unsigned int character,int size,uint color) {
	if(m_cache.m_id!=id) {
		m_cache.m_font=GetFont(id);
		m_cache.m_id=id;
	};
	if(m_cache.m_font==nullptr) {return;};

	const float inv=0.00390625f;
	Vector3 c(0.0f,0.0f,0.0f);
	c.x=(float)(ubyte(color>>16)&0xff)*inv;
	c.y=(float)(ubyte(color>>8)&0xff)*inv;
	c.z=(float)(ubyte(color)&0xff)*inv;
	if(!m_system.CacheCharacter(m_cache.m_font,character,size,c)) {
		System::Log("Warning, could not cache character (ID:%d,%d,%d)!",id,character,size);
	};
};
Exemplo n.º 10
0
int cfwrite_compressed(void *param_buf, int param_elsize, int param_nelem, CFILE *cfile)
{
	char *in = (char *)param_buf;
	int bytecount = (param_elsize * param_nelem );

	int pixcount;		// number of pixels in the current packet
	char *inputpixel=NULL;	// current input pixel position
	char *matchpixel=NULL;	// pixel value to match for a run
	int rlcount;		// current count in r.l. string 
	int rlthresh;		// minimum valid run length
	char *copyloc;		// location to begin copying at

	// set the threshold -- the minimum valid run length
	rlthresh = 2;					// Require a 2 pixel span before rle'ing
	
	// set the first pixel up

	inputpixel = in;
	pixcount = 1;
	rlcount = 0;
	copyloc = (char *)0;

	// loop till data processing complete
	do	{

		// if we have accumulated a 128-byte packet, process it
		if ( pixcount == 129 )	{
			ubyte code = 127;

			// set the run flag if this is a run

			if ( rlcount >= rlthresh )	{
					code |= 0x80;
					pixcount = 2;
			}

			cfwrite( &code, 1, 1, cfile );

			// copy the data into place
			cfwrite( copyloc, 1, pixcount-1, cfile );
			pixcount = 1;

			// set up for next packet
			continue;
		}

		// if zeroth byte, handle as special case
		if ( pixcount == 1 )	{
			rlcount = 0;
			copyloc = inputpixel;		/* point to 1st guy in packet */
			matchpixel = inputpixel;	/* set pointer to pix to match */
			pixcount = 2;
			inputpixel += 1;
			continue;
		}

		// assembling a packet -- look at next pixel

		// current pixel == match pixel?
		if ( *inputpixel == *matchpixel )	{

			//	establishing a run of enough length to
			//	save space by doing it
			//		-- write the non-run length packet
			//		-- start run-length packet

			if ( ++rlcount == rlthresh )	{
				
				//	close a non-run packet
				
				if ( pixcount > (rlcount+1) )	{
					// write out length and do not set run flag

					ubyte code = (ubyte)(pixcount - 2 - rlthresh);
					cfwrite( &code, 1, 1, cfile );

					cfwrite( copyloc, 1, (pixcount-1-rlcount), cfile );
					copyloc = inputpixel;
					pixcount = rlcount + 1;
				}
			}
		} else {

			// no match -- either break a run or continue without one
			//	if a run exists break it:
			//		write the bytes in the string (1+1)
			//		start the next string

			if ( rlcount >= rlthresh )	{

				ubyte code = (ubyte)(0x80 | rlcount);
				cfwrite( &code, 1, 1, cfile );
				cfwrite( copyloc, 1, 1, cfile );
				pixcount = 1;
				continue;
			} else {

				//	not a match and currently not a run
				//		- save the current pixel
				//		- reset the run-length flag
				rlcount = 0;
				matchpixel = inputpixel;
			}
		}
		pixcount++;
		inputpixel += 1;
	} while ( inputpixel < (in + bytecount));

	// quit this buffer without loosing any data
	if ( --pixcount >= 1 )	{
		ubyte code = ubyte(pixcount - 1);

		// set the run flag if this is a run

		if ( rlcount >= rlthresh )	{
				code |= 0x80;
				pixcount = 1;
		}

		cfwrite( &code, 1, 1, cfile );

		// copy the data into place
		cfwrite( copyloc, 1, pixcount, cfile );
	}

	return param_nelem;
}
Exemplo n.º 11
0
void KeyHandler (SDL_KeyboardEvent *event)
{
    ubyte			state;
    int			keyCode, keyState, nKeyboard = gameOpts->input.keyboard.nType;
    SDLKey		keySym;
    wchar_t		unicode;
    tKeyInfo*	keyP;
    ubyte			temp;

    keySym = event->keysym.sym;
    unicode = event->keysym.unicode;
    keyState = (event->state == SDL_PRESSED); //  !(wInfo & KF_UP);

//=====================================================
//Here a translation from win keycodes to mac keycodes!
//=====================================================

    for (int i = 0, j = sizeofa (keyProperties); i < j; i++) {
#if UNICODE_KEYS == 0
        if (nKeyboard == 1) {
            if (-1 == (keyCode = KeyGerman (i)))
                continue;
        }
        else if (nKeyboard == 2) {
            if (-1 == (keyCode = KeyFrench (i)))
                continue;
        }
        else if (nKeyboard == 3) {
            if (-1 == (keyCode = KeyDvorak (i)))
                continue;
        }
        else
#endif
            keyCode = i;
        keyP = keyData.keys + keyCode;

#if UNICODE_KEYS
        if (unicode && (keyProperties [i].asciiValue != wchar_t (255))) {
            if ((keyProperties [i].asciiValue == unicode) || (keyProperties [i].shiftedAsciiValue == unicode))
#	if DBG
                if (keyP->lastState)
                    state = keyState;
                else
#	endif
                    state = keyState;
            else
                state = keyP->lastState;
        }
        else if (keyProperties [i].sym == keySym)
#else
        if (keyProperties [i].sym == keySym)
#endif
            state = keyState;
        else
            state = keyP->lastState;

        if (keyP->lastState == state) {
            if (state) {
                keyP->counter++;
                gameStates.input.keys.nLastPressed = keyCode;
                gameStates.input.keys.xLastPressTime = TimerGetFixedSeconds ();
                keyP->flags = 0;
                if (gameStates.input.keys.pressed [KEY_LSHIFT] || gameStates.input.keys.pressed [KEY_RSHIFT])
                    keyP->flags |= ubyte (KEY_SHIFTED / 256);
                if (gameStates.input.keys.pressed [KEY_LALT] || gameStates.input.keys.pressed [KEY_RALT])
                    keyP->flags |= ubyte (KEY_ALTED / 256);
                if ((gameStates.input.keys.pressed [KEY_LCTRL] && (nKeyboard != 1)) || gameStates.input.keys.pressed [KEY_RCTRL])
                    keyP->flags |= ubyte (KEY_CTRLED / 256);
            }
        }
        else {
            if (state) {
                gameStates.input.keys.nLastPressed = keyCode;
                keyP->timeWentDown = gameStates.input.keys.xLastPressTime = TimerGetFixedSeconds();
                keyData.keys [keyCode].timeHeldDown = 0;
                gameStates.input.keys.pressed [keyCode] = 1;
                keyP->downCount += state;
                keyP->counter++;
                keyP->state = 1;
                keyP->flags = 0;
                if (gameStates.input.keys.pressed [KEY_LSHIFT] || gameStates.input.keys.pressed [KEY_RSHIFT])
                    keyP->flags |= ubyte (KEY_SHIFTED / 256);
                if (gameStates.input.keys.pressed [KEY_LALT] || gameStates.input.keys.pressed [KEY_RALT])
                    keyP->flags |= ubyte (KEY_ALTED / 256);
                if (((nKeyboard != 1) && gameStates.input.keys.pressed [KEY_LCTRL]) || gameStates.input.keys.pressed [KEY_RCTRL])
                    keyP->flags |= ubyte (KEY_CTRLED / 256);
//				keyP->timeWentDown = gameStates.input.keys.xLastPressTime = TimerGetFixedSeconds();
            }
            else {
                gameStates.input.keys.pressed [keyCode] = 0;
                gameStates.input.keys.nLastReleased = keyCode;
                keyP->upCount += keyP->state;
                keyP->state = 0;
                keyP->counter = 0;
                keyP->timeHeldDown += TimerGetFixedSeconds () - keyP->timeWentDown;
            }
        }
        if (state && (!keyP->lastState || ((keyP->counter > 30) && (keyP->counter & 1)))) {
            if (gameStates.input.keys.pressed [KEY_LSHIFT] || gameStates.input.keys.pressed [KEY_RSHIFT])
                keyCode |= KEY_SHIFTED;
            if (gameStates.input.keys.pressed [KEY_LALT] || gameStates.input.keys.pressed [KEY_RALT])
                keyCode |= KEY_ALTED;
            if (((nKeyboard != 1) && gameStates.input.keys.pressed [KEY_LCTRL]) || gameStates.input.keys.pressed [KEY_RCTRL])
                keyCode |= KEY_CTRLED;
            if (gameStates.input.keys.pressed [KEY_LCMD] || gameStates.input.keys.pressed [KEY_RCMD])
                keyCode |= KEY_COMMAND;
#if DBG
            if (gameStates.input.keys.pressed [KEY_DELETE])
                keyCode |= KEYDBGGED;
#endif
            temp = keyData.nKeyTail + 1;
            if (temp >= KEY_BUFFER_SIZE)
                temp = 0;
            if (temp != keyData.nKeyHead) {
#if DBG
                if ((i == KEY_LSHIFT) || (i == KEY_RSHIFT) ||
                        (i == KEY_LALT) || (i == KEY_RALT) ||
                        (i == KEY_RCTRL) || (i == KEY_LCTRL))
                    keyData.keyBuffer [keyData.nKeyTail] = keyCode;
                else
#endif
                    keyData.keyBuffer [keyData.nKeyTail] = keyCode;
                keyData.xTimePressed [keyData.nKeyTail] = gameStates.input.keys.xLastPressTime;
                keyData.nKeyTail = temp;
            }
        }
        keyP->lastState = state;
    }
}
  // applies the histogramMethod for the type boundary Zero
  bool kNearestNeighFilter::histogramMethodZero(const imatrix& src,
					imatrix& dest) const {
    int i,j,row,col;//index

    const int limit = sizeOfKernel/2;   //half size of the kernel
    const int rowSize = src.rows();
    const int columnSize = src.columns();
    const int lastCol = src.lastColumn()-limit;
    const int lastRow = src.lastRow()-limit;

    ivector histogram(histoSize,0);  //the histogram for a channel8
    dest.resize(src.size(),ubyte(0),false,false);

    //runs area 4,5,6
    for(row=limit;row<=lastRow;++row) {
      const int r = row+limit;
      histogram.fill(0);
      col=0;

      //number of 0's are known
      histogram.at(0) = sizeOfKernel*(sizeOfKernel-limit-1);
      for(i=row-limit;i<=r;++i)
        for(j=0;j<=limit;++j)
          ++histogram.at(src.at(i,j));
      dest.at(row,col) = getMostLabel(histogram,src,row,col);

      // the kernel at the position between the border and the image
      while(col < limit) {
        histogram.at(0) -= sizeOfKernel; // cut all the 0 in the leftmost column
	++col;
        j = col+limit;        // for each pixel in the rightmost column
        for(i=row-limit;i<=r;++i)
          ++histogram.at(src.at(i,j));
	dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }

      //runs area 5
      histogramMethodMiddle(src,dest,histogram,row,col);

      // area 6
      col = lastCol;
      while(col < (columnSize-1)) {
        j = col-limit;
        for(i=row-limit;i<=r;++i)
          --histogram.at(src.at(i,j));
        ++col;
        histogram.at(0) += sizeOfKernel;

	dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }
    }

    // runs area 1,2,3
    for(row=0;row<limit;++row) {
      const int r=row+limit;
      // runs middle top rows (area 2)
      for(col=limit;col<=lastCol;++col) {
	histogram.fill(0);
        const int c=col+limit;
        histogram.at(0) = sizeOfKernel*(sizeOfKernel-(limit+1)-row);
	for(i=0;i<=r;++i)
          for(j=col-limit;j<=c;++j)
	    ++histogram.at(src.at(i,j));
        dest.at(row,col) = getMostLabel(histogram,src,row,col) ;
      }
      // runs left top corner (area 1);
      for(col=0;col<limit;++col) {
	histogram.fill(0);
	const int c=col+limit;
        histogram.at(0) = sizeOfKernel*sizeOfKernel-(limit+1)*(limit+1+row+col)-col*row;
        for(i=0;i<=r;++i)
	  for(j=0;j<=c;++j)
	    ++histogram.at(src.at(i,j));
	dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }
      // runs top right corner (area 3)
      for(col=lastCol+1;col<=columnSize-1;++col) {
	histogram.fill(0);
	const int c=columnSize-1;
	histogram.at(0) = sizeOfKernel*sizeOfKernel
	  -(limit+1)*(limit+1+row+(columnSize-1-col))-row*(columnSize-1-col);
        for(i=0;i<=r;++i)
          for(j=col-limit;j<=c;++j)
            ++histogram.at(src.at(i,j));
	dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }
    }

    //runs the rows at the bottom (area 7,8,9)
    for(row=lastRow+1;row<=rowSize-1;++row) {
      //runs middle bottom rows (area 8)
      for(col=limit;col<=lastCol;++col) {
	histogram.fill(0);
        const int c=col+limit;
        histogram.at(0) = sizeOfKernel*(sizeOfKernel-(limit+1)-(rowSize-1-row));
        for(i=row-limit;i<=rowSize-1;++i)
          for(j=col-limit;j<=c;++j)
            ++histogram.at(src.at(i,j));
	dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }
      // runs bottom left corner (area 7)
      for(col=0;col<limit;++col) {
	histogram.fill(0);
	const int c=col+limit;
        histogram.at(0) = sizeOfKernel*sizeOfKernel-(limit+1)*
          (limit+1+(rowSize-1-row)+col)-col*(rowSize-1-row);
        for(i=row-limit;i<=rowSize-1;++i)
          for(j=0;j<=c;++j)
            ++histogram.at(src.at(i,j));
	dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }
      //runs bottom right corner (area 9)
      for(col=lastCol+1;col<=columnSize-1;++col) {
	histogram.fill(0);
	const int c = columnSize-1;
	histogram.at(0) = sizeOfKernel*sizeOfKernel
	  -(limit+1)*(limit+1+(rowSize-1-row)+(columnSize-1-col))
	  -(rowSize-1-row)*(columnSize-1-col);
        for(i=row-limit;i<=rowSize-1;++i)
          for(j=col-limit;j<=c;++j)
            ++histogram.at(src.at(i,j));
        dest.at(row,col) = getMostLabel(histogram,src,row,col);
      }
    }
    return true;
  };
Exemplo n.º 13
0
  // Quantization takes place here!
  bool medianCut::performQuantization(const image& src,
                                      image& dest,
                                      channel8& mask,
                                      palette &thePalette) const {

    // parameters and const variables
    const parameters& param = getParameters();
    const int imageRows=src.rows();          // number of rows in src
    const int imageCols=src.columns();       // number of columns in src

    // resize destination containers
    dest.resize(imageRows,imageCols,rgbPixel(),false,false);
    mask.resize(imageRows,imageCols,ubyte(),false,false);

    // Variables
    int row,col;            // row, column counters
    int r,g,b;              // red,green,blue
    ivector iVec(3);        // int-vector

    std::list<boxInfo> theLeaves; // list of leaves (tree without root
                                  // and nodes)
    std::list<boxInfo>::iterator  splitPos;   // position to split
    std::list<boxInfo>::iterator  iter;       // iterator for theLeaves

    // create histogram with desired pre-quantization dimensions from src
    histogram theHist(3,param.preQuant);

    const float factor = param.preQuant/256.0f;

    for (row = 0 ; row < imageRows ; row++) {
      for (col = 0 ; col < imageCols ; col++) {

        r = static_cast<int>(src.at( row,col ).getRed()   * factor);
        g = static_cast<int>(src.at( row,col ).getGreen() * factor);
        b = static_cast<int>(src.at( row,col ).getBlue()  * factor);
        
        // insert point with quantized color
        dest.at(row,col).set((r*256+128)/param.preQuant,
                             (g*256+128)/param.preQuant,
                             (b*256+128)/param.preQuant,0); 

        iVec[0] = r;
        iVec[1] = g;
        iVec[2] = b;

        theHist.put(iVec);
      }
    }

    // initialization of first box of list (the whole histogram)
    boxInfo theBox(rgbPixel(0,0,0),
                   rgbPixel(param.preQuant-1,
                            param.preQuant-1,
                            param.preQuant-1));

    computeBoxInfo(theHist,theBox);

    // return, if desired number of colors smaller than colors in
    // pre-quantized image
    if (theBox.colors < param.numberOfColors) {

      thePalette.resize(theBox.colors,rgbPixel(),false,false);

      // prepare palette     
      int i = 0;
      for (r=0;r<param.preQuant;++r) {
        for (g=0;g<param.preQuant;++g) {
          for (b=0;b<param.preQuant;++b) {
            iVec[0] = r;
            iVec[1] = g;
            iVec[2] = b;
            if (theHist.at(iVec) > 0) {
              thePalette.at(i).set((r*256+128)/param.preQuant,
                                   (g*256+128)/param.preQuant,
                                   (b*256+128)/param.preQuant);
            }
          }
        }
      }

      // use the palette to generate the corresponding channel
      usePalette colorizer;
      colorizer.apply(dest,thePalette,mask);
      
      return true;
    }

    // Push first box into List
    theLeaves.push_back(theBox);

    // MAIN LOOP (do this until you have enough leaves (count), or no
    // splittable boxes (entries))
    int count, entries=1;  // auxiliary variables for the main loop
    for (count=1; (count<param.numberOfColors) && (entries!=0); count++) {

      // find box with largest number of entries from list
      entries = 0;
      for (iter = theLeaves.begin() ; iter != theLeaves.end() ; iter++) {
        if ( (*iter).colorFrequency > entries ) {
          // Avoid choosing single colors, i.e. unsplittable boxes
          if (  ((*iter).max.getRed()   > (*iter).min.getRed())   ||
                ((*iter).max.getGreen() > (*iter).min.getGreen()) ||
                ((*iter).max.getBlue()  > (*iter).min.getBlue()) ) {
            entries   = (*iter).colorFrequency;
            splitPos  = iter;
          }
        }
      }

      // A splittable box was found.
      // The iterator "splitPos" indicates its position in the List
      if (entries >0) {
        // Determine next axis to split (largest variance) and box dimensions
        int splitAxis;  // split axis indicator
        if ( ((*splitPos).var[0] >= (*splitPos).var[1]) &&
             ((*splitPos).var[0] >= (*splitPos).var[2]) ) {
          splitAxis = 0;  // red axis
        }
        else if ( (*splitPos).var[1] >= (*splitPos).var[2] ) {
          splitAxis = 1;  // green axis
        }
        else {
          splitAxis = 2;  // blue axis
        }

        int rMax  = ((*splitPos).max.getRed());
        int rMin  = ((*splitPos).min.getRed());
        int gMax  = ((*splitPos).max.getGreen());
        int gMin  = ((*splitPos).min.getGreen());
        int bMax  = ((*splitPos).max.getBlue());
        int bMin  = ((*splitPos).min.getBlue());

        // pass through box along the axis to split
        bool found;             // becomes true when split plane is found
        int nrOfCols=0;         // counter: number of colors of box
        int prevNrOfCols=0;     // forerunner of nrOfCols
        rgbPixel lower1;   // lower pixel from box 1
        rgbPixel upper1;   // upper pixel from box 1
        rgbPixel lower2;   // lower pixel from box 2
        rgbPixel upper2;   // upper pixel from box 2

        switch (splitAxis) {
          case 0: // red axis
            nrOfCols = 0;
            for (r = rMin , found = false ; (!found) && (r<=rMax) ; r++) {
              prevNrOfCols = nrOfCols;
              for (g = gMin ; g <= gMax ; g++) {
                for (b=bMin;b<=bMax;b++) {
                  iVec[0] = r;
                  iVec[1] = g;
                  iVec[2] = b;
                  if (theHist.at(iVec) > 0.0) {
                    nrOfCols += static_cast<long int>(theHist.at(iVec));
                  }
                }
              }
              if ( nrOfCols >= (*splitPos).colorFrequency/2 ) {
                found=true;
              }
            }
            if (fabs(prevNrOfCols -
                     static_cast<float>((*splitPos).colorFrequency)/2) <
                fabs(nrOfCols     -
                     static_cast<float>((*splitPos).colorFrequency)/2)) {
                r--;
                nrOfCols = prevNrOfCols;
            }
            // first box
            lower1.setRed(rMin);  lower1.setGreen(gMin);  lower1.setBlue(bMin);
            upper1.setRed(r-1);   upper1.setGreen(gMax);  upper1.setBlue(bMax);
            // second box
            lower2.setRed(r);     lower2.setGreen(gMin);  lower2.setBlue(bMin);
            upper2.setRed(rMax);  upper2.setGreen(gMax);  upper2.setBlue(bMax);
            break;

          case 1: // g axis
            nrOfCols = 0;
            for (g = gMin , found = false ; (!found) && (g<=gMax) ; g++) {
              prevNrOfCols = nrOfCols;
              for (r = rMin ; r <= rMax ; r++) {
                for (b = bMin ; b <= bMax ; b++) {
                  iVec[0] = r;
                  iVec[1] = g;
                  iVec[2] = b;
                  if (theHist.at(iVec) > 0.0) {
                    nrOfCols += static_cast<long int>(theHist.at(iVec));
                  }
                }
              }
              if ( nrOfCols >= (*splitPos).colorFrequency/2 ) {
                found=true;
              }
            }
            if (fabs(prevNrOfCols -
                     static_cast<float>((*splitPos).colorFrequency)/2) <
                fabs(nrOfCols     -
                     static_cast<float>((*splitPos).colorFrequency)/2)) {
                g--;
                nrOfCols = prevNrOfCols;
            }
            // first box
            lower1.setRed(rMin);  lower1.setGreen(gMin);  lower1.setBlue(bMin);
            upper1.setRed(rMax);  upper1.setGreen(g-1);   upper1.setBlue(bMax);
            // second box
            lower2.setRed(rMin);  lower2.setGreen(g);     lower2.setBlue(bMin);
            upper2.setRed(rMax);  upper2.setGreen(gMax);  upper2.setBlue(bMax);
            break;

          case 2: // b axis
            nrOfCols = 0;
            for (b = bMin , found = false ; (!found) && (b<=bMax) ; b++) {
              prevNrOfCols = nrOfCols;
              for (r = rMin ; r <= rMax ; r++) {
                for (g = gMin ; g <= gMax ; g++) {
                  iVec[0] = r;
                  iVec[1] = g;
                  iVec[2] = b;
                  if (theHist.at(iVec) > 0.0) {
                    nrOfCols += static_cast<long int>(theHist.at(iVec));
                  }
                }
              }
              if ( nrOfCols >= (*splitPos).colorFrequency/2 ) {
                found=true;
              }
            }
            if (fabs(prevNrOfCols -
                     static_cast<float>((*splitPos).colorFrequency)/2) <
                fabs(nrOfCols     -
                     static_cast<float>((*splitPos).colorFrequency)/2)) {
                b--;
                nrOfCols = prevNrOfCols;
            }
            // first box
            lower1.setRed(rMin); lower1.setGreen(gMin); lower1.setBlue(bMin);
            upper1.setRed(rMax); upper1.setGreen(gMax); upper1.setBlue(b-1);
            // second box
            lower2.setRed(rMin); lower2.setGreen(gMin); lower2.setBlue(b);
            upper2.setRed(rMax); upper2.setGreen(gMax); upper2.setBlue(bMax);
            break;
          default:
            break;
        } // end of switch

        // compute box info of new boxes and
        // append both at the end of list
        theBox.min = lower1;
        theBox.max = upper1;
        computeBoxInfo(theHist,theBox);
        theLeaves.push_back(theBox);

        theBox.min = lower2;
        theBox.max = upper2;
        computeBoxInfo(theHist,theBox);
        theLeaves.push_back(theBox);

        // delete splited box from list
        theLeaves.erase(splitPos);
      }

    } // end of for (MAIN LOOP)

    // compute block histogram and respective color palette
    thePalette.resize(theLeaves.size());
    int i;
    for (iter = theLeaves.begin() , i=0 ;
         iter != theLeaves.end() ;
         iter++ , i++) {
      // misuse histogram as a look-up-table
      for (r = (*iter).min.getRed(); r <= (*iter).max.getRed(); r++) {
        for (g = (*iter).min.getGreen(); g <= (*iter).max.getGreen(); g++) {
          for (b = (*iter).min.getBlue(); b <= (*iter).max.getBlue(); b++) {
            iVec[0] = r;
            iVec[1] = g;
            iVec[2] = b;
            theHist.at(iVec) = i; // insert palette-index (refers to
                                  // color in palette)
          }
        }
      }

      // create palette
      r = (static_cast<int>((*iter).mean[0]*factor)*256+128)/param.preQuant;
      g = (static_cast<int>((*iter).mean[1]*factor)*256+128)/param.preQuant;
      b = (static_cast<int>((*iter).mean[2]*factor)*256+128)/param.preQuant;
      thePalette[i].set(r,g,b,0);  // insert color
    }

    // create new image with palette and theHist
    dest.resize(imageRows,imageCols);
    mask.resize(imageRows,imageCols,0,false,true);

    // <= 256 colors? then also fill the mask
    if (thePalette.size() <= 256) {
      for (row = 0 ; row < imageRows ; row++) {
        for (col = 0 ; col < imageCols ; col++) {
          iVec[0] = static_cast<int>(src.at( row,col ).getRed()   * factor);
          iVec[1] = static_cast<int>(src.at( row,col ).getGreen() * factor);
          iVec[2] = static_cast<int>(src.at( row,col ).getBlue()  * factor);

          i = static_cast<int>(theHist.at( iVec ));

          dest.at(row,col) = thePalette[i];// insert point with quantized color
          mask.at(row,col) = i;     // insert palette index of quantized color
        }
      }
    }
    else {
      for (row = 0 ; row < imageRows ; row++) {
        for (col = 0 ; col < imageCols ; col++) {
          iVec[0] = static_cast<int>(src.at( row,col ).getRed()   * factor);
          iVec[1] = static_cast<int>(src.at( row,col ).getGreen() * factor);
          iVec[2] = static_cast<int>(src.at( row,col ).getBlue()  * factor);

          i = static_cast<int>(theHist.at( iVec ));

          r = thePalette[i].getRed();
          g = thePalette[i].getGreen();
          b = thePalette[i].getBlue();

          dest.at(row,col).set(r,g,b,0); // insert point with quantized color
        }
      }
    }

    return true;
  }
Exemplo n.º 14
0
int CParticle::Create (CFixVector *vPos, CFixVector *vDir, CFixMatrix *mOrient,
                       short nSegment, int nLife, int nSpeed, char nParticleSystemType, char nClass,
                       float nScale, tRgbaColorf *colorP, int nCurTime, int bBlowUp, char nFadeType,
                       float fBrightness, CFixVector *vEmittingFace)
{

    tRgbaColorf	color;
    int			nType = particleImageManager.GetType (nParticleSystemType);

    m_bChecked = 0;
    m_bBlowUp = bBlowUp && gameOpts->render.particles.bDisperse;
    if (nScale < 0)
        m_nRad = float (-nScale);
    else if (gameOpts->render.particles.bSyncSizes)
        m_nRad = float (PARTICLE_SIZE (gameOpts->render.particles.nSize [0], nScale, m_bBlowUp));
    else
        m_nRad = float (nScale);
    if (!m_nRad)
        m_nRad = 1.0f;
    m_nType = nType;
    m_bEmissive = (nParticleSystemType == LIGHT_PARTICLES) ? 1 : (nParticleSystemType == FIRE_PARTICLES) ? 2 : 0;
    m_nClass = nClass;
    m_nFadeType = nFadeType;
    m_nSegment = nSegment;
    m_nBounce = ((m_nType == BUBBLE_PARTICLES) || (m_nType == WATERFALL_PARTICLES)) ? 1 : 2;
    m_bReversed = 0;
    m_nMoved = nCurTime;
    if (nLife < 0)
        nLife = -nLife;
    m_nLife = nLife;
    m_nDelay = 0; //bStart ? randN (nLife) : 0;

    m_color [0] =
        m_color [1] =
            color = (colorP && (m_bEmissive < 2)) ? *colorP : defaultParticleColor;

    if ((nType == BULLET_PARTICLES) || (nType == BUBBLE_PARTICLES)) {
        m_bBright = 0;
        m_nFadeState = -1;
    }
    else {
        m_bBright = (nType <= SMOKE_PARTICLES) ? (rand () % 50) == 0 : 0;
        if (colorP) {
            if (!m_bEmissive) {
                m_color [0].red *= RANDOM_FADE;
                m_color [0].green *= RANDOM_FADE;
                m_color [0].blue *= RANDOM_FADE;
            }
            m_nFadeState = 0;
        }
        else {
            m_color [0].red = 1.0f;
            m_color [0].green = 0.5f;
            m_color [0].blue = 0.0f;
            m_nFadeState = 2;
        }
        if (m_bEmissive)
            m_color [0].alpha = float (SMOKE_START_ALPHA + 64) / 255.0f;
        else if (nParticleSystemType != GATLING_PARTICLES) {
            if (!colorP)
                m_color [0].alpha = float (3 * SMOKE_START_ALPHA / 4 + randN (SMOKE_START_ALPHA / 2)) / 255.0f;
            else {
                if (colorP->alpha < 0) {
                    ubyte a = ubyte (-colorP->alpha * 255.0f * 0.25f + 0.5f);
                    m_color [0].alpha = float (3 * a + randN (2 * a)) / 255.0f;
                }
                else {
                    if (2 == (m_nFadeState = char (colorP->alpha))) {
                        m_color [0].red = 1.0f;
                        m_color [0].green = 0.5f;
                        m_color [0].blue = 0.0f;
                    }
                    m_color [0].alpha = float (3 * SMOKE_START_ALPHA / 4 + randN (SMOKE_START_ALPHA / 2)) / 255.0f;
                }
            }
            if (m_bBlowUp && !m_bBright) {
                fBrightness = 1.0f - fBrightness;
                m_color [0].alpha += fBrightness * fBrightness / 8.0f;
            }
        }
    }
#if 0
    if (nType == FIRE_PARTICLES)
        nSpeed = int (sqrt (double (nSpeed)) * float (I2X (1)));
    else
#endif
        nSpeed *= I2X (1);
    if (!vDir) {
        m_vDrift [X] = nSpeed - randN (2 * nSpeed);
        m_vDrift [Y] = nSpeed - randN (2 * nSpeed);
        m_vDrift [Z] = nSpeed - randN (2 * nSpeed);
        m_vDir.SetZero ();
        m_bHaveDir = 1;
    }
    else {
        m_vDir = *vDir;

        CAngleVector	a;
        CFixMatrix		m;
        a [PA] = randN (I2X (1) / 4) - I2X (1) / 8;
        a [BA] = randN (I2X (1) / 4) - I2X (1) / 8;
        a [HA] = randN (I2X (1) / 4) - I2X (1) / 8;
        m = CFixMatrix::Create (a);
        if (nType == WATERFALL_PARTICLES)
            CFixVector::Normalize (m_vDir);
        m_vDrift = m * m_vDir;
        CFixVector::Normalize (m_vDrift);
        if (nType == WATERFALL_PARTICLES) {
            fix dot = CFixVector::Dot (m_vDir, m_vDrift);
            if (dot < I2X (1) / 2)
                return 0;
        }
        float d = float (CFixVector::DeltaAngle (m_vDrift, m_vDir, NULL));
        if (d) {
            d = (float) exp ((I2X (1) / 8) / d);
            nSpeed = (fix) ((float) nSpeed / d);
        }
        m_vDrift *= nSpeed;
        if (nType <= FIRE_PARTICLES)
            m_vDir *= (I2X (3) / 4 + I2X (randN (16)) / 64);
#if DBG
        if (CFixVector::Dot (m_vDrift, m_vDir) < 0)
            d = 0;
#endif
        m_bHaveDir = 1;
    }

    if (vEmittingFace)
        m_vPos = *RandomPointOnQuad (vEmittingFace, vPos);
    else if (nType != BUBBLE_PARTICLES)
        m_vPos = *vPos + m_vDrift * (I2X (1) / 64);
    else {
        //m_vPos = *vPos + vDrift * (I2X (1) / 32);
        nSpeed = m_vDrift.Mag () / 16;
        CFixVector v = CFixVector::Avg ((*mOrient).RVec () * (nSpeed - randN (2 * nSpeed)), (*mOrient).UVec () * (nSpeed - randN (2 * nSpeed)));
        m_vPos = *vPos + v + (*mOrient).FVec () * (I2X (1) / 2 - randN (I2X (1)));
    }

    if ((nType != BUBBLE_PARTICLES) && mOrient) {
        CAngleVector	vRot;
        CFixMatrix		mRot;

        vRot [BA] = 0;
        vRot [PA] = 2048 - ((d_rand () % 9) * 512);
        vRot [HA] = 2048 - ((d_rand () % 9) * 512);
        mRot = CFixMatrix::Create (vRot);
        m_mOrient = *mOrient * mRot;
    }

    if (nType <= SMOKE_PARTICLES) {
        if (m_bBlowUp)
            m_nLife = 2 * m_nLife / 3;
        m_nLife = 4 * m_nLife / 5 + randN (2 * m_nLife / 5);
        m_nRad += float (randN (int (m_nRad)));
    }
    else if (nType == FIRE_PARTICLES) {
        m_nLife = 3 * m_nLife / 4 + randN (m_nLife / 4);
        m_nRad += float (randN (int (m_nRad)));
    }
    else if (nType == BUBBLE_PARTICLES)
        m_nRad = m_nRad / 10 + float (randN (int (9 * m_nRad / 10)));
    else
        m_nRad *= 2;

//m_nRad *= 0.5f;
    m_vStartPos = m_vPos;

    if (m_bBlowUp) {
        m_nWidth = (nType == WATERFALL_PARTICLES) ? m_nRad * 0.6666667f : m_nRad;
        m_nHeight = m_nRad;
    }
    else {
        m_nWidth = (nType == WATERFALL_PARTICLES) ? m_nRad * 0.3333333f : m_nRad * 2;
        m_nHeight = m_nRad * 2;
    }
    m_nWidth /= 65536.0f;
    m_nHeight /= 65536.0f;
    m_nRad /= 65536.0f;

    m_nFrames = ParticleImageInfo (nType).nFrames;
    m_deltaUV = 1.0f / float (m_nFrames);
    if (nType == BULLET_PARTICLES) {
        m_iFrame = 0;
        m_nRotFrame = 0;
        m_nOrient = 3;
    }
    else if (nType == BUBBLE_PARTICLES) {
        m_iFrame = rand () % (m_nFrames * m_nFrames);
        m_nRotFrame = 0;
        m_nOrient = 0;
    }
    else if ((nType == LIGHT_PARTICLES) /*|| (nType == WATERFALL_PARTICLES)*/) {
        m_iFrame = 0;
        m_nRotFrame = 0;
        m_nOrient = 0;
    }
    else if (nType == FIRE_PARTICLES) {
        m_iFrame = (rand () % 10 < 6) ? 0 : 2;	// more fire than smoke (60:40)
        if (m_iFrame < 2)
            m_nLife  = 9 * m_nLife / 10;
        else
            m_nLife  = 10 * m_nLife / 9;
        m_nRotFrame = rand () % PARTICLE_POSITIONS;
        m_nOrient = rand () % 4;
    }
    else {
        m_iFrame = rand () % (m_nFrames * m_nFrames);
        m_nRotFrame = rand () % PARTICLE_POSITIONS;
        m_nOrient = rand () % 4;
#if 1
#endif
    }
    m_nTTL = m_nLife;

    m_nRenderType = RenderType ();
    m_bAnimate = (nType != FIRE_PARTICLES) && (gameOpts->render.particles.nQuality > 1) && (m_nFrames > 1);
    m_bRotate = (m_nRenderType <= SMOKE_PARTICLES) ? 1 : (m_nRenderType == FIRE_PARTICLES + PARTICLE_TYPES) ? -1 : 0;

    UpdateDecay ();
    UpdateTexCoord ();
#if 0
    if (colorP && (colorP->alpha < 0))
        m_color [0].alpha /= 2.0f;
    else
#endif
    {
        if (m_bEmissive)
            m_color [0].alpha = 1.0f;
        else if (nParticleSystemType == SIMPLE_SMOKE_PARTICLES)
            m_color [0].alpha /= 3.5f - float (gameOpts->render.particles.nQuality) / 2.0f; //colorP ? 2.0f + (color.red + color.green + color.blue) / 3.0f : 2.0f;
        else if (nParticleSystemType == SMOKE_PARTICLES)
            m_color [0].alpha /= colorP ? 3.0f - (color.red + color.green + color.blue) / 3.0f : 2.5f;
        else if (nParticleSystemType == BUBBLE_PARTICLES)
            m_color [0].alpha /= 2.0f;
        else if (nParticleSystemType == GATLING_PARTICLES)
            m_color [0].alpha /= 4.0f;
#	if 0
        else if (nParticleSystemType == GATLING_PARTICLES)
            ;//m_color [0].alpha /= 6;
#	endif
    }
    SetupColor (fBrightness);
    return 1;
}
Exemplo n.º 15
0
void calc_alphacolor_hud_type_old( alphacolor_old * ac )
{
	int i,j;
	int tr,tg,tb, Sr, Sg, Sb;
	ubyte * pal;
	int r, g, b, alpha;
	float falpha;

	// Assert(Alphacolors_intited);

//	mprintf(( "Calculating alphacolor for %d,%d,%d,%d\n", ac->r, ac->g, ac->b, ac->alpha ));

	falpha = i2fl(ac->alpha)/255.0f;
	if ( falpha<0.0f ) falpha = 0.0f; else if ( falpha > 1.0f ) falpha = 1.0f;

	alpha = ac->alpha >> 4;
	if (alpha < 0 ) alpha = 0; else if (alpha > 15 ) alpha = 15;
	r = ac->r;
	if (r < 0 ) r = 0; else if (r > 255 ) r = 255;
	g = ac->g;
	if (g < 0 ) g = 0; else if (g > 255 ) g = 255;
	b = ac->b;
	if (b < 0 ) b = 0; else if (b > 255 ) b = 255;

	int ii[16];

	for (j=1; j<15; j++ )	{

		// JAS: Use 1.5/Gamma instead of 1/Gamma because on Adam's
		// PC a gamma of 1.2 makes text look good, but his gamma is
		// really 1.8.   1.8/1.2 = 1.5
		float factor = falpha * (float)pow(i2fl(j)/14.0f, 1.5f/Gr_gamma);
		//float factor = i2fl(j)/14.0f;

		tr = fl2i( i2fl(r) * factor );
		tg = fl2i( i2fl(g) * factor );
		tb = fl2i( i2fl(b) * factor );

		ii[j] = tr;
		if ( tg > ii[j] )	ii[j] = tg;
		if ( tb > ii[j] )	ii[j] = tb;
	}

	pal = gr_palette;

	int m = r;
	if ( g > m ) m = g;
	if ( b > m ) m = b;

	ubyte ri[256], gi[256], bi[256];

	if ( m > 0 )	{
		for (i=0; i<256; i++ )	{
			ri[i] = ubyte((i*r)/m);
			gi[i] = ubyte((i*g)/m);
			bi[i] = ubyte((i*b)/m);
		}
	} else {
		for (i=0; i<256; i++ )	{
			ri[i] = 0;
			gi[i] = 0;
			bi[i] = 0;
		}
	}

	for (i=0; i<256; i++ )	{
		Sr = pal[0];
		Sg = pal[1];
		Sb = pal[2];
		pal += 3;

		int dst_intensity = Sr;
		if ( Sg > dst_intensity ) dst_intensity = Sg;
		if ( Sb > dst_intensity ) dst_intensity = Sb;

		ac->table.lookup[0][i] = (unsigned char)i;

		for (j=1; j<15; j++ )	{

			int tmp_i = max( ii[j], dst_intensity );

			ac->table.lookup[j][i] = (unsigned char)palette_find(ri[tmp_i],gi[tmp_i],bi[tmp_i]);
		}

		float di = (i2fl(Sr)*.30f+i2fl(Sg)*0.60f+i2fl(Sb)*.10f)/255.0f;
		float factor = 0.0f + di*0.75f;

		tr = fl2i( factor*i2fl(r)*falpha );
		tg = fl2i( factor*i2fl(g)*falpha );
		tb = fl2i( factor*i2fl(b)*falpha );

		if ( tr > 255 ) tr = 255; else if ( tr < 0 ) tr = 0;
		if ( tg > 255 ) tg = 255; else if ( tg < 0 ) tg = 0; 
		if ( tb > 255 ) tb = 255; else if ( tb < 0 ) tb = 0;

		ac->table.lookup[15][i] = (unsigned char)palette_find(tr,tg,tb);
		//ac->table.lookup[15][i] = (unsigned char)palette_find(255,0,0);
	}
}
Exemplo n.º 16
0
//clips an edge against one plane.
vertex *clip_edge(int plane_flag,vertex *on_pnt,vertex *off_pnt, uint flags)
{
	float ratio;
	vertex *tmp;

	tmp = get_temp_point();

	if ( plane_flag & CC_OFF_USER )	{

		// Clip with user-defined plane
		vector w, ray_direction;
		float num,den;

		vm_vec_sub(&ray_direction,(vector *)&off_pnt->x,(vector *)&on_pnt->x);
			
		vm_vec_sub(&w,(vector *)&on_pnt->x,&G3_user_clip_point);
	
		den = -vm_vec_dot(&G3_user_clip_normal,&ray_direction);
		if ( den == 0.0f ) {	// Ray & plane are parallel, so there is no intersection
			Int3();	// Get John
			ratio = 1.0f;
		} else {
			num =  vm_vec_dot(&G3_user_clip_normal,&w);
	
			ratio = num / den;
		}

		tmp->x = on_pnt->x + (off_pnt->x-on_pnt->x) * ratio;
		tmp->y = on_pnt->y + (off_pnt->y-on_pnt->y) * ratio;
		tmp->z = on_pnt->z + (off_pnt->z-on_pnt->z) * ratio;

	} else {
		float a,b,kn,kd;

		//compute clipping value k = (xs-zs) / (xs-xe-zs+ze)
		//use x or y as appropriate, and negate x/y value as appropriate

		if (plane_flag & (CC_OFF_RIGHT | CC_OFF_LEFT)) {
			a = on_pnt->x;
			b = off_pnt->x;
		}
		else {
			a = on_pnt->y;
			b = off_pnt->y;
		}

		if (plane_flag & (CC_OFF_LEFT | CC_OFF_BOT)) {
			a = -a;
			b = -b;
		}

		kn = a - on_pnt->z;						//xs-zs
		kd = kn - b + off_pnt->z;				//xs-zs-xe+ze

		ratio = kn / kd;

		tmp->x = on_pnt->x + (off_pnt->x-on_pnt->x) * ratio;
		tmp->y = on_pnt->y + (off_pnt->y-on_pnt->y) * ratio;

		if (plane_flag & (CC_OFF_TOP|CC_OFF_BOT))	{
			tmp->z = tmp->y;
		} else {
			tmp->z = tmp->x;
		}

		if (plane_flag & (CC_OFF_LEFT|CC_OFF_BOT))
			tmp->z = -tmp->z;

	}

	if (flags & TMAP_FLAG_TEXTURED) {
		tmp->u = on_pnt->u + (off_pnt->u-on_pnt->u) * ratio;
		tmp->v = on_pnt->v + (off_pnt->v-on_pnt->v) * ratio;

		tmp->env_u = on_pnt->env_u + (off_pnt->env_u-on_pnt->env_u) * ratio;
		tmp->env_v = on_pnt->env_v + (off_pnt->env_v-on_pnt->env_v) * ratio;
	}

	if (flags & TMAP_FLAG_GOURAUD ) {
		if (flags & TMAP_FLAG_RAMP) {

			float on_b, off_b;

			on_b = i2fl(on_pnt->b);
			off_b = i2fl(off_pnt->b);

			tmp->b = ubyte(fl2i(on_b + (off_b-on_b) * ratio));
		}
		if (flags & TMAP_FLAG_RGB) {
			float on_r, on_b, on_g, onspec_r, onspec_g, onspec_b;
			float off_r, off_b, off_g, offspec_r, offspec_g, offspec_b;

			on_r = i2fl(on_pnt->r);
			off_r = i2fl(off_pnt->r);

			on_g = i2fl(on_pnt->g);
			off_g = i2fl(off_pnt->g);

			on_b = i2fl(on_pnt->b);
			off_b = i2fl(off_pnt->b);


			onspec_r = i2fl(on_pnt->spec_r);
			offspec_r = i2fl(off_pnt->spec_r);

			onspec_g = i2fl(on_pnt->spec_g);
			offspec_g = i2fl(off_pnt->spec_g);

			onspec_b = i2fl(on_pnt->spec_b);
			offspec_b = i2fl(off_pnt->spec_b);


			tmp->r = ubyte(fl2i(on_r + (off_r-on_r) * ratio));
			tmp->g = ubyte(fl2i(on_g + (off_g-on_g) * ratio));
			tmp->b = ubyte(fl2i(on_b + (off_b-on_b) * ratio));

			tmp->spec_r = ubyte(fl2i(onspec_r + (offspec_r-onspec_r) * ratio));
			tmp->spec_g = ubyte(fl2i(onspec_g + (offspec_g-onspec_g) * ratio));
			tmp->spec_b = ubyte(fl2i(onspec_b + (offspec_b-onspec_b) * ratio));
		}
	}
	else
	{
		tmp->spec_r=tmp->spec_g=tmp->spec_b=0;
	}

	if (flags & TMAP_FLAG_ALPHA) {

		float on_a, off_a;

		on_a = i2fl(on_pnt->a);
		off_a = i2fl(off_pnt->a);

		tmp->a = ubyte(fl2i(on_a + (off_a-on_a) * ratio));
	}

	g3_code_vertex(tmp);

	return tmp;	
}
bool FontBuilder::FTSystem::Fill(FTFont *font,void *buffer,int size,unsigned int &pos,float x,float y,float z,unsigned int color,String *str) {
	if(font==nullptr||buffer==nullptr||str==nullptr) {return false;};

	bool tag=false;
	TextVertex *vertices=(TextVertex*)buffer;
	int len=str->length();
	for(int i=0;i<len;i++) {
		/*if(!tag) {
			if(str->at(i)=='<') {
				tag=true;
			};
		}
		else {
			if(str->at(i)=='>') {
				tag=false;
			};
		};*/
		if(/*!tag&&*/str->at(i)==' ') {
			x+=(float)size*1.25f;
			continue;
		};
		unsigned int c=(unsigned int)ubyte(str->at(i));
		FTFont::GlyphEntry *e=font->FindCharIndex(c,size);

		if(!e) {
			CacheCharacter(font,c,size,Vector3(1.0f,1.0f,1.0f));
			e=font->FindCharIndex(c,size);
			if(!e) {e=font->FindCharIndex(ubyte('?'),size);};
		};

		float pw=(float)e->width;
		float ph=(float)e->height;
		float px=x+float(e->offx);
		float py=y+float(e->offy);

		float ux=e->uv[0].x;
		float uy=e->uv[0].y;
		float uw=e->uv[1].x;
		float uh=e->uv[1].y;

		vertices[pos+0].m_position=Vector3(px,py,z);
		vertices[pos+0].m_texcoord=Vector2(ux,uy);
		vertices[pos+0].m_color=color;

		vertices[pos+1].m_position=Vector3(px+pw,py,z);
		vertices[pos+1].m_texcoord=Vector2(ux+uw,uy);
		vertices[pos+1].m_color=color;

		vertices[pos+2].m_position=Vector3(px+pw,py+ph,z);
		vertices[pos+2].m_texcoord=Vector2(ux+uw,uy+uh);
		vertices[pos+2].m_color=color;

		vertices[pos+3].m_position=Vector3(px+pw,py+ph,z);
		vertices[pos+3].m_texcoord=Vector2(ux+uw,uy+uh);
		vertices[pos+3].m_color=color;

		vertices[pos+4].m_position=Vector3(px,py+ph,z);
		vertices[pos+4].m_texcoord=Vector2(ux,uy+uh);
		vertices[pos+4].m_color=color;

		vertices[pos+5].m_position=Vector3(px,py,z);
		vertices[pos+5].m_texcoord=Vector2(ux,uy);
		vertices[pos+5].m_color=color;

		pos+=6;
		x+=e->advx;
	};

	return true;
};
Exemplo n.º 18
0
int G3AccumVertColor (int nVertex, CFloatVector3 *pColorSum, CVertColorData *vcdP, int nThread)
{
	int					i, j, nLights, nType, 
							bSkipHeadlight = gameOpts->ogl.bHeadlight && !gameStates.render.nState,
							bTransform = gameStates.render.nState && !gameStates.ogl.bUseTransform,
							nSaturation = gameOpts->render.color.nSaturation;
	int					nBrightness, nMaxBrightness = 0;
	float					fLightDist, fAttenuation, fLightAngle, spotEffect, NdotL, RdotE;
	CFloatVector3		spotDir, lightDir, lightPos, vertPos, vReflect;
	CFloatVector3		lightColor, colorSum, vertColor = CFloatVector3::Create (0.0f, 0.0f, 0.0f);
	CDynLight*			prl;
	CDynLightIndex*	sliP = &lightManager.Index (0) [nThread];
	CActiveDynLight*	activeLightsP = lightManager.Active (nThread) + sliP->nFirst;
	CVertColorData		vcd = *vcdP;

#if DBG
if (nThread == 0)
	nThread = nThread;
if (nThread == 1)
	nThread = nThread;
#endif
colorSum = *pColorSum;
vertPos = *vcd.vertPosP - *transformation.m_info.posf [1].XYZ ();
vertPos.Neg ();
CFloatVector3::Normalize (vertPos);
nLights = sliP->nActive;
if (nLights > lightManager.LightCount (0))
	nLights = lightManager.LightCount (0);
i = sliP->nLast - sliP->nFirst + 1;
#if DBG
if ((nDbgVertex >= 0) && (nVertex == nDbgVertex))
	nDbgVertex = nDbgVertex;
#endif
for (j = 0; (i > 0) && (nLights > 0); activeLightsP++, i--) {
#if 1
	if (!(prl = activeLightsP->pl))
#else
	if (!(prl = GetActiveRenderLight (activeLightsP, nThread)))
#endif
		continue;
	nLights--;
#if DBG
	if ((nDbgSeg >= 0) && (prl->info.nSegment == nDbgSeg) && ((nDbgSide < 0) || (prl->info.nSide == nDbgSide)))
		nDbgSeg = nDbgSeg;
#	if 0
	else
		continue;
#	endif
#endif
	if (!prl->render.bState)
		continue;
#if 0
	if (i == vcd.nMatLight)
		continue;
#endif
	nType = prl->render.nType;
	if (bSkipHeadlight && (nType == 3))
		continue;
#if ONLY_HEADLIGHT
	if (nType != 3)
		continue;
#endif
	if (prl->info.bVariable && gameData.render.vertColor.bDarkness)
		continue;
	lightColor = *(reinterpret_cast<CFloatVector3*> (&prl->info.color));

	spotDir = *prl->info.vDirf.XYZ (); 
	lightPos = *prl->render.vPosf [bTransform].XYZ ();
	lightDir = lightPos - *vcd.vertPosP;
	if (IsLightVert (nVertex, prl)) {
		fLightDist = 0.0f;
		NdotL = 1.0f;
		}
	else {
		fLightDist = lightDir.Mag () * gameStates.ogl.fLightRange;
		if (lightDir.IsZero ())
			lightDir = vcd.vertNorm;
		else
			CFloatVector3::Normalize (lightDir);
		if ((fLightDist <= 0.1f) || vcd.vertNorm.IsZero ())
			NdotL = 1.0f;
		else {
			NdotL = CFloatVector3::Dot (vcd.vertNorm, lightDir);
			if ((NdotL < 0.0f) && (NdotL > -0.01f))
				NdotL = 0.0f;
			}
		}

#if USE_FACE_DIST
	if (/*(nVertex < 0) &&*/ (nType < 2)) {
		bool bInRad = DistToFace (lightPos, *vcd.vertPosP, prl->info.nSegment, ubyte (prl->info.nSide)) == 0;
		CFloatVector3 dir = lightPos - *vcd.vertPosP;
		fLightDist = dir.Mag () * gameStates.ogl.fLightRange;
		CFloatVector3::Normalize (dir);
		float dot = CFloatVector3::Dot (vcd.vertNorm, dir);
		if (NdotL <= dot) {
			NdotL = dot;
			lightDir = dir;
			}
		if (fabs (fLightDist) < 1.0f)
			fLightDist = 0.0f;
		}
#endif
	if ((gameStates.render.nState || (nType < 2)) && (fLightDist > 0.0f)) {
		// decrease the distance between light and vertex by the light's radius
		// check whether the vertex is behind the light or the light shines at the vertice's back
		// if any of these conditions apply, decrease the light radius, chosing the smaller negative angle
		fLightAngle = (fLightDist > 0.1f) ? -CFloatVector3::Dot (lightDir, spotDir) + 0.01f : 1.0f;
#if !USE_FACE_DIST
		float lightRad = (fLightAngle < 0.0f) ? 0.0f : prl->info.fRad * (1.0f - 0.9f * float (sqrt (fabs (fLightAngle))));	// make rad smaller the greater the angle 
		fLightDist -= lightRad * gameStates.ogl.fLightRange; //make light darker if face behind light source
#endif
		}
	else
		fLightAngle = 1.0f;
	if	(fLightDist <= 0.0f) {
		NdotL = 1.0f;
		fLightDist = 0.0f;
		fAttenuation = 1.0f / prl->info.fBrightness;
		}
	else {	//make it decay faster
		float decay = min (fLightAngle, NdotL);
		if (decay < 0.0f) {
#if 0
			fLightDist -= 1e2f * decay;
#else
			decay += 1.0000001f;
			fLightDist /= decay * decay;
#endif
			}	
		//if ((nType < 2) && (nVertex < 0))
		//fLightDist *= 0.9f;
#if USE_FACE_DIST
		if (/*(nVertex < 0) &&*/ (nType < 2)) 
			fAttenuation = (1.0f + GEO_LIN_ATT * fLightDist + GEO_QUAD_ATT * fLightDist * fLightDist);
		else
#endif
			fAttenuation = (1.0f + GEO_LIN_ATT * fLightDist + GEO_QUAD_ATT * fLightDist * fLightDist);
#if USE_FACE_DIST
		if ((nType < 2) && (prl->info.fRad > 0.0f))
#else
		if ((nVertex > -1) && (prl->info.fRad > 0.0f))
#endif
			NdotL += (1.0f - NdotL) / (0.5f + fAttenuation / 2.0f);
		fAttenuation /= prl->info.fBrightness;
		}
	if (prl->info.bSpot) {
		if (NdotL <= 0.0f)
			continue;
		CFloatVector3::Normalize (spotDir);
		lightDir = -lightDir;
		/*
		lightDir [Y] = -lightDir [Y];
		lightDir [Z] = -lightDir [Z];
		*/
		//spotEffect = G3_DOTF (spotDir, lightDir);
		spotEffect = CFloatVector3::Dot (spotDir, lightDir);

		if (spotEffect <= prl->info.fSpotAngle)
			continue;
		if (prl->info.fSpotExponent)
			spotEffect = (float) pow (spotEffect, prl->info.fSpotExponent);
		fAttenuation /= spotEffect * gameStates.ogl.fLightRange;
		vertColor = *gameData.render.vertColor.matAmbient.XYZ () + (*gameData.render.vertColor.matDiffuse.XYZ () * NdotL);
		}
	else {
		vertColor = *gameData.render.vertColor.matAmbient.XYZ ();
		if (NdotL > 0.1f)
			vertColor += (*gameData.render.vertColor.matDiffuse.XYZ () * NdotL);
		else if (NdotL >= 0.0f)
			vertColor += (*gameData.render.vertColor.matDiffuse.XYZ () * 0.1f);
		else
			NdotL = 0.0f;
		}
	vertColor *= lightColor;
	if ((NdotL > 0.0f) && (fLightDist > 0.0f) && (vcd.fMatShininess > 0.0f) /* && vcd.bMatSpecular */) {
		//RdotV = max (dot (Reflect (-Normalize (lightDir), Normal), Normalize (-vertPos)), 0.0);
		if (!prl->info.bSpot)	//need direction from light to vertex now
			lightDir.Neg ();
		vReflect = CFloatVector3::Reflect (lightDir, vcd.vertNorm);
		CFloatVector3::Normalize (vReflect);
#if DBG
		if ((nDbgVertex >= 0) && (nVertex == nDbgVertex))
			nDbgVertex = nDbgVertex;
#endif
		RdotE = CFloatVector3::Dot (vReflect, vertPos);
		if (RdotE > 0.0f) {
			//spec = pow (Reflect dot lightToEye, matShininess) * matSpecular * lightSpecular
			vertColor += (lightColor * (float) pow (RdotE, vcd.fMatShininess));
			}
		}
	if ((nSaturation < 2) || gameStates.render.bHaveLightmaps) {//sum up color components
		colorSum = colorSum + vertColor * (1.0f / fAttenuation);
		}
	else {	//use max. color components
		vertColor = vertColor * fAttenuation;
		nBrightness = sqri ((int) (vertColor [R] * 1000)) + sqri ((int) (vertColor [G] * 1000)) + sqri ((int) (vertColor [B] * 1000));
		if (nMaxBrightness < nBrightness) {
			nMaxBrightness = nBrightness;
			colorSum = vertColor;
			}
		else if (nMaxBrightness == nBrightness) {
			if (colorSum [R] < vertColor [R])
				colorSum [R] = vertColor [R];
			if (colorSum [G] < vertColor [G])
				colorSum [G] = vertColor [G];
			if (colorSum [B] < vertColor [B])
				colorSum [B] = vertColor [B];
			}
		}
	j++;
	}
if (j) {
	if ((nSaturation == 1) || gameStates.render.bHaveLightmaps) { //if a color component is > 1, cap color components using highest component value
		float	cMax = colorSum [R];
		if (cMax < colorSum [G])
			cMax = colorSum [G];
		if (cMax < colorSum [B])
			cMax = colorSum [B];
		if (cMax > 1) {
			colorSum [R] /= cMax;
			colorSum [G] /= cMax;
			colorSum [B] /= cMax;
			}
		}
	*pColorSum = colorSum;
	}
#if DBG
if (nLights)
	nLights = 0;
#endif
if (!RENDERPATH)
	lightManager.ResetNearestToVertex (nVertex, nThread);
return j;
}
Exemplo n.º 19
0
int PageInBitmap (CBitmap *bmP, const char *bmName, int nIndex, int bD1, bool bHires)
{
	CBitmap			*altBmP = NULL;
	int				nFile, nSize, nOffset, nFrames, nShrinkFactor, nBestShrinkFactor,
						bRedone = 0, bTGA;
	sbyte				nFlags;
	bool				bDefault = false;
	CFile				cf, *cfP = &cf;
	char				fn [6][FILENAME_LEN];

#if DBG
if (!bmName)
	return 0;
if ((nDbgTexture > 0) && (nIndex == nDbgTexture))
	nDbgTexture = nDbgTexture;
#endif
if (bmP->Buffer ())
	return 1;

StopTime ();
nShrinkFactor = 8 >> min (gameOpts->render.textures.nQuality, gameStates.render.nMaxTextureQuality);
if (nShrinkFactor < 4) {
	if (nShrinkFactor == 1)
		nShrinkFactor = 2;	// cap texture quality at 256x256 (x frame#)
	else if (IsPowerup (bmName) || IsWeapon (bmName))	// force downscaling of powerup hires textures
		nShrinkFactor <<= 1;
	}
nSize = (int) bmP->FrameSize ();
if (nIndex >= 0)
	GetFlagData (bmName, nIndex);
#if DBG
if (strstr (bmName, "metl139"))
	bmName = bmName;
#endif
if (gameStates.app.bNostalgia)
	gameOpts->render.textures.bUseHires [0] = 0;

bTGA = 0;
nFlags = (nIndex < 0) ? 0 : gameData.pig.tex.bitmapFlags [bD1][nIndex];
if (bmP->Texture ())
	bmP->Texture ()->Release ();
bmP->SetBPP (1);

if ((*bmName && /*!gameStates.app.bDemoData &&*/ ((nIndex < 0) || IsCockpit (bmName) || bHires || gameOpts->render.textures.bUseHires [0])) &&
	 !(gameOpts->render.powerups.b3D && IsWeapon (bmName) && !gameStates.app.bHaveMod)) {
#if 0
	if ((nIndex >= 0) && ReadS3TC (gameData.pig.tex.altBitmaps [bD1] + nIndex, gameFolders.szTextureCacheDir [bD1], bmName)) {
		altBmP = gameData.pig.tex.altBitmaps [bD1] + nIndex;
		altBmP->nType = BM_TYPE_ALT;
		bmP->SetOverride (altBmP);
		BM_FRAMECOUNT (altBmP) = 1;
		nFlags &= ~BM_FLAG_RLE;
		nFlags |= BM_FLAG_TGA;
		bmP = altBmP;
		altBmP = NULL;
		}
	else
#endif
	if (*gameFolders.szTextureDir [2]) {
		char szLevelFolder [FILENAME_LEN];
		if (gameData.missions.nCurrentLevel < 0)
			sprintf (szLevelFolder, "slevel%02d", -gameData.missions.nCurrentLevel);
		else
			sprintf (szLevelFolder, "level%02d", gameData.missions.nCurrentLevel);
		sprintf (gameFolders.szTextureDir [3], "%s/%s", gameFolders.szTextureDir [2], szLevelFolder);
		sprintf (gameFolders.szTextureCacheDir [3], "%s/%s", gameFolders.szTextureCacheDir [2], szLevelFolder);
		}
	else
		*gameFolders.szTextureDir [3] =
		*gameFolders.szTextureCacheDir [3] = '\0';
	MakeBitmapFilenames (bmName, gameFolders.szTextureDir [3], gameFolders.szTextureCacheDir [3], fn [1], fn [0], nShrinkFactor);
	MakeBitmapFilenames (bmName, gameFolders.szTextureDir [2], gameFolders.szTextureCacheDir [2], fn [3], fn [2], nShrinkFactor);
	MakeBitmapFilenames (bmName, gameFolders.szTextureDir [bD1], gameFolders.szTextureCacheDir [bD1], fn [5], fn [4], nShrinkFactor);

	if (0 <= (nFile = OpenBitmapFile (fn, cfP))) {
		cfP->Close ();
		PrintLog ("loading hires texture '%s' (quality: %d)\n", fn [nFile], min (gameOpts->render.textures.nQuality, gameStates.render.nMaxTextureQuality));
		if (nFile < 2)	//was level specific mod folder
			MakeTexSubFolders (gameFolders.szTextureCacheDir [3]);
		if (nIndex < 0)
			altBmP = &gameData.pig.tex.addonBitmaps [-nIndex - 1];
		else
			altBmP = &gameData.pig.tex.altBitmaps [bD1][nIndex];
		if (!ReadTGA (fn [nFile], "", altBmP)) {
			altBmP = NULL;
			if (!bDefault)
				cfP->Close ();
			throw (EX_OUT_OF_MEMORY);
			}
		else {
			bTGA = 1;
			if (strstr (fn [nFile], "omegblob#") && strstr (fn [nFile], "/mods/"))
				gameStates.render.bOmegaModded = 1;
			altBmP->SetType (BM_TYPE_ALT);
			bmP->SetOverride (altBmP);
			bmP = altBmP;
			bmP->DelFlags (BM_FLAG_RLE);
			nSize = bmP->Size ();
			nFrames = (bmP->Height () % bmP->Width ()) ? 1 : bmP->Height () / bmP->Width ();
			bmP->SetFrameCount (ubyte (nFrames));
			nOffset = -1;
			if (nIndex >= 0) {
				nFlags = bmP->Flags ();
				if (bmP->Height () > bmP->Width ()) {
					tEffectClip	*ecP = NULL;
					tWallClip *wcP;
					tVideoClip *vcP;
					while ((ecP = FindEffect (ecP, nIndex))) {
						//e->vc.nFrameCount = nFrames;
						ecP->flags |= EF_ALTFMT;
						//ecP->vClipInfo.flags |= WCF_ALTFMT;
						}
					if (!ecP) {
						if ((wcP = FindWallAnim (nIndex))) {
						//w->nFrameCount = nFrames;
							wcP->flags |= WCF_ALTFMT;
							}
						else if ((vcP = FindVClip (nIndex))) {
							//v->nFrameCount = nFrames;
							vcP->flags |= WCF_ALTFMT;
							}
						else {
							PrintLog ("   couldn't find animation for '%s'\n", bmName);
							}
						}
					}
				}
			}
		}
	}

if (!altBmP) {
	if (nIndex < 0) {
		StartTime (0);
		return 0;
		}
	cfP = cfPiggy + bD1;
	if (!cfP->File ())
		PiggyInitPigFile (NULL);
	nOffset = bitmapOffsets [bD1][nIndex];
	bDefault = true;
	}

bRedone = 1;
if ((nOffset >= 0) && cfP->Seek (nOffset, SEEK_SET)) {
	if (!bDefault)
		cfP->Close ();
	throw (EX_IO_ERROR);
	}
#if 1//DBG
bmP->SetName (bmName);
#endif
#if TEXTURE_COMPRESSION
if (bmP->Compressed ())
	UseBitmapCache (bmP, bmP->CompressedSize ());
else
#endif
	{
	if (bTGA || bmP->CreateBuffer ())
		UseBitmapCache (bmP, nSize);
	}
if (!bmP->Buffer () || (bitmapCacheUsed > bitmapCacheSize)) {
	if (!bDefault)
		cfP->Close ();
	throw (EX_OUT_OF_MEMORY);
	}
if (!bTGA && (nIndex >= 0))
	bmP->SetFlags (nFlags);
bmP->SetId (nIndex);
#if DBG
if (nIndex == nDbgTexture)
	nDbgTexture = nDbgTexture;
#endif
int i = ReadBitmap (bmP, nSize, cfP, bDefault, bD1 != 0, bHires);
if (i) {
	if (i < 0) {
		if (!bDefault)
			cfP->Close ();
		throw (EX_IO_ERROR);
		}
	}
else
#if TEXTURE_COMPRESSION
if (!bmP->Compressed ())
#endif
	{
	bmP->SetType (BM_TYPE_ALT);
	bmP->SetTranspType (-1);
	if (IsOpaqueDoor (nIndex)) {
		bmP->DelFlags (BM_FLAG_TRANSPARENT);
		bmP->TransparentFrames () [0] &= ~1;
		}
#if TEXTURE_COMPRESSION
	if (CompressTGA (bmP))
		bmP->SaveS3TC (gameFolders.szTextureCacheDir [(nFile < 2) ? 3 : (nFile < 4) ? 2 : bD1], bmName);
	else {
#endif
		nBestShrinkFactor = BestShrinkFactor (bmP, nShrinkFactor);
		if ((nBestShrinkFactor > 1) && ShrinkTGA (bmP, nBestShrinkFactor, nBestShrinkFactor, 1)) {
			nSize /= (nBestShrinkFactor * nBestShrinkFactor);
			if (gameStates.app.bCacheTextures) {
				tTgaHeader	h;

				memset (&h, 0, sizeof (h));
				h.bits = bmP->BPP () * 8;
				h.width = bmP->Width ();
				h.height = bmP->Height ();
				h.imageType = 2;
				// nFile < 2: mod level texture folder
				// nFile < 4: mod texture folder
				// otherwise standard D1 or D2 texture folder
				SaveTGA (bmName, gameFolders.szTextureCacheDir [(nFile < 2) ? 3 : (nFile < 4) ? 2 : bD1], &h, bmP);
				}
			}
		}
#if TEXTURE_COMPRESSION
	}
#endif

#if DBG
nPrevIndex = nIndex;
strcpy (szPrevBm, bmName);
#endif
tRgbColorf color;
if (0 <= (bmP->AvgColor (&color)))
	bmP->SetAvgColorIndex (ubyte (bmP->Palette ()->ClosestColor (&color)));
StartTime (0);
if (!bDefault)
	cfP->Close ();
return 1;
}
Exemplo n.º 20
0
Arquivo: reduce.c Projeto: Albitex/tb
void reconstruct_table(ubyte *table, char color, struct dtz_map *map)
{
  int i, k;
  int num = map->max_num;
  ubyte (*inv_map)[256] = map->inv_map;
  ubyte v[256];

  for (i = 0; i < 256; i++)
    v[i] = 0;

#ifndef SUICIDE
  v[ILLEGAL] = num;
  v[BROKEN] = num;
  v[UNKNOWN] = num;
  v[CAPT_DRAW] = num;
  v[CAPT_CWIN_RED] = num;
  v[CAPT_WIN] = num;
  for (i = 0; i <= REDUCE_PLY_RED; i++) {
    v[CAPT_CWIN_RED + i + 2] = inv_map[2][(reduce_cnt + i) / 2];
    v[LOSS_IN_ONE - i - 1] = inv_map[3][(reduce_cnt + i + 1) / 2];
  }
  v[CAPT_CWIN_RED + i + 2] = inv_map[2][(reduce_cnt + i) / 2];
#else
  v[BROKEN] = num;
  v[UNKNOWN] = num;
  v[CAPT_WIN] = v[CAPT_CWIN] = v[CAPT_DRAW] = num;
  v[CAPT_CLOSS] = v[CAPT_LOSS] = num;
  v[THREAT_WIN] = v[BASE_WIN + 4] = v[THREAT_DRAW] = num;
  for (i = 0; i <= REDUCE_PLY_RED; i++) {
    v[BASE_WIN + i + 6] = inv_map[2][(reduce_cnt + i) / 2];
    v[BASE_LOSS - i - 4] = inv_map[3][(reduce_cnt + i) / 2];
  }
#endif

  transform_v = v;
  transform_tbl = table;
  run_threaded(transform_table, work_g, 0);

  v[0] = 0;
  int red_cnt = 0;
#ifndef SUICIDE
  for (k = 0; k < num_saves; k++) {
    if (k == 0) {
      v[255] = inv_map[1][0];
      if (map->ply_accurate_win)
	for (i = 0; i < DRAW_RULE; i++)
	  v[i + 1] = inv_map[0][i];
      else
	for (i = 0; i < DRAW_RULE; i++)
	  v[i + 1] = inv_map[0][i / 2];
      if (map->ply_accurate_loss)
	for (i = 0; i < DRAW_RULE; i++)
	  v[254 - i] = inv_map[1][i];
      else
	for (i = 0; i < DRAW_RULE; i++)
	  v[254 - i] = inv_map[1][i / 2];
      for (; i <= REDUCE_PLY; i += 2) {
	v[1 + DRAW_RULE + (i - DRAW_RULE) / 2] = inv_map[2][(i - DRAW_RULE) / 2];
	v[254 - DRAW_RULE - (i - DRAW_RULE) / 2] = inv_map[3][(i - DRAW_RULE) / 2];
      }
      red_cnt = REDUCE_PLY - DRAW_RULE - 2;
    } else {
      for (i = 0; i <= REDUCE_PLY_RED + 1; i += 2) {
	v[1 + ((red_cnt & 1) + i) / 2] = inv_map[2][(red_cnt + i) / 2];
	v[255 - ((red_cnt & 1) + i + 1) / 2] = inv_map[3][(red_cnt + i + 1) / 2];
      }
      red_cnt += REDUCE_PLY_RED;
    }
    reconstruct_table_pass(table, color, k, v);
  }
#else
  for (k = 0; k < num_saves; k++) {
    if (k == 0) {
      if (map->ply_accurate_win)
	for (i = 3; i <= DRAW_RULE; i++)
	  v[1 + (i - 3)] = inv_map[0][i - 1];
      else
	for (i = 3; i <= DRAW_RULE; i++)
	  v[1 + (i - 3)] = inv_map[0][(i - 1) / 2];
      if (map->ply_accurate_loss)
	for (i = 2; i <= DRAW_RULE; i++)
	  v[255 - (i - 2)] = inv_map[1][i - 1];
      else
	for (i = 2; i <= DRAW_RULE; i++)
	  v[255 - (i - 2)] = inv_map[1][(i - 1) / 2];
      for (i = DRAW_RULE + 1; i < REDUCE_PLY; i++) {
	v[DRAW_RULE - 1 + (i - DRAW_RULE - 1) / 2] = inv_map[2][(i - DRAW_RULE - 1) / 2];
	v[254 - (DRAW_RULE - 2) - (i - DRAW_RULE - 1) / 2] = inv_map[3][(i - DRAW_RULE - 1) / 2];
      }
      red_cnt = REDUCE_PLY - 1 - DRAW_RULE;
    } else {
      for (i = 0; i < REDUCE_PLY_RED; i += 2) {
	v[1 + ((red_cnt & 1) + i) / 2] = inv_map[2][(red_cnt + i) / 2];
	v[255 - ((red_cnt & 1) + i) / 2] = inv_map[3][(red_cnt + i) / 2];
      }
      red_cnt += REDUCE_PLY_RED;
    }
    reconstruct_table_pass(table, color, k, v);
  }
#endif

  if (color == 'w') {
    printf("Verifying reconstructed table_w based on collected statistics.\n");
    verify_stats(table_w, total_stats_w, map);
  } else {
    printf("Verifying reconstructed table_b based on collected statistics.\n");
    verify_stats(table_b, total_stats_b, map);
  }
}
Exemplo n.º 21
0
void test_a_doublebyte_conv(const std::string& encname)
{
	std::wstring wencname(encname.begin(), encname.end());
	xm::Encoding* enc = xm::EncodingManager::Instance().GetEncoding(wencname);

	MB2UDataMap::const_iterator mb2uend = mb2u[encname].end();
	for (size_t i=0; i<256; ++i)
	{
		ubyte bs[2] = { ubyte(i), 0 };
		if (enc->IsLeadByte(bs[0]))
		{
			for(size_t j=0; j<256; ++j)
			{
				char mbs_arr[3] = { char(i), char(j), 0 };
				MB2UDataMap::const_iterator it = mb2u[encname].find(mbs_arr);

				bs[1] = ubyte(j);
				ucs4_t u = enc->MultiBytetoUCS4(bs);
				if (u != 0)
				{
					BOOST_CHECK(it != mb2uend);
					if (it != mb2uend)
					{
						ucs4_t t = it->second;
						BOOST_CHECK(u == t);
					}
				}
				else
				{
					BOOST_CHECK(it == mb2uend);
				}
			}
		}
		else
		{
			char mbs_arr[2] = { char(i), 0 };
			MB2UDataMap::const_iterator it = mb2u[encname].find(mbs_arr);
			ucs4_t u = enc->MultiBytetoUCS4(bs);
			if (u != 0)
			{
				BOOST_CHECK(it != mb2uend);
				if (it != mb2uend)
				{
					ucs4_t t = it->second;
					BOOST_CHECK(u == t);
				}
			}
			else
			{
				BOOST_CHECK(it == mb2uend);
			}
		}
	}

	U2MBDataMap::const_iterator u2mbend = u2mb[encname].end();
	for (ucs4_t i=0; i<=0x10FFFF; ++i)
	{
		ubyte buf[4];
		size_t n = enc->UCS4toMultiByte(i, buf);
		BOOST_CHECK(n <= 2);

		U2MBDataMap::const_iterator it = u2mb[encname].find(i);
		if (n == 1 || n == 2)
		{
			BOOST_CHECK(it != u2mbend);
			if (it != u2mbend)
			{
				buf[n] = 0;
				std::string mbs((const char*)buf);
				BOOST_CHECK(it->second == mbs);
			}
		}
		else if(n == 0)
		{
			BOOST_CHECK(it == u2mbend);
		}
	}

	mb2u[encname].clear();
	u2mb[encname].clear();
}