Example #1
0
/** 
 * Load text data, font bitmap and clear list and structure chars 
 * @return TRUE if it completed successfully or FALSE otherwise
 */
bool
scrolltext_once_init (void)
{
  Sint32 i;
  fntscroll *schar;

  scrolltext_free ();

  if (!scrolltext_load ())
    {
      return FALSE;
    }

  /* extract scrolltext font bitmap (12,143 bytes) */
  if (!bitmap_load
      ("graphics/bitmap/fonts/font_scrolltext.spr", &fnt_scroll[0], 1,
       FONT_SCROLLTEXT_MAXOF_GLYPHS))
    {
      return FALSE;
    }

  /* allocate empty string */
  if (scrolltext_emtpy == NULL)
    {
      scrolltext_emtpy = memory_allocation (SCROLLTEXT_EMPTY_LENGTH + 1);
      if (scrolltext_emtpy == NULL)
        {
          LOG_ERR ("scrolltext_emtpy out of memory");
          return FALSE;
        }
      for (i = 0; i < SCROLLTEXT_EMPTY_LENGTH; i++)
        {
          scrolltext_emtpy[i] = ' ';
        }
      scrolltext_emtpy[i] = '\0';
    }

  /* allocate chars elements */
  if (scrolltext_chars == NULL)
    {
      scrolltext_chars =
        (fntscroll *) memory_allocation (SCROLLTEXT_MAXOF_CHARS *
                                         sizeof (fntscroll));
      if (scrolltext_chars == NULL)
        {
          LOG_ERR ("scrolltext_chars out of memory");
          return FALSE;
        }
    }

  /* clear list and chars elements */
  for (i = 0; i < SCROLLTEXT_MAXOF_CHARS; i++)
    {
      schar = &scrolltext_chars[i];
      schar->is_enabled = FALSE;
    }
  scrolltext_numof_chars = 0;
  scrolltext_init ();
  return TRUE;
}
Example #2
0
/**
 * Allocate memory and load a file (filename with a number)
 * @param filename Filename specified by path
 * @param num Interger to convert in string
 * @return Pointer to the file data
 */
char *
loadfile_num (const char *const filename, Sint32 num)
{
  char *data, *fname;

  if (filename == NULL || strlen (filename) == 0)
    {
      LOG_ERR ("filename is a NULL string");
      return NULL;
    }

  fname = memory_allocation (strlen (filename) + 1);
  if (fname == NULL)
    {
      LOG_ERR ("filename: \"%s\"; num: %i; "
               "not enough memory to allocate %i bytes",
               filename, num, (Uint32) (strlen (filename) + 1));
      return NULL;
    }
  sprintf (fname, filename, num);
  LOG_DBG ("file \"%s\" was loaded in memory", fname);
  data = load_file (fname);
  free_memory (fname);
  return data;
}
Example #3
0
// Инициализация коммуникаций (1), перевод глобальных параметров в локальные процессора (2),
// инициализация ускорителя (2.5), выделение памяти (3), загрузка начальных/сохраненных данных (4)
// Для задачи Б-Л загрузка проницаемостей из файла.
void initialization(long int* time_counter, int argc, char* argv[])
{
	communication_initialization(argc, argv); // (1)

	print_task_name();

	sizes_initialization();

	blocks_initialization();

	global_to_local_vars(); // (2)

	device_initialization(); // (2.5)

	memory_allocation(); // (3)

	load_permeability(HostArraysPtr.K); // (5)

	data_initialization(time_counter);

	load_data_to_device(HostArraysPtr.P_w, DevArraysPtrLoc->P_w);
	load_data_to_device(HostArraysPtr.S_w, DevArraysPtrLoc->S_w);
	load_data_to_device(HostArraysPtr.S_n, DevArraysPtrLoc->S_n);
	load_data_to_device(HostArraysPtr.S_g, DevArraysPtrLoc->S_g);
	load_data_to_device(HostArraysPtr.roS_w_old, DevArraysPtrLoc->roS_w_old);
	load_data_to_device(HostArraysPtr.roS_n_old, DevArraysPtrLoc->roS_n_old);
	load_data_to_device(HostArraysPtr.roS_g_old, DevArraysPtrLoc->roS_g_old);
	load_data_to_device(HostArraysPtr.m, DevArraysPtrLoc->m);
	load_data_to_device(HostArraysPtr.K, DevArraysPtrLoc->K);
#ifdef ENERGY
	load_data_to_device(HostArraysPtr.T, DevArraysPtrLoc->T);
#endif
}
Example #4
0
bool
scrolltext_extract (void)
{
  Uint32 i;
  const char *model = EXPORT_DIR "/scrolltext/char-xx.png";
  char *filename = memory_allocation (strlen (model) + 1);
  if (filename == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes\n",
               (Uint32) (strlen (model) + 1));
      return FALSE;
    }
  if (!create_dir (EXPORT_DIR "/scrolltext"))
    {
      free_memory (filename);
      return FALSE;
    }
  for (i = 0; i < FONT_SCROLLTEXT_MAXOF_GLYPHS; i++)
    {
      sprintf (filename, EXPORT_DIR "/scrolltext/char-%02d.png", i);
      if (!bitmap_to_png (&fnt_scroll[i], filename, 20, 21, offscreen_pitch))
        {
          free_memory (filename);
          return FALSE;
        }
    }
  free_memory (filename);
  return TRUE;
}
Example #5
0
/** 
 * Load scrolltext ascii data
 * @return TRUE if it completed successfully or FALSE otherwise
 */
bool
scrolltext_load (void)
{
  Uint32 filesize, i, j;
  char *filedata;
  filedata = loadfile_with_lang ("texts/scroll_%s.txt", &filesize);
  if (filedata == NULL)
    {
      return FALSE;
    }

  scrolltext_menu = memory_allocation (filesize);
  if (scrolltext_menu == NULL)
    {
      free_memory (filedata);
      return FALSE;
    }

  j = 0;
  for (i = 0; i < filesize; i++)
    {
      if (filedata[i] >= ' ' && filedata[i] != '"')
        {
          scrolltext_menu[j++] = filedata[i];
        }
    }
  free_memory (filedata);
  return TRUE;
}
Example #6
0
int* kPartitioning(double ** comm, int n, int k, int * constraints, int nb_constraints, int greedy_trials)
{
  /* ##### declarations & allocations ##### */

  PriorityQueue Qpart, *Q = NULL, *Qinst = NULL;
  double **D = NULL;
  int deficit, surplus, *part = NULL;
  int real_n = n-nb_constraints;

  part = build_p_vector(comm, n, k, greedy_trials, constraints, nb_constraints);

  memory_allocation(&Q, &Qinst, &D, real_n, k);

  /* ##### Initialization ##### */

  initialization(part, comm, &Qpart, Q, Qinst, D, real_n, k, &deficit, &surplus);

  /* ##### Main loop ##### */
  while((nextGain(&Qpart, Q, &deficit, &surplus))>0)
    {
      algo(part, comm, &Qpart, Q, Qinst, D, real_n, &deficit, &surplus);
    }

  /* ##### Balancing the partition  ##### */
  balancing(real_n, deficit, surplus, D, part); /*if partition isn't balanced we have to make one last move*/

  /* ##### Memory deallocation ##### */
  destruction(&Qpart, Q, Qinst, D, real_n, k);

  return part;
}
Example #7
0
/**
 * Load the list of the games et increase the counter of the game
 * selected game in the counter file
 * The counter is re-initialized when a new version of the game is launched
 * If the file does not exist or that it is corrupted, it is recreated
 * @param gamename The name of the game (ie "Powermanga")
 * @param vmaj Major version
 * @param vmin Minor version
 * @return Number of times the game has been launched, 0 the first time
 */
Sint32
counter_shareware_update (char *gamename, Sint32 vmaj, Sint32 vmin)
{
  Sint32 cnt;
  Uint32 ver = (vmaj << 16) + vmin;
  cnt = 0;

  /* load file */
  if (!counter_load_file ())
    {
      /* first use or non-existent file */
      GameCount = (TLKGameInfo *) memory_allocation (sizeof (TLKGameInfo));
      if (GameCount == NULL)
        {
          return FALSE;
        }
      GameCount[0].count = 1;
      GameCount[0].time = 0;
      GameCount[0].version = ver;
      memcpy (GameCount[0].name, gamename, strlen (gamename) + 1);
      num_of_games = 1;
      counter_save_file ();
    }
  else
    {
      /* search a game */
      cnt = counter_search_game (gamename);
      if (cnt == -1)
        {
          /* add game */
          GameCount[num_of_games].count = 1;
          GameCount[0].time = 0;
          GameCount[0].version = ver;
          memcpy (GameCount[num_of_games].name, gamename,
                  strlen (gamename) + 1);
          num_of_games++;
          cnt = 0;
        }
      else
        {
          /* check version */
          if (GameCount[cnt].version < ver)
            {
              /* new version available */
              GameCount[cnt].version = ver;
              GameCount[cnt].count = 1;
              GameCount[cnt].time = 0;
              cnt = 0;
            }
          else
            {
              /* increase counter */
              GameCount[cnt].count++;
              cnt = GameCount[cnt].count;
            }
        }
      counter_save_file ();
    }
  return cnt;
}
Example #8
0
/**
 * Load images of the gems and allocate gems structures 
 * @return TRUE if it completed successfully or FALSE otherwise 
 */
bool
bonus_once_init (void)
{
  bonus_free ();

  /* extract gems sprites images (80,868 bytes) */
  if (!image_load
      ("graphics/sprites/bonus_gems.spr", &bonus[0][0], GEM_NUMOF_TYPES,
       GEM_NUMOF_IMAGES))
    {
      return FALSE;
    }

  /* allocate gems data structure */
  if (gems == NULL)
    {
      gems =
        (gem_str *) memory_allocation (MAX_NUMOF_GEMS_ON_SCREEN *
                                       sizeof (gem_str));
      if (gems == NULL)
        {
          LOG_ERR ("not enough memory to allocate 'gems' structure");
          return FALSE;
        }
    }
  return 1;
}
Example #9
0
/** 
 * Color conversion 8-bit to 15-bits 16-bit, 24 bit or 32-bit
 * @param Pointer to a bitmap structure
 * @return Pointer to a pixel buffer
 */
static char *
convert_16_or_24 (bitmap_desc * gfx)
{
  Uint32 size;
  char *buffer;
  if (bytes_per_pixel == 1)
    {
      return gfx->pixel;
    }
  size = gfx->width * gfx->height;
  buffer = memory_allocation (size * bytes_per_pixel);
  if (buffer == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes!",
               size * bytes_per_pixel);
      return NULL;
    }
  switch (bytes_per_pixel)
    {
    case 2:
      conv8_16 (gfx->pixel, buffer, pal16, size);
      break;
    case 3:
      conv8_24 (gfx->pixel, buffer, pal32, size);
      break;
    case 4:
      conv8_32 (gfx->pixel, buffer, pal32, size);
      break;
    }
  free_memory (gfx->pixel);
  gfx->pixel = buffer;
  gfx->size = size * bytes_per_pixel;
  return buffer;
}
Example #10
0
/**
 * Allocate memory and load a file (filename with a language code)
 * @param filename Filename specified by path
 * @param fsize Pointer on the size of file which will be loaded
 * @return Pointer to the file data
 */
char *
loadfile_with_lang (const char *const filename, Uint32 * const fsize)
{
  const char *lang;
  char *data, *fname;
  if (filename == NULL || strlen (filename) == 0)
    {
      LOG_ERR ("filename is a NULL string");
      return NULL;
    }

  fname = memory_allocation (strlen (filename) + 1);
  if (fname == NULL)
    {
      LOG_ERR ("filename: \"%s\" not enough memory"
               " to allocate %i bytes", filename,
               (Uint32) (strlen (filename) + 1));
      return NULL;
    }
  strcpy (fname, filename);
  lang = configfile_get_lang ();
  sprintf (fname, filename, lang);
  LOG_DBG ("file \"%s\" was loaded in memory", fname);
  data = loadfile (fname, fsize);
  free_memory (fname);
  return data;
}
Example #11
0
/** 
 * Extract a "*.spr" file data into a 'bitmap' structure 
 * @param bmp Pointer to a bitmap structure
 * @param filedata Pointer to the file data
 * @return The source pointer incremented
 */
static char *
bitmap_extract (bitmap * bmp, char *filedata)
{
  char *ptr8;
  Sint32 *ptr32;
  ptr8 = filedata;

  /*
   * read the pixel data (8 bits per pixel)
   */
  /* 32-bit access */
  ptr32 = (Sint32 *) (ptr8);
  /* number of pixels */
  bmp->numof_pixels = little_endian_to_int (ptr32++);
  bmp->img = memory_allocation (bmp->numof_pixels * bytes_per_pixel);
  if (bmp->img == NULL)
    {
      return NULL;
    }
  /* 8-bit access */
  ptr8 = (char *) ptr32;
  ptr8 = read_pixels (bmp->numof_pixels, ptr8, bmp->img);

  /* 
   * read offsets and repeat values 
   */
  /* 32-bit access */
  ptr32 = (Sint32 *) (ptr8);
  /* size of the table in bytes */
  bmp->nbr_data_comp = little_endian_to_int (ptr32++);
  bmp->compress = memory_allocation (bmp->nbr_data_comp * 2);
  if (bmp->compress == NULL)
    {
      return NULL;
    }
  /* 8-bit access */
  ptr8 = (char *) ptr32;
  ptr8 = read_compress (bmp->nbr_data_comp, ptr8, bmp->compress);
  return ptr8;
}
Example #12
0
/**
 * Allocate memory and load a file there
 * @param filename the file which should be loaded
 * @param fsize pointer on the size of file which will be loaded
 * @return file data buffer pointer
 */
char *
load_absolute_file (const char *const filename, Uint32 * const filesize)
{
  size_t fsize;
  FILE *fstream;
  char *buffer;
#ifdef WIN32
  fstream = fopen (filename, "rb");
#else
  fstream = fopen (filename, "r");
#endif
  if (fstream == NULL)
    {
#if defined(_WIN32_WCE)
      LOG_ERR ("can't open file  %s", filename);
#else
      LOG_ERR ("can't open file  %s (%s)", filename, strerror (errno));
#endif
      return NULL;
    }
  fsize = get_file_size (fstream);
  (*filesize) = fsize;
  if (fsize == 0)
    {
      fclose (fstream);
      LOG_ERR ("file %s is empty!", filename);
      return NULL;
    }
  buffer = memory_allocation (fsize);
  if (buffer == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes!",
               filename, (Sint32) fsize);
      fclose (fstream);
      return NULL;
    }
  if (fread (buffer, sizeof (char), fsize, fstream) != fsize)
    {
      free_memory (buffer);
#if defined(_WIN32_WCE)
      LOG_ERR ("can't read file \"%s\"", filename);
#else
      LOG_ERR ("can't read file \"%s\" (%s)", filename, strerror (errno));
#endif
      fclose (fstream);
      return NULL;
    }
  fclose (fstream);
  LOG_DBG ("file \"%s\" was loaded in memory", filename);
  return buffer;
}
Example #13
0
/**
 * Allocates memory and coopies into it the string addressed
 * @param Null-terminated string to duplicate.
 * @return Pointer to a newly allocated copy of the string or NULL 
 */
char *
string_duplicate (register const char *str)
{
  register char *new_str;
  register Uint32 size;
  size = strlen (str) + 1;
  new_str = memory_allocation (size);
  if (new_str == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes", size);
      return NULL;
    }
  memcpy (new_str, str, size);
  return new_str;
}
/*Computation of probabilities*/
static int init_prob(double k,double sigma,double theta,double T,double t0,long Nt)
{ 
  double df;
  int j;
  double beta,alpha1,alpha2;
  
  dt=(T-t0)/(double)Nt;
  dr=sigma*sqrt(3./4.*dt);
  alpha1=(4.*k*theta-SQR(sigma))/8.;
  alpha2=k/2.;
  beta=dr/(2.*dt);
  r_min=(-beta+sqrt(SQR(beta)+4.*alpha1*alpha2))/(2.*alpha2);
  r_max=(beta+sqrt(SQR(beta)+4.*alpha1*alpha2))/(2.*alpha2);

  Ns=(int)ceil((r_max-r_min)/dr);

  memory_allocation(Nt);
  for(j=0;j<=Ns;j++)
    {
      r_vect[j]=r_min+(double)j*dr;
      disc[j]=exp(-SQR(r_vect[j])*dt); 
      df=((4.*k*theta-SQR(sigma))/(8.*r_vect[j])-r_vect[j]*k/2.)*dt/dr;
      
      if(j==0)
	{
	  pu[j]=1./6.+(SQR(df)-df)/2.;
	  pm[j]=df-2.*pu[j];
	  pd[j]=1.-pu[j]-pm[j];
	}
      else if(j==Ns)
	{      
	  pd[j]=1./6.+(SQR(df)+df)/2.;
	  pm[j]=-df-2.*pd[j];
	  pu[j]=1.-pd[j]-pm[j];
	}
      else
	{      
	  pu[j]=1./6.+(SQR(df)+df)/2.;
	  pd[j]=pu[j]-df;
	  pm[j]=1.-pu[j]-pd[j]; 
	}
    }
 
  return OK;
}
Example #15
0
bool
energy_gauge_extract (void)
{
  const char *model = EXPORT_DIR "/gauges/energy_gauge-%01d.png";
  char *filename = memory_allocation (strlen (model) + 1);
  if (filename == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes\n",
               (Uint32) (strlen (model) + 1));
      return FALSE;
    }
  if (!create_dir (EXPORT_DIR "/gauges"))
    {
      free_memory (filename);
      return FALSE;
    }
  free_memory (filename);
  return TRUE;
}
bool
satellite_extract (void)
{
  Uint32 type, frame;
  const char *model =
    EXPORT_DIR "/satellites/satellite-%01d/satellite-%01d.png";
  char *filename = memory_allocation (strlen (model) + 1);
  if (filename == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes\n",
               (Uint32) (strlen (model) + 1));
      return FALSE;
    }
  if (!create_dir (EXPORT_DIR "/satellites"))
    {
      free_memory (filename);
      return FALSE;
    }
  for (type = 0; type < SATELLITES_NUMOF_TYPES; type++)
    {
      sprintf (filename, EXPORT_DIR "/satellites/satellite-%01d", type + 1);
      if (!create_dir (filename))
        {
          free_memory (filename);
          return FALSE;
        }
      for (frame = 0; frame < SATELLITES_NUMOF_IMAGES; frame++)
        {
          sprintf (filename,
                   EXPORT_DIR "/satellites/satellite-%01d/satellite-%01d.png",
                   type + 1, frame);
          if (!image_to_png (&satellites_images[type][frame], filename))
            {
              free_memory (filename);
              return FALSE;
            }
        }
    }
  return TRUE;
}
Example #17
0
bool
bonus_extract (void)
{
  Uint32 type, frame;
  const char *model = EXPORT_DIR "/bonus-gems/bonus-gem-x/bonus-gem-xx.png";
  char *filename = memory_allocation (strlen (model) + 1);
  if (filename == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes\n",
               (Uint32) (strlen (model) + 1));
      return FALSE;
    }
  if (!create_dir (EXPORT_DIR "/bonus-gems"))
    {
      free_memory (filename);
      return FALSE;
    }
  for (type = 0; type < GEM_NUMOF_TYPES; type++)
    {
      sprintf (filename, EXPORT_DIR "/bonus-gems/bonus-gem-%01d", type + 1);
      if (!create_dir (filename))
        {
          free_memory (filename);
          return FALSE;
        }
      for (frame = 0; frame < GEM_NUMOF_IMAGES; frame++)
        {
          sprintf (filename,
                   EXPORT_DIR "/bonus-gems/bonus-gem-%01d/bonus-gem-%02d.png",
                   type + 1, frame);
          if (!image_to_png (&bonus[type][frame], filename))
            {
              free_memory (filename);
              return FALSE;
            }
        }
    }
  free_memory (filename);
  return TRUE;
}
Example #18
0
/**
 * Load data allocate buffers, initialize structure of the starfield 
 * @return TRUE if it completed successfully or FALSE otherwise
 */
bool
starfield_once_init (void)
{
  if (!starfield_load ())
    {
      return FALSE;
    }

  /* allocate starfield data structure */
  if (stars == NULL)
    {
      stars =
        (star_structure *) memory_allocation (NUMOF_STARS *
                                              sizeof (star_structure));
      if (stars == NULL)
        {
          LOG_ERR ("'stars' out of memory");
          return FALSE;
        }
    }
  starfield_init ();
  return TRUE;
}
Example #19
0
bool
starfield_extract (void)
{
  Uint32 type, frame;
  const char *model = EXPORT_DIR "/stars/stars-%01d/star-%01d.png";
  char *filename = memory_allocation (strlen (model) + 1);
  if (filename == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes\n",
               (Uint32) (strlen (model) + 1));
      return FALSE;
    }
  if (!create_dir (EXPORT_DIR "/stars"))
    {
      return FALSE;
    }
  for (type = 0; type < TYPE_OF_STARS; type++)
    {
      sprintf (filename, EXPORT_DIR "/stars/stars-%01d", type + 1);
      if (!create_dir (filename))
        {
          return FALSE;
        }
      for (frame = 0; frame < STAR_NUMOF_IMAGES; frame++)
        {
          sprintf (filename, EXPORT_DIR "/stars/stars-%01d/star-%01d.png",
                   type + 1, frame);
          if (!image_to_png (&star_field[type][frame], filename))
            {
              free_memory (filename);
              return FALSE;
            }
        }
    }
  free_memory (filename);
  return TRUE;
}
Example #20
0
/**
 * Convert a wide-character string to a new character string
 * @param source Pointer to the wide-chars string to be converted  
 * @param length The number of wide-chars in the source string
 * @param code_page The code page used to perform the conversion
 * @return Pointer to the buffer to receive the translated string or
 *         NULL upon failure. This buffer must be released once it is 
 *         not needed anymore
 */
char *
wide_char_to_bytes (wchar_t * source, Uint32 length, Uint32 code_page)
{
  Sint32 size;
  char *dest;
  if (source == NULL)
    {
      return NULL;
    }
  if (length == 0)
    {
      length = wcslen (source) + 1;
    }
  size = WideCharToMultiByte (code_page, 0, source, length,
                              NULL, 0, NULL, NULL);
  if (size == 0)
    {
      LOG_ERR ("WideCharToMultiByte() failed!");
      return NULL;
    }
  dest = memory_allocation (size);
  if (dest == NULL)
    {
      LOG_ERR ("not enough memory to allocate %i bytes", size);
    }
  size = WideCharToMultiByte (code_page, 0, source, length,
                              dest, size, NULL, NULL);
  if (size == 0)
    {
      LOG_ERR ("WideCharToMultiByte() failed!");
      free_memory (dest);
      return NULL;
    }
  dest[size] = 0;
  return dest;
}
Example #21
0
/**
 * Allocate and precalculate sinus and cosinus curves 
 * @return TRUE if it completed successfully or FALSE otherwise
 */
bool
alloc_precalulate_sinus (void)
{
  Uint32 i;
  double a, step, pi;

  if (precalc_sin128 == NULL)
    {
      i = 128 * sizeof (float) * 2;
      precalc_sin128 = (float *) memory_allocation (i);
      if (precalc_sin128 == NULL)
        {
          LOG_ERR ("not enough memory to allocate %i bytes", i);
          return FALSE;
        }
      precalc_cos128 = precalc_sin128 + 128;
    }
  pi = 4 * atan (1.0);
  a = 0.0;
  step = (pi * 2) / 128;
  for (i = 0; i < 128; i++)
    {
      precalc_sin128[i] = (float) sin (a);
      precalc_cos128[i] = (float) cos (a);
      a += step;
    }
  if (precalc_sin == NULL)
    {
      i = 32 * sizeof (float) * 2;
      precalc_sin = (float *) memory_allocation (i);
      if (precalc_sin == NULL)
        {
          LOG_ERR ("not enough memory to allocate %i bytes", i);
          return FALSE;
        }
      precalc_cos = precalc_sin + 32;
    }

  step = (pi * 2) / 32;
  a = 0.0;
  for (i = 0; i < 32; i++)
    {
      precalc_sin[i] = (float) sin (a);
      precalc_cos[i] = (float) cos (a);
      a += step;
    }
  /* table user for guided missile */
  for (i = 0; i < 32; i++)
    {
      depix[0][i] = precalc_cos[i] * 0.5f;
      depix[1][i] = precalc_cos[i] * 1.0f;
      depix[2][i] = precalc_cos[i] * 1.5f;
      depix[3][i] = precalc_cos[i] * 2.0f;
      depix[4][i] = precalc_cos[i] * 2.5f;
      depix[5][i] = precalc_cos[i] * 3.0f;
      depix[6][i] = precalc_cos[i] * 3.5f;
      depix[7][i] = precalc_cos[i] * 4.0f;
      depix[8][i] = precalc_cos[i] * 4.5f;
      depix[9][i] = precalc_cos[i] * 5.0f;
      depix[10][i] = precalc_cos[i] * 5.5f;
      depix[11][i] = precalc_cos[i] * 6.0f;
      depix[12][i] = precalc_cos[i] * 6.5f;
      depiy[0][i] = precalc_sin[i] * 0.5f;
      depiy[1][i] = precalc_sin[i] * 1.0f;
      depiy[2][i] = precalc_sin[i] * 1.5f;
      depiy[3][i] = precalc_sin[i] * 2.0f;
      depiy[4][i] = precalc_sin[i] * 2.5f;
      depiy[5][i] = precalc_sin[i] * 3.0f;
      depiy[6][i] = precalc_sin[i] * 3.5f;
      depiy[7][i] = precalc_sin[i] * 4.0f;
      depiy[8][i] = precalc_sin[i] * 4.5f;
      depiy[9][i] = precalc_sin[i] * 5.0f;
      depiy[10][i] = precalc_sin[i] * 5.5f;
      depiy[11][i] = precalc_sin[i] * 6.0f;
      depiy[12][i] = precalc_sin[i] * 6.5f;
    }
  return TRUE;
}
Example #22
0
/**
 * Convert from sprite filedata to 'image' stucture 
 * Values from filedata are stored in little-endian
 * - x-coordinate, y-coordinate, width and height of the sprite
 * - List of the collision coordinates
 * - list of the collisions areas coordinates and areas sizes (width/height)
 * - list of the cannons coordinates and shots angles
 * - list of the pixels of the sprite without the transparent pixels (0 value)
 * - list of offsets and repeats values (compress table) for displaying sprite
 *
 * @param img Pointer to destination 'image' structure 
 * @param file Pointer to source sprite filedata
 * @return Pointer to the end of source sprite filedata
 */
static char *
image_extract (image * img, const char *file)
{
  Uint32 i;
  Sint16 *dest;
  /* pointer to the file (8/16/32-bit access */
  char *ptr8;
  Sint16 *ptr16;
  Sint32 *ptr32;

  /* 
   * read coordinates and size of the sprite 
   */
  /* 16-bit access */
  ptr16 = (Sint16 *) file;
  /* x and y coordinates of the centre of gravity  */
  img->x_gc = little_endian_to_short (ptr16++);
  img->y_gc = little_endian_to_short (ptr16++);
  /* image width and height */
  img->w = little_endian_to_short (ptr16++);
  img->h = little_endian_to_short (ptr16++);

  /* 
   * read zones and points of collision
   */
  /* number of points of collision */
  img->numof_collisions_points = little_endian_to_short (ptr16++);
  dest = &img->collisions_points[0][0];
  for (i = 0; i < MAX_OF_COLLISION_POINTS * 2; i++)
    {
      *(dest++) = little_endian_to_short (ptr16++);
    }
  /* number of zones of collision */
  img->numof_collisions_zones = little_endian_to_short (ptr16++);
  dest = &img->collisions_coords[0][0];
  for (i = 0; i < MAX_OF_COLLISION_ZONES * 2; i++)
    {
      *(dest++) = little_endian_to_short (ptr16++);
    }
  dest = &img->collisions_sizes[0][0];
  for (i = 0; i < MAX_OF_COLLISION_ZONES * 2; i++)
    {
      *(dest++) = little_endian_to_short (ptr16++);
    }

  /* 
   * read origins of shots (location of the cannons) and angle shots 
   */
  /* number of cannons */
  img->numof_cannons = little_endian_to_short (ptr16++);
  dest = &img->cannons_coords[0][0];
  for (i = 0; i < MAX_OF_CANNONS * 2; i++)
    {
      *(dest++) = little_endian_to_short (ptr16++);
    }
  for (i = 0; i < MAX_OF_CANNONS; i++)
    {
      img->cannons_angles[i] = little_endian_to_short (ptr16++);
    }

  /*
   * read the pixel data (8 bits per pixel)
   */
  /* 32-bit access */
  ptr32 = (Sint32 *) (ptr16);
  /* number of pixels */
  img->numof_pixels = little_endian_to_int (ptr32++);
  img->img = memory_allocation (img->numof_pixels * bytes_per_pixel);
  if (img->img == NULL)
    {
      return NULL;
    }
  /* 8-bit access */
  ptr8 = (char *) ptr32;
  ptr8 = read_pixels (img->numof_pixels, ptr8, img->img);

  /* 
   * read offsets and repeat values 
   */
  /* 32-bit access */
  ptr32 = (Sint32 *) (ptr8);
  /* size of the table in bytes */
  img->nbr_data_comp = little_endian_to_int (ptr32++);
  img->compress = memory_allocation (img->nbr_data_comp * 2);
  if (img->compress == NULL)
    {
      return NULL;
    }
  /* 8-bit access */
  ptr8 = (char *) ptr32;
  ptr8 = read_compress (img->nbr_data_comp, ptr8, img->compress);
  return ptr8;
}
Example #23
0
/**
 * Save the counter file
 * @return
 */
static bool
counter_save_file (void)
{
  Uint32 n, nb, chk, pos;
  DWORD size;
  char *buffer = 0;
  Uint32 *pint = 0;
  HKEY hk;
  Uint32 regerr;
  size = 4 * 3;
  for (n = 0; n < num_of_games; n++)
    {
      size += 4 * 4 + strlen (GameCount[n].name) + 1;
    }
  buffer = (char *) memory_allocation (size + 1);
  if (buffer == NULL)
    {
      return FALSE;
    }
  /* 0 = checksum */
  pos = 4;
  /* file version number */
  pint = (Uint32 *) (buffer + pos);
  *pint = 2;
  pos += 4;
  /* number games */
  pint = (Uint32 *) (buffer + pos);
  *pint = num_of_games;
  pos += 4;
  for (n = 0; n < num_of_games; n++)
    {
      pint = (Uint32 *) (buffer + pos);
      *pint = GameCount[n].count;
      pos += 4;
      pint = (Uint32 *) (buffer + pos);
      *pint = GameCount[n].time;
      pos += 4;
      pint = (Uint32 *) (buffer + pos);
      *pint = GameCount[n].version;
      pos += 4;
      nb = strlen (GameCount[n].name) + 1;
      pint = (Uint32 *) (buffer + pos);
      *pint = nb;
      pos += 4;
      memcpy (buffer + pos, GameCount[n].name, nb);
      pos += nb;
    }
  /* crypt the buffer */
  counter_crypt (buffer, size, buffer, (char *) Codecounter_cryptage);
  /* generate checksum */
  chk = 0;
  for (n = 4; n < size; n++)
    {
      chk += (unsigned char) buffer[n];
    }
  pint = (Uint32 *) buffer;
  *pint = chk;
  DWORD regcm;
  regerr = RegCreateKeyEx (HKEY_CURRENT_USER,
                           "Software\\TLK Games\\Data",
                           0,
                           0,
                           REG_OPTION_NON_VOLATILE,
                           KEY_WRITE, 0, &hk, &regcm);
  if (regerr == ERROR_SUCCESS)
    {
      regerr = RegSetValueEx (hk,
                              "Count", 0, REG_BINARY, (LPBYTE) buffer, size);
      if (regerr != ERROR_SUCCESS)
        {
          free_memory (buffer);
          return FALSE;
        }
    }
  else
    {
      free_memory (buffer);
      return FALSE;
    }
  if (buffer != NULL)
    {
      free_memory (buffer);
    }
  return TRUE;
}
Example #24
0
/**
 * Load games list in the counter file
 * @return TRUE if it completed successfully or FALSE otherwise
 */
static bool
counter_load_file (void)
{
  Sint32 ver;
  Uint32 n, nb, chk, pos;
  DWORD size;
  char *buffer = NULL;
  HKEY hk;
  Uint32 regerr;
  size = 0;
  regerr = RegOpenKeyEx (HKEY_CURRENT_USER,
                         "Software\\TLK Games\\Data",
                         0, KEY_QUERY_VALUE, &hk);
  if (regerr == ERROR_SUCCESS)
    {
      DWORD regtype = REG_BINARY;
      regerr = RegQueryValueEx (hk,
                                "Count",
                                NULL, &regtype, (LPBYTE) buffer, &size);
      buffer = (char *) memory_allocation (size + 1);
      if (NULL == buffer)
        {
          return FALSE;
        }
      regerr = RegQueryValueEx (hk,
                                "Count", 0, &regtype, (LPBYTE) buffer, &size);

      if (regerr != ERROR_SUCCESS)
        {
          RegCloseKey (hk);
          free_memory (buffer);
          return FALSE;
        }
      RegCloseKey (hk);
    }
  else
    {
      return FALSE;
    }


  /* checksum */
  chk = 0;
  for (n = 4; n < size; n++)
    {
      chk += (unsigned char) buffer[n];
    }
  if (size > 0)
    {
      n = *((Uint32 *) buffer);
    }
  else
    {
      n = 1;
    }
  if (n != chk)
    {
      /* bad checksum: delete file! */
      regerr = RegOpenKeyEx (HKEY_CURRENT_USER,
                             "Software\\TLK Games\\Data", 0, KEY_WRITE, &hk);
      if (regerr == ERROR_SUCCESS)
        {
          regerr = RegDeleteKey (hk, "Count");
        }
      RegCloseKey (hk);
      free_memory (buffer);
      return FALSE;
    }
  /* uncrypt the buffer */
  counter_uncrypt (buffer, size, buffer, (char *) Codecounter_cryptage);
  pos = 4;
  /* version */
  ver = *((Uint32 *) (buffer + pos));
  pos += 4;
  /* number of input */
  nb = *((Uint32 *) (buffer + pos));
  pos += 4;
  num_of_games = nb;
  GameCount =
    (TLKGameInfo *) memory_allocation (sizeof (TLKGameInfo) *
                                       (num_of_games + 1));
  if (GameCount == NULL)
    {
      return FALSE;
    }
  for (n = 0; n < num_of_games; n++)
    {
      GameCount[n].count = *((Uint32 *) (buffer + pos));
      pos += 4;
      GameCount[n].time = *((Uint32 *) (buffer + pos));
      pos += 4;
      GameCount[n].version = *((Uint32 *) (buffer + pos));
      pos += 4;
      nb = *((Uint32 *) (buffer + pos));
      pos += 4;
      memcpy (GameCount[n].name, buffer + pos, nb);
      pos += nb;
    }
  if (buffer != NULL)
    {
      free_memory (buffer);
    }
  return TRUE;
}
Example #25
0
/**
 * Copy a image structure into a buffer
 * @param width Height of the sprite in pixels 
 * @param height Width of the sprite in pixels
 * @param source Buffer containing 256 color pixels of the sprite
 * @param repeats Buffer containing values of offset and the number of
 *                contiguous pixels to be copied.
 * @param size_counter Size of 'repeats' buffer
 * @param size_of_line The width of the offscreen of the game.
 *                     Always 512 pixels.
 * @return A pointer to the buffer
 */
static char *
image_to_buffer_32_bit (Uint32 width, Uint32 height, unsigned char *source,
                        char *repeats, Uint32 size_counter,
                        Uint32 size_of_line)
{
  _compress *t;
  register Uint32 offset;
#if __WORDSIZE == 64
  Uint64 real_size;
#else
  Uint32 real_size;
#endif
  unsigned char *buffer, *p, *pal, pixel;
  Uint32 buffer_size, modulo_line;
  Uint32 line_jumps;
  Uint16 count, i;
  if (width < 1 || height < 1 || width > size_of_line
      || height > size_of_line)
    {
      LOG_ERR ("(!) size of image: %ix%i", width, height);
      return NULL;
    }

  /* allocate the destination buffer that will contain the 32-bit bitmap */
  buffer_size = width * height * 4;
  buffer = (unsigned char *) memory_allocation (buffer_size);
  if (buffer == NULL)
    {
      return NULL;
    }
  size_counter = size_counter >> 2;
  width = width;
  p = (unsigned char *) buffer;
  count = 0;
  t = (_compress *) repeats;
  do
    {
      offset = t->offset;
      if (offset >= size_of_line)
        {
          line_jumps = offset / size_of_line;
          modulo_line = offset % size_of_line;
          offset =
            (offset - line_jumps * size_of_line) + (line_jumps * width);
          if (modulo_line > width)
            {
              offset = offset - size_of_line + width;
            }
        }
      else
        {
          if (offset >= width)
            {
              offset = offset - size_of_line + width;
            }
        }
      /* offset destination */
      p = p + offset * 4;
      /* num of 32 words to copy */
      count = t->r1;
      for (i = 0; i < count * 4; i++)
        {
          pixel = *(source++);
          pal = &palette_24[pixel * 3];
#if __WORDSIZE == 64
          real_size = ((Uint64) (p + 3) - (Uint64) buffer);
#else
          real_size = ((Uint32) (p + 3) - (Uint32) buffer);
#endif
          if (real_size > buffer_size)
            {
              LOG_ERR ("1) count = %i", count);
              p += 3;
              continue;
            }
          *(p++) = pal[0];
          *(p++) = pal[1];
          *(p++) = pal[2];
          if (pal[0] < 64 && pal[1] < 64 && pal[2] < 64)
            {
              *(p++) = 255;
            }
          else
            {
              *(p++) = 255;
            }
        }
      /* 8 bits data */
      count = t->r2;
      for (i = 0; i < count; i++)
        {
          pixel = *(source++);
          pal = &palette_24[pixel * 3];
#if __WORDSIZE == 64
          real_size = ((Uint64) (p + 3) - (Uint64) buffer);
#else
          real_size = ((Uint32) (p + 3) - (Uint32) buffer);
#endif
          if (real_size > buffer_size)
            {
              LOG_ERR ("2) count = %i", count);
              p += 3;
              continue;
            }
          *(p++) = pal[0];
          *(p++) = pal[1];
          *(p++) = pal[2];
          if (pal[0] < 64 && pal[1] < 64 && pal[2] < 64)
            {
              *(p++) = 255;
            }
          else
            {
              *(p++) = 255;
            }
        }
      t++;
      size_counter--;
    }
  while (size_counter > 0);
#if __WORDSIZE == 64
  real_size = ((Uint64) p - (Uint64) buffer);
#else
  real_size = ((Uint32) p - (Uint32) buffer);
#endif
  if (real_size > buffer_size)
    {
      LOG_ERR ("%i is greater than %i (%ix%i)",
               (Sint32) real_size, buffer_size, width, height);
    }
  LOG_DBG ("width: %i, height: %i, real_size: %i, buffer_size: %i", width,
           height, real_size, buffer_size);
  return (char *) buffer;
}
Example #26
0
int main(int argc, char **argv)
{
  init_rand();
  setup_gsl_dgen();

  dgen_parse_cmdline(argc, argv);

  int i, j, h, p, k, c;
  
  int cons_cap, num_cons = -1, root_cap, num_root = -1;
  char **cons_seqs, **root_seqs;

  int internal_node_index = 0, leaf_node_index = M;
  int max_internal_node_index = 2000000;
  int max_leaf_node_index = 2000000;
  int sum_seen_or_unseen = 0;

  int ploidy, codon_sequence_length = -1, n_genes, total_n_HLA;
  Decimal mu;

  if(json_parameters_path == NULL) die("No .json file passed.");

  load_lengths_for_simulation_from_json(json_parameters_path, &kappa, &mu,
                                        &codon_sequence_length, &total_n_HLA, &ploidy, &n_genes);

  if(ploidy < 1) die("Ploidy is less than 1.");
  if(n_genes < 1) die("Number of genes is less than 1.");
  
  if(cons_path != NULL) {
    printf("Loading sequences to obtain consensus...\n");
    num_cons = load_seqs(cons_path, &cons_seqs, &cons_cap);
    assert(num_cons > 0);
    printf("Loaded %i sequences to determine consensus.\n", num_cons);
    
    codon_sequence_length = strlen(cons_seqs[0]);
    printf("Codon_sequence_length: %i\n",codon_sequence_length/3);
    
    if(codon_sequence_length % 3 != 0)
      die("Sequences contain partial codons [%i mod 3 != 0].", codon_sequence_length);

    for(c = 0; c < num_cons; c++) {
      if((int) strlen(cons_seqs[c]) != codon_sequence_length) {
        die("Sequences from which to derive the consensus sequence aren't all "
            "the same length.");
      }
    }
    codon_sequence_length = codon_sequence_length/3;
  }

  if(root_path != NULL) {
    printf("Loading sequences to obtain root...\n");
    num_root = load_seqs(root_path, &root_seqs, &root_cap);
    printf("Loaded %i sequences to determine root.\n", num_root);
    
    if(cons_path == NULL)
      die("Did not pass a file to find the consensus sequence.");
    
    if((int) (strlen(root_seqs[0])/3) != codon_sequence_length)
      die("Sequences used to determine the root are different lengths to those used for the consensus.");

    for(c = 0; c < num_root; c++) {
      if((int) strlen(root_seqs[c]) != 3*codon_sequence_length) {
        die("Sequences from which to derive the root sequence aren't all "
            "the same length.");
      }
    }
  }

  Decimal *internal_node_times = my_malloc(max_internal_node_index * sizeof(Decimal) , __FILE__, __LINE__);
  Decimal *leaf_node_times = my_malloc(max_leaf_node_index * sizeof(Decimal), __FILE__, __LINE__);
  int *seen_or_unseen = my_malloc(max_internal_node_index * sizeof(int), __FILE__, __LINE__);

  birth_death_simulation_backwards(max_internal_node_index, max_leaf_node_index,
                                   internal_node_times, 
                                   leaf_node_times,
                                   &internal_node_index, &leaf_node_index,
                                   seen_or_unseen,
                                   N, M, lambda, mu_tree, past_sampling);

  for(i = 0; i < internal_node_index; i++) sum_seen_or_unseen += seen_or_unseen[i];
  
  int total_nodes = (2 * leaf_node_index) - 1 + internal_node_index - sum_seen_or_unseen;
  Tree *tree = my_malloc((total_nodes+1) * sizeof(Tree), __FILE__, __LINE__);
  // Now malloc the memory that this points to.
  int *HLAs_in_tree = my_malloc((total_nodes+1) * ploidy * n_genes * sizeof(int), __FILE__, __LINE__);

  for(i = 0; i < total_nodes; i++) 
    tree[i].HLAs = &HLAs_in_tree[i * ploidy * n_genes];

  construct_birth_death_tree(leaf_node_index, internal_node_index,
                             leaf_node_times, internal_node_times,
                             M, seen_or_unseen,
                             tree);

  // Reverse the direction that time is measured in the tree.
  // DEV: Don't need to do this, waste of computation - sort.
  // DEV: The parent times are wrong when there are unseen nodes.
  for(i = 0; i < total_nodes; i++)
    tree[i].node_time = tree[total_nodes-1].node_time - tree[i].node_time;
   
  int root_node = tree[total_nodes-1].node;
  
  if(write_newick_tree_to_file == true) {
    write_newick_tree(newick_tree_data_file, tree, root_node, 1);
    fclose(newick_tree_data_file);
  }

  Decimal S_portion[NUM_CODONS];
  Decimal NS_portion[NUM_CODONS];

  for(c = 0; c < NUM_CODONS; c++) {
    S_portion[c] = kappa * beta_S[c] + beta_V[c];
    NS_portion[c] = kappa * alpha_S[c] + alpha_V[c];
  }
  
  int n_HLA[n_genes];

  printf("Total number of HLA types: %i.\n", total_n_HLA);

  Decimal HLA_prevalences[total_n_HLA];
  int wildtype_sequence[codon_sequence_length];
  Decimal *R = my_malloc(codon_sequence_length * sizeof(Decimal), __FILE__, __LINE__);
  Decimal *omega = my_malloc(codon_sequence_length * sizeof(Decimal), __FILE__, __LINE__);
  Decimal *reversion_selection = my_malloc(codon_sequence_length * sizeof(Decimal), __FILE__, __LINE__);

  memory_allocation(num_cons, num_root, codon_sequence_length,
                    max_internal_node_index, max_leaf_node_index, 
                    total_nodes, ploidy, n_genes, total_n_HLA,
                    leaf_node_index);

  int (*codon_sequence_matrix)[codon_sequence_length] = my_malloc(total_nodes *
                                                                  sizeof(int[codon_sequence_length]),
                                                                  __FILE__, __LINE__);
  Decimal (*HLA_selection_profiles)[codon_sequence_length] = my_malloc(total_n_HLA * sizeof(Decimal[codon_sequence_length]),
                                                                       __FILE__, __LINE__);

  load_parameters_for_simulation_from_json(json_parameters_path, codon_sequence_length,
                                           omega, R, reversion_selection, total_n_HLA,
                                           n_genes, n_HLA, HLA_prevalences,
                                           HLA_selection_profiles);
  
  Decimal sum_check;
  for(i = 0, k = 0; i < n_genes; i++) {
    sum_check = 0;
    for(h = 0; h < n_HLA[i]; h++, k++) {
      sum_check += HLA_prevalences[k];
    }
    if(sum_check > 1.00001 || sum_check < 0.9999) die("HLA prevalences for gene %i do not sum to 1\n", i+1);
  }
  
  if(cons_path != NULL) {
    printf("Mapping gaps to consensus...\n");
    // Set the consensus sequence - the consensus of the optional sequence file 
    // that is passed.
    char wildtype_sequence_dummy[3*codon_sequence_length+1];
    generate_consensus(cons_seqs, num_cons, 3*codon_sequence_length, wildtype_sequence_dummy);
    printf("Wildtype sequence:\n%s\n", wildtype_sequence_dummy);
    // By default, set the root as the wildtype sequence.
    for(i = 0; i < codon_sequence_length; i++)
      wildtype_sequence[i] = (int) amino_to_code(wildtype_sequence_dummy+i*3);

    if(root_path == NULL) {
      for(i = 0; i < codon_sequence_length; i++)
        codon_sequence_matrix[root_node][i] = wildtype_sequence[i];
    } else {
      printf("Mapping gaps to root...\n");
      char root_sequence_dummy[3*codon_sequence_length+1];
      generate_consensus(root_seqs, num_root, 3*codon_sequence_length, root_sequence_dummy);
      printf("Root sequence:\n%s\n", root_sequence_dummy);
      
      for(i = 0; i < codon_sequence_length; i++)
        codon_sequence_matrix[root_node][i] = (int) amino_to_code(root_sequence_dummy+i*3);
      printf("Number of root sequences: %i.\n", num_root);
      for(c = 0; c < num_root; c++) free(root_seqs[c]);
      free(root_seqs);
    }
    printf("Number of consensus sequences: %i.\n", num_cons);
    for(c = 0; c < num_cons; c++) free(cons_seqs[c]);
    free(cons_seqs);
  
  } else {
    for(i = 0; i < codon_sequence_length; i++) {
      // Sample the root sequence according to the HIV codon usage information.
      codon_sequence_matrix[root_node][i] = discrete_sampling_dist(NUM_CODONS, prior_C1);
      // As default, set the root node to the consensus sequence.  
      wildtype_sequence[i] = codon_sequence_matrix[root_node][i];
    }
  }
  
  // No matter what is read in, there is no recombination simulated - so make sure it's set to 0.
  for(i = 0; i < codon_sequence_length; i++) R[i] = 0;

  write_summary_json(json_summary_file,
                     mu, codon_sequence_length, ploidy,
                     n_genes, n_HLA, total_n_HLA,
                     HLA_prevalences,
                     omega, R, reversion_selection,
                     HLA_selection_profiles);

  free(R);
  
  fprintf(simulated_root_file, ">root_sequence\n");
  for(i = 0; i < codon_sequence_length; i++)
    fprintf(simulated_root_file, "%s", code_to_char(codon_sequence_matrix[root_node][i]));
  fprintf(simulated_root_file, "\n");

  int root_HLA[ploidy * n_genes];
  int cumulative_n_HLA = 0;

  for(i = 0, k = 0; i < n_genes; i++) {
    for(p = 0; p < ploidy; p++, k++) {
      root_HLA[k] = cumulative_n_HLA + 
                    discrete_sampling_dist(n_HLA[i], &HLA_prevalences[cumulative_n_HLA]);
      tree[root_node].HLAs[k] = root_HLA[k];
    }
    cumulative_n_HLA = cumulative_n_HLA + n_HLA[i];
  }

  printf("Passing HLA information...\n");
  pass_HLA(ploidy, n_genes, root_node,
                           tree, leaf_node_index, total_n_HLA,
                           n_HLA, HLA_prevalences);
  printf("Passed HLA information\n");
  
  // printf("Printing the tree\n");
  // for(i = 0; i < total_nodes; i++) {
  //   printf("%i %i %i "DECPRINT" %i", tree[i].node, tree[i].daughter_nodes[0],
  //          tree[i].daughter_nodes[1], tree[i].node_time,
  //          tree[i].seen_or_unseen);
  //   for(j = 0; j < (ploidy * n_genes); j++) {
  //     printf(" %i", tree[i].HLAs[j]);
  //   }
  //   printf("\n");
  // }

  if(write_tree_to_file == true) {
    write_tree(tree_data_file, tree, root_node, ploidy, n_genes);
    fclose(tree_data_file);
  }

  printf("Passing sequence information...\n");
  
  pass_codon_sequence_change(codon_sequence_length, ploidy,
                             n_genes, total_n_HLA, 
                             root_node, mu,
                             codon_sequence_matrix,
                             tree,
                             leaf_node_index,
                             S_portion, NS_portion,
                             HLA_selection_profiles,
                             wildtype_sequence,
                             omega, reversion_selection);

  printf("Passed sequence information\n"
         "Now generating .fasta files of reference and query sequences, and\n"
         "a .csv file of the HLA information associated to the query sequences.\n");

  if(num_queries < 0) {
    // Set the number of query sequences.
    num_queries = (int) (query_fraction * leaf_node_index);
    printf("Number of queries: %i.\n", num_queries);
  } else {
    printf("Number of queries: %i.\n", num_queries);
  }

  if(num_queries > leaf_node_index) die("Number of query sequences larger than the number of leaves");
  int *all_sequences = my_malloc(leaf_node_index * sizeof(int), __FILE__, __LINE__);
  int num_refs = leaf_node_index - num_queries;

  for(i = 0; i < leaf_node_index; i++) all_sequences[i] = i;

  save_simulated_ref_and_query_fasta(num_queries, num_refs, leaf_node_index,
                                     all_sequences, codon_sequence_length, codon_sequence_matrix,
                                     tree, ploidy, n_genes);

  // Now save the hla types to a .csv file.
  fprintf(hla_query_file, "\"\",");
  for(h = 0; h < total_n_HLA-1; h++) fprintf(hla_query_file, "\"%i\",", h+1);
  fprintf(hla_query_file, "\"%i\"\n", total_n_HLA);
  
  // Write the HLA types of the leaves to a file.
  int (*hla_types)[total_n_HLA] = my_malloc(leaf_node_index * sizeof(int[total_n_HLA]), __FILE__, __LINE__);

  for(i = 0; i < leaf_node_index; i++)
  {
    for(h = 0; h < total_n_HLA; h++)
      hla_types[i][h] = 0;
    for(j = 0; j < (n_genes * ploidy); j++)
      hla_types[i][tree[i].HLAs[j]] = 1;
  }

  // Write the query HLA types to a .csv file.
  for(i = num_refs; i < leaf_node_index; i++)
  {
    fprintf(hla_query_file,"\"simulated_seq_%i_HLA", all_sequences[i]+1);
    for(h = 0; h < (ploidy * n_genes); h++) fprintf(hla_query_file, "_%i", tree[all_sequences[i]].HLAs[h]);
    fprintf(hla_query_file, "\"");
    for(h = 0; h < total_n_HLA; h++) {
      fprintf(hla_query_file, ",%i", hla_types[all_sequences[i]][h]);
    }
    fprintf(hla_query_file, "\n");
  }

  free(hla_types); 
  free(internal_node_times);
  free(leaf_node_times);
  free(seen_or_unseen);
  free(codon_sequence_matrix);
  free(HLA_selection_profiles);
  free(all_sequences);
  free(omega);
  free(reversion_selection);

  free(tree[0].HLAs);
  free(tree);

  fclose(summary_file);
  fclose(json_summary_file);
  fclose(simulated_refs_file);
  fclose(simulated_root_file);
  fclose(simulated_queries_file);
  fclose(hla_query_file);

  clearup_gsl_dgen();
  return EXIT_SUCCESS;
}
int main()
{
	/*Option parameters*/
	double tt = 1;
	double H = 90.0;
	double K = 100.0;
	double r_premia = 10;
	double spot = 95.0;
	double spot_step = 5;
	uint spot_iterations = 21;

	/*Heston model parameters*/
	double v0 = 0.1; /* initial volatility */
	double kappa = 2.0; /*heston parameter, mean reversion*/
	double theta = 0.2; /*heston parameter, long-run variance*/
	double sigma = 0.2; /*heston parameter, volatility of variance*/
	double omega = sigma; /*sigma is used everywhere, omega - in the variance tree*/
	double rho = 0.5; /*heston parameter, correlation*/

	/*method parameters*/
	uint Nt = 100; /*number of time steps*/
	uint M = uint(pow(2, 12)); /*space grid. should be a power of 2*/
	double L = 3; /*scaling coefficient*/

	int allocation = memory_allocation(Nt, M, M);
	if (allocation == MEMORY_ALLOCATION_FAILURE)
	{
		return MEMORY_ALLOCATION_FAILURE;
	}
	else
	{
		double start_time = clock() / double(CLOCKS_PER_SEC);
		compute_price(tt, H, K, r_premia, v0, kappa, theta, sigma, rho, L, M, Nt);
		double end_time = clock() / double(CLOCKS_PER_SEC);
		for (int j = find_nearest_right_price_position(1.5*K,M); j >= find_nearest_left_price_position(H, M); j--)
		{
			printf("ba_price %f Price %f + %f i\n", ba_prices[j], F_next[j][0].r, F_next[j][0].i);
		}
		for (uint i = 0; i < spot_iterations; i++)
		{
			printf("interp ba_price %f Price %f\n", spot + i*spot_step, quadratic_interpolation(spot + i*spot_step, M));
		}
		printf("Time elapsed (in sedonds): %f\n", end_time - start_time);

		free_memory(Nt, M, M);
		getchar();
		return OK;
	}
	/*
	double mc_price = 0;
	int trajectories = 100000;
	for (int trajectory = 0; trajectory < trajectories; trajectory++)
	{
		if(trajectory % 1000 == 0)
			printf("trajectories left:  %d \n", trajectories - trajectory);
		mc_price += generate_heston_trajectory_return(tt, spot, H, K, r_premia, v0, kappa, theta, sigma, rho, 10000);
	}
	mc_price = mc_price / double(trajectories);
	printf("avg_price %f", mc_price);
	getchar();*/
}
Example #28
0
/**
 * Allocate buffers and precalcule the rings
 * @return TRUE if it completed successfully or 0 otherwise
 */
bool
shockwave_once_init (void)
{
    double a, step, pi;
    Sint32 i, j, n, r;
    Sint16 x, y;


    /* allocate shockwaves data structure */
    if (shockwave == NULL)
    {
        shockwave =
            (shockwave_struct *) memory_allocation (MAX_NUMOF_SHOCKWAVES *
                    sizeof (shockwave_struct));
        if (shockwave == NULL)
        {
            LOG_ERR ("shockwave out of memory");
            return FALSE;
        }
    }
    if (shockwave_right_buffer == NULL)
    {
        shockwave_right_buffer =
            (Sint32 *) memory_allocation (offscreen_height * sizeof (Sint32));
        if (shockwave_right_buffer == NULL)
        {
            LOG_ERR ("shockwave_right_buffer out of memory");
            return FALSE;
        }

    }
    if (shockwave_left_buffer == NULL)
    {
        shockwave_left_buffer =
            (Sint32 *) memory_allocation (offscreen_height * sizeof (Sint32));
        if (shockwave_left_buffer == NULL)
        {
            LOG_ERR ("shockwave_left_buffer out of memory");
            return FALSE;
        }

    }

    if (shockwave_ring_x == NULL)
    {
        shockwave_ring_x =
            (Sint16 *) memory_allocation (NUMOF_RINGS_SHOCKWAVE *
                                          NUMOF_POINTS_SHOCKWAVE * 2 *
                                          sizeof (Sint16));
        if (shockwave_ring_x == NULL)
        {
            LOG_ERR ("'shockwave_ring_x' out of memory");
            return FALSE;
        }
        shockwave_ring_y =
            shockwave_ring_x + NUMOF_RINGS_SHOCKWAVE * NUMOF_POINTS_SHOCKWAVE;
    }

    /* set colors of the shockwaves */
    shockwave_colors[0] = search_color (255, 255, 0);
    shockwave_colors[1] = search_color (248, 248, 0);
    shockwave_colors[2] = search_color (241, 241, 0);
    shockwave_colors[3] = search_color (234, 234, 0);
    shockwave_colors[4] = search_color (227, 227, 0);
    shockwave_colors[5] = search_color (220, 220, 0);
    shockwave_colors[6] = search_color (213, 213, 0);
    shockwave_colors[7] = search_color (206, 206, 0);
    shockwave_colors[8] = search_color (199, 199, 0);
    shockwave_colors[9] = search_color (192, 192, 0);
    shockwave_colors[10] = search_color (185, 185, 0);
    shockwave_colors[11] = search_color (178, 178, 0);
    shockwave_colors[12] = search_color (171, 171, 0);
    shockwave_colors[13] = search_color (164, 164, 0);
    shockwave_colors[14] = search_color (157, 157, 0);
    shockwave_colors[15] = search_color (150, 150, 0);
    shockwave_colors[16] = search_color (143, 143, 0);
    shockwave_colors[17] = search_color (136, 136, 0);
    shockwave_colors[18] = search_color (129, 129, 0);
    shockwave_colors[19] = search_color (122, 122, 0);
    shockwave_colors[20] = search_color (115, 115, 0);
    shockwave_colors[21] = search_color (108, 108, 0);
    shockwave_colors[22] = search_color (101, 101, 0);
    shockwave_colors[23] = search_color (94, 94, 0);
    shockwave_colors[24] = search_color (87, 87, 0);

    /*
     * precalculate the 55 rings (rings are circles)
     */
    n = NUMOF_POINTS_SHOCKWAVE;
    pi = 4 * atan (1.0);
    /* ring radius: 30 to 300 pixels */
    r = 30 * pixel_size;
    step = (pi * 2) / (NUMOF_POINTS_SHOCKWAVE - 1);
    for (i = 0; i < NUMOF_RINGS_SHOCKWAVE; i++, r += 5)
    {
        /* clear angle value */
        a = 0.0;
        for (j = 0; j < (NUMOF_POINTS_SHOCKWAVE - 1); j++)
        {
            x = (Sint16) (cos (a) * r);
            y = (Sint16) (sin (a) * r);
            a = a + step;
            shockwave_ring_x[i * n + j] = x;
            shockwave_ring_y[i * n + j] = y;
        }
        /* the first and last point are equal to get a closer ring */
        shockwave_ring_x[i * n + j] = shockwave_ring_x[i * n];
        shockwave_ring_y[i * n + j] = shockwave_ring_y[i * n];
    }
    shockwave_init ();
    return TRUE;
}
Example #29
0
/**
 * Load and decompress a PCX file
 * @param filename Filename specified by path
 * @return Pointer to a bitmap_desc structure or null if an error occurred 
 */
bitmap_desc *
load_pcx (const char *filename)
{
  Uint32 width, height, depth, size, ptr;
  Uint16 *ptr16;
  unsigned char numof_bytes;
  unsigned char val;
  Uint32 i, j, total;
  unsigned char *filedata, *pixel;
  bitmap_desc *bmp;
  filedata = (unsigned char *) loadfile (filename, &size);
  if (filedata == NULL)
    {
      return NULL;
    }
  ptr16 = (Uint16 *) filedata;
  width = (little_endian_to_ushort (ptr16 + 4)
           - little_endian_to_ushort (ptr16 + 2)) + 1;
  height = (little_endian_to_ushort (ptr16 + 5)
            - little_endian_to_ushort (ptr16 + 3)) + 1;
  /* bits per pixel */
  depth = filedata[3];

  /* allocate bitmap description structure memory */
  bmp = (bitmap_desc *) memory_allocation (sizeof (bitmap_desc));
  if (bmp == NULL)
    {
      LOG_ERR ("not enough memory to allocate 'bmp'");
      return NULL;
    }
  bmp->width = width;
  bmp->height = height;
  bmp->depth = depth;
  bmp->size = width * height * (depth >> 3);
  /* allocate bitmap memory */
  bmp->pixel = memory_allocation (bmp->size);
  if (bmp->pixel == NULL)
    {
      LOG_ERR ("height=%i / width=%i", filename, width, height);
      LOG_ERR ("not enough memory to allocate %i bytes", bmp->size);
      free_memory ((char *) bmp);
      return NULL;
    }
  /* decompress rle */
  pixel = (unsigned char *) bmp->pixel;
  total = 0;
  i = size - 768;
  ptr = 128;
  while (ptr < i)
    {
      if ((filedata[ptr] & 0xC0) == 0xC0)
        {
          numof_bytes = filedata[ptr] & 0x3F;
          ptr++;
        }
      else
        {
          numof_bytes = 1;
        }
      val = filedata[ptr];
      /* bug fixed by Samuel Hocevar */
      total += numof_bytes;
      if (total >= bmp->size)
        {
          break;
        }
      for (j = 0; j < numof_bytes; j++)
        {
          *pixel = val;
          pixel++;
        }
      ptr++;
    }
  free_memory ((char *) filedata);
  LOG_DBG ("filename: \"%s\"; height:%i; width:%i; size:%i bytes", filename,
           width, height, bmp->size);
  return bmp;
}
Example #30
0
/**
 * Locate a file under one of the data directories
 * @param name Name of file relative to data directory
 * @return Pointer to a malloc'd buffer containing the name under which the
 * file was found (free()-ing the buffer is the responsibility of the caller.)
 * or NULL if could not locate file (not found, or not enough memory, or the
 * name given was absolute)
 * @author Andre Majorel
 */
char *
locate_data_file (const char *const name)
{
  static const char bogus = '\0';
  static const char *home_dir;
  const char **p;
  char *pathname;
  struct stat s;
  const char *subdir = "/share/games/mangadualist/";

  if (name == NULL)
    {
      LOG_ERR ("NULL pointer was passed as an argument!");
      return NULL;
    }
  /* if absolute path, return a pointer to a duplicate string */
  if (*name == '/')
    {
      return string_duplicate (name);
    }
  /* process each folder of the list */
  for (p = data_directories;; p++)
    {
      if (*p == 0)
        {
          pathname =
            memory_allocation (strlen (prefix_dir) + strlen (subdir) +
                               strlen (name) + 1);
          if (pathname == NULL)
            {
              fflush (stdout);
              LOG_ERR ("not enough memory");
              return NULL;
            }
          strcpy (pathname, prefix_dir);
          strcat (pathname, subdir);
          strcat (pathname, name);
        }
      /* not user anymore */
      else if (**p == '~')
        {
          home_dir = &bogus;
          if (home_dir == &bogus)
            {
              home_dir = getenv ("HOME");
            }
          if (home_dir == 0)
            {
              /* $HOME not set. Skip this directory */
              continue;
            }
          pathname = memory_allocation (strlen (home_dir)
                                        + 1 + strlen (*p + 1) + 1 +
                                        strlen (name) + 1);
          if (pathname == NULL)
            {
              fflush (stdout);
              LOG_ERR ("not enough memory");
              return NULL;
            }
          strcpy (pathname, home_dir);
          strcat (pathname, *p + 1);
          strcat (pathname, "/");
          strcat (pathname, name);
        }
      else
        {
          /* check if the file is located in current directory */
          pathname = memory_allocation (strlen (*p) + 1 + strlen (name) + 1);
          if (pathname == NULL)
            {
              fflush (stdout);
              LOG_ERR ("not enough memory");
              return NULL;
            }
          strcpy (pathname, *p);
          strcat (pathname, "/");
          strcat (pathname, name);
        }
      if (stat (pathname, &s) == 0 && !S_ISDIR (s.st_mode))
        {
          return pathname;
        }
      free_memory (pathname);
      if (*p == 0)
        {
          break;
        }
    }
  /* not found */
  return NULL;
}