Пример #1
0
Файл: hash.c Проект: btb/d2x
int hashtable_init( hashtable *ht, int size )	{
	int i;

	ht->size=0;

	for (i=1; i<13; i++ )	{
		if ( (1<<i) >= size )	{
			ht->bitsize = i;
			ht->size = 1<<i;
			break;
		}
	}
	size = ht->size;
	ht->and_mask = ht->size - 1;
	if (ht->size==0)
		Error( "Hashtable has size of 0" );

	ht->key = d_malloc( size * sizeof(char *) );
	if (ht->key==NULL)
		Error( "Not enough memory to create a hash table of size %d", size );

	for (i=0; i<size; i++ )
		ht->key[i] = NULL;

	// Use calloc cause we want zero'd array.
	ht->value = d_malloc( size*sizeof(int) );
	if (ht->value==NULL)	{
		d_free(ht->key);
		Error( "Not enough memory to create a hash table of size %d\n", size );
	}

	ht->nitems = 0;

	return 0;
}
Пример #2
0
DError* d_error_new(int level,const char* file,int line, const char* msg,...){
    
    char* buffer;
    
    DError* error = (DError*)d_malloc(sizeof(DError));
    error->level = level;
    
    if ( msg == NULL){
        error->msg = NULL;
    }
    else {
        error->file = d_strdup(file);
        error->line = line;
        
        va_list args;
        va_start(args,msg);
        int count = vsnprintf(buffer,0,msg,args);
        va_end(args);
        buffer = d_malloc(sizeof(char)*count+1);
        
        va_list args2;
        va_start(args2,msg);
        vsnprintf(buffer,count+1,msg,args2);
        va_end(args2);
        
        error->msg = buffer;
        
    }
    
    return error;
}
Пример #3
0
void align_polygon_model_data(polymodel *pm)
{
	int i, chunk_len;
	int total_correction = 0;
	ubyte *cur_old, *cur_new;
	chunk cur_ch;
	chunk ch_list[MAX_CHUNKS];
	int no_chunks = 0;
	int tmp_size = pm->model_data_size + SHIFT_SPACE;
	ubyte *tmp = d_malloc(tmp_size); // where we build the aligned version of pm->model_data

	Assert(tmp != NULL);
	//start with first chunk (is always aligned!)
	cur_old = pm->model_data;
	cur_new = tmp;
	chunk_len = get_chunks(cur_old, cur_new, ch_list, &no_chunks);
	memcpy(cur_new, cur_old, chunk_len);
	while (no_chunks > 0) {
		int first_index = get_first_chunks_index(ch_list, no_chunks);
		cur_ch = ch_list[first_index];
		// remove first chunk from array:
		no_chunks--;
		for (i = first_index; i < no_chunks; i++)
			ch_list[i] = ch_list[i + 1];
		// if (new) address unaligned:
		if ((u_int32_t)new_dest(cur_ch) % 4L != 0) {
			// calculate how much to move to be aligned
			short to_shift = 4 - (u_int32_t)new_dest(cur_ch) % 4L;
			// correct chunks' addresses
			cur_ch.correction += to_shift;
			for (i = 0; i < no_chunks; i++)
				ch_list[i].correction += to_shift;
			total_correction += to_shift;
			Assert((u_int32_t)new_dest(cur_ch) % 4L == 0);
			Assert(total_correction <= SHIFT_SPACE); // if you get this, increase SHIFT_SPACE
		}
		//write (corrected) chunk for current chunk:
		*((short *)(cur_ch.new_base + cur_ch.offset))
		  = INTEL_SHORT(cur_ch.correction
				+ INTEL_SHORT(*((short *)(cur_ch.old_base + cur_ch.offset))));
		//write (correctly aligned) chunk:
		cur_old = old_dest(cur_ch);
		cur_new = new_dest(cur_ch);
		chunk_len = get_chunks(cur_old, cur_new, ch_list, &no_chunks);
		memcpy(cur_new, cur_old, chunk_len);
		//correct submodel_ptr's for pm, too
		for (i = 0; i < MAX_SUBMODELS; i++)
			if (pm->model_data + pm->submodel_ptrs[i] >= cur_old
			    && pm->model_data + pm->submodel_ptrs[i] < cur_old + chunk_len)
				pm->submodel_ptrs[i] += (cur_new - tmp) - (cur_old - pm->model_data);
 	}
	d_free(pm->model_data);
	pm->model_data_size += total_correction;
	pm->model_data = 
	d_malloc(pm->model_data_size);
	Assert(pm->model_data != NULL);
	memcpy(pm->model_data, tmp, pm->model_data_size);
	d_free(tmp);
}
Пример #4
0
static int audio_data_handler(unsigned char major, unsigned char minor, unsigned char *data, int len, void *context)
{
#ifdef AUDIO
	static const int selected_chan=1;
	int chan;
	int nsamp;
	if (mve_audio_canplay)
	{
		if (mve_audio_playing)
			SDL_LockAudio();

		chan = get_ushort(data + 2);
		nsamp = get_ushort(data + 4);
		if (chan & selected_chan)
		{
			/* HACK: +4 mveaudio_uncompress adds 4 more bytes */
			if (major == MVE_OPCODE_AUDIOFRAMEDATA) {
				if (mve_audio_compressed) {
					nsamp += 4;

					mve_audio_buflens[mve_audio_buftail] = nsamp;
					mve_audio_buffers[mve_audio_buftail] = (short *)d_malloc(nsamp);
					mveaudio_uncompress(mve_audio_buffers[mve_audio_buftail], data, -1); /* XXX */
				} else {
					nsamp -= 8;
					data += 8;

					mve_audio_buflens[mve_audio_buftail] = nsamp;
					mve_audio_buffers[mve_audio_buftail] = (short *)d_malloc(nsamp);
					memcpy(mve_audio_buffers[mve_audio_buftail], data, nsamp);
				}
			} else {
				mve_audio_buflens[mve_audio_buftail] = nsamp;
				mve_audio_buffers[mve_audio_buftail] = (short *)d_malloc(nsamp);

				memset(mve_audio_buffers[mve_audio_buftail], 0, nsamp); /* XXX */
			}

			if (++mve_audio_buftail == TOTAL_AUDIO_BUFFERS)
				mve_audio_buftail = 0;

			if (mve_audio_buftail == mve_audio_bufhead)
				fprintf(stderr, "d'oh!  buffer ring overrun (%d)\n", mve_audio_bufhead);
		}

		if (mve_audio_playing)
			SDL_UnlockAudio();
	}
#endif

	return 1;
}
Пример #5
0
CFILE * cfopen(char * filename, char * mode )
{
	int length;
	FILE * fp;
	CFILE *cfile;

	if (stricmp( mode, "rb"))	{
		Error( "cfiles can only be opened with mode==rb\n" );
	}

	if (filename[0] != '\x01') {
		#ifdef MACINTOSH
		char mac_path[255];

		macify_dospath(filename, mac_path);
		fp = cfile_get_filehandle( mac_path, mode);
		#else
		fp = cfile_get_filehandle( filename, mode );		// Check for non-hog file first...
		#endif
	} else {
		fp = NULL;		//don't look in dir, only in hogfile
		filename++;
	}

	if ( !fp ) {
		fp = cfile_find_libfile(filename, &length );
		if ( !fp )
			return NULL;		// No file found
		cfile = d_malloc ( sizeof(CFILE) );
		if ( cfile == NULL ) {
			fclose(fp);
			return NULL;
		}
		cfile->file = fp;
		cfile->size = length;
		cfile->lib_offset = ftell( fp );
		cfile->raw_position = 0;
		return cfile;
	} else {
		cfile = d_malloc ( sizeof(CFILE) );
		if ( cfile == NULL ) {
			fclose(fp);
			return NULL;
		}
		cfile->file = fp;
		cfile->size = filelength( fileno(fp) );
		cfile->lib_offset = 0;
		cfile->raw_position = 0;
		return cfile;
	}
}
Пример #6
0
int CreateSphere (tOOF_vector **pSphere)
{
    int			nFaces, i, j;
    tOOF_vector	*buf [2];

    if (gameData.render.sphere.nFaceNodes == 3) {
        nFaces = 8;
        j = 6;
    }
    else {
        nFaces = 6;
        j = 4;
    }
    for (i = 0; i < gameData.render.sphere.nTessDepth; i++)
        nFaces *= j;
    for (i = 0; i < 2; i++) {
        if (!(buf [i] = (tOOF_vector *) d_malloc (nFaces * (gameData.render.sphere.nFaceNodes + 1) * sizeof (tOOF_vector)))) {
            if (i)
                d_free (buf [i - 1]);
            return -1;
        }
    }
    j = (gameData.render.sphere.nFaceNodes == 3) ?
        BuildSphereTri ((tOOF_triangle **) buf, &nFaces) :
        BuildSphereQuad ((tOOF_quad **) buf, &nFaces);
    d_free (buf [!j]);
    *pSphere = buf [j];
    return nFaces;
}
Пример #7
0
void save_screen_shot(int automap_flag)
{
	static int savenum=0;
	char savename[13+sizeof(SCRNS_DIR)];
	unsigned char *buf;

	if (!GameArg.DbgGlReadPixelsOk){
		if (!automap_flag)
			HUD_init_message_literal(HM_DEFAULT, "glReadPixels not supported on your configuration");
		return;
	}

	stop_time();

	if (!PHYSFSX_exists(SCRNS_DIR,0))
		PHYSFS_mkdir(SCRNS_DIR); //try making directory

	do
	{
		sprintf(savename, "%sscrn%04d.tga",SCRNS_DIR, savenum++);
	} while (PHYSFSX_exists(savename,0));

	if (!automap_flag)
		HUD_init_message(HM_DEFAULT, "%s 'scrn%04d.tga'", TXT_DUMPING_SCREEN, savenum-1 );

#ifndef OGLES
	glReadBuffer(GL_FRONT);
#endif

	buf = d_malloc(grd_curscreen->sc_w*grd_curscreen->sc_h*3);
	write_bmp(savename,grd_curscreen->sc_w,grd_curscreen->sc_h,buf);
	d_free(buf);

	start_time();
}
Пример #8
0
d_table
d_tableNew(
    int ( *  compare )(),
    void ( * cleanAction )() )
{
    d_table table;

    assert(compare != 0);
    /* Allocate table object */
    table = (d_table)d_malloc(C_SIZEOF(d_table), "Table");
    if (table) {
        /* QAC EXPECT 3892; */
        /* Call super-init */
        d_objectInit(d_object(table), D_TABLE,
                     (d_objectDeinitFunc)d_tableDeinit);
        /* Initialize table object */
        ut_avlCTreedefInit (&table->td,
                            offsetof (C_STRUCT(d_tableNode), avlnode), offsetof (C_STRUCT(d_tableNode), object),
                            (int (*) (const void *, const void *)) compare, 0,
                            UT_AVL_TREEDEF_FLAG_INDKEY);
        ut_avlCInit (&table->td, &table->tree);
        table->cleanAction = cleanAction;
    }
    return table;
}
Пример #9
0
Файл: digi.c Проект: paud/d2x-xl
int DigiSpeedupSound (digi_sound *gsp, struct sound_slot *ssp, int speed)
{
    int	h, i, j, l;
    ubyte	*pDest, *pSrc;

    l = FixMulDiv (ssp->bResampled ? ssp->length : gsp->length, speed, F1_0);
    if (!(pDest = (ubyte *) d_malloc (l)))
        return -1;
    pSrc = ssp->bResampled ? ssp->samples : gsp->data;
    for (h = i = j = 0; i < l; i++) {
        pDest [j] = pSrc [i];
        h += speed;
        while (h >= F1_0) {
            j++;
            h -= F1_0;
        }
    }
    if (ssp->bResampled)
    {
        d_free (ssp->samples);
    }
    else
        ssp->bResampled = 1;
    ssp->samples = pDest;
    return ssp->length = j;
}
Пример #10
0
char* splitword(char *s, char splitchar)
{
 int x,l,l2;
 char *word;

   for(l=0;s[l]!=0;l++);
   for(x=0;s[x]!=splitchar&&x<l;x++);
  l2=x;
  s[x]=0;
  word = (char *) d_malloc(sizeof(char) * (l2+1));
   for(x=0;x<=l2;x++)
    word[x]=s[x];

   if(l==l2)
    s[0]=0;
   else
    {
     while(x<=l)
      {
       s[x-l2-1]=s[x];
       x++;
      }
    }
  return word;
}
Пример #11
0
void create_new_mission(void)
{
	if (Current_mission)
		free_mission();
	
	Current_mission = d_malloc(sizeof(Mission));
	if (!Current_mission)
		return;
	memset(Current_mission, 0, sizeof(Mission));
	
	Current_mission->path = d_strdup("new_mission");
	if (!Current_mission->path)
	{
		free_mission();
		return;
	}

	Current_mission->filename = Current_mission->path;
	
	MALLOC(Level_names, d_fname, 1);
	if (!Level_names)
	{
		free_mission();
		return;
	}

	strcpy(Level_names[0], "GAMESAVE.LVL");
}
Пример #12
0
struct s_list *f_keys_initialize(struct s_list *supplied, const char *file, char separator) {
	struct s_list *result = supplied;
	struct s_keys_entry *entry;
	char buffer[d_string_buffer_size], *pointer;
	FILE *stream;
	if (!result)
		f_list_init(&result);
	if ((stream = fopen(file, "r"))) {
		while (!feof(stream)) {
			memset(buffer, 0, d_string_buffer_size);
			if (fgets(buffer, d_string_buffer_size, stream))
				if ((pointer = strchr(buffer, separator))) {
					*pointer = '\0';
					pointer++;
					f_string_trim(buffer);
					f_string_trim(pointer);
					if ((f_string_strlen(buffer) > 0) && (f_string_strlen(pointer) > 0))
						if ((entry = (struct s_keys_entry *) d_malloc(sizeof(struct s_keys_entry)))) {
							strncpy(entry->key, buffer, d_string_buffer_size);
							strncpy(entry->value, pointer, d_string_buffer_size);
							f_list_append(result, (struct s_list_node *)entry, e_list_insert_head);
						}
				}
		}
		fclose(stream);
	}
	return result;
}
Пример #13
0
int CreateSphere (tSphereData *sdP)
{
	int			nFaces, i, j;
	tOOF_vector	*buf [2];

if (sdP->nFaceNodes == 3) {
	nFaces = 8;
	j = 6;
	}
else {
	nFaces = 6;
	j = 4;
	}
for (i = 0; i < sdP->nTessDepth; i++)
	nFaces *= j;
for (i = 0; i < 2; i++) {
	if (!(buf [i] = (tOOF_vector *) d_malloc (nFaces * (sdP->nFaceNodes + 1) * sizeof (tOOF_vector)))) {
		if (i)
			d_free (buf [i - 1]);
		return -1;
		}
	}
j = (sdP->nFaceNodes == 3) ? 
	 BuildSphereTri ((tOOF_triangle **) buf, &nFaces, sdP->nTessDepth) : 
	 BuildSphereQuad ((tOOF_quad **) buf, &nFaces, sdP->nTessDepth);
d_free (buf [!j]);
sdP->pSphere = buf [j];
return nFaces;
}
Пример #14
0
struct s_attributes *p_object_attributes_malloc(size_t size, const char *type) {
    struct s_attributes *result;
    if ((result = (struct s_attributes *) d_malloc(size)))
        result->type = type;
    else
        d_die(d_error_malloc);
    return result;
}
Пример #15
0
char *dumb_dup(const char *s)
{
	char *copy = (char *)d_malloc(strlen(s) + 1);
	if (copy) {
		strcpy(copy, s);
	}
	return copy;
}
Пример #16
0
UI_DIALOG * ui_create_dialog( short x, short y, short w, short h, enum dialog_flags flags, int (*callback)(UI_DIALOG *, d_event *, void *), void *userdata )
{
	UI_DIALOG	*dlg;
	int sw, sh, req_w, req_h;

	dlg = (UI_DIALOG *) d_malloc(sizeof(UI_DIALOG));
	if (dlg==NULL) Error("Could not create dialog: Out of memory");

	sw = grd_curscreen->sc_w;
	sh = grd_curscreen->sc_h;

	//mouse_set_limits(0, 0, sw - 1, sh - 1);

	req_w = w;
	req_h = h;

	dlg->flags = flags;

	if (flags & DF_BORDER)
	{
		x -= BORDER_WIDTH;
		y -= BORDER_WIDTH;
		w += 2*BORDER_WIDTH;
		h += 2*BORDER_WIDTH;
	}

	if ( x < 0 ) x = 0;
	if ( (x+w-1) >= sw ) x = sw - w;
	if ( y < 0 ) y = 0;
	if ( (y+h-1) >= sh ) y = sh - h;

	D_X = x;
	D_Y = y;
	D_WIDTH = w;
	D_HEIGHT = h;
	D_GADGET = NULL;
	dlg->keyboard_focus_gadget = NULL;
	selected_gadget = NULL;

	dlg->callback = callback;
	dlg->userdata = userdata;
	dlg->wind = window_create(&grd_curscreen->sc_canvas,
						 x + ((flags & DF_BORDER) ? BORDER_WIDTH : 0),
						 y + ((flags & DF_BORDER) ? BORDER_WIDTH : 0),
						 req_w, req_h, (int (*)(window *, d_event *, void *)) ui_dialog_handler, dlg);

	if (!dlg->wind)
	{
		d_free(dlg);
		return NULL;
	}

	if (!(flags & DF_MODAL))
		window_set_modal(dlg->wind, 0);	// make this window modeless, allowing events to propogate through the window stack

	return dlg;

}
Пример #17
0
d_define_method(emitter, record)(struct s_object *self, const char *id) {
	d_using(emitter);
	struct s_signal *signal;
	if ((signal = (struct s_signal *) d_malloc(sizeof(struct s_signal)))) {
		strncpy(signal->id, id, (d_emitter_name_size-1));
		f_list_append(emitter_attributes->signals, (struct s_list_node *)signal, e_list_insert_head);
	}
	return (void *)signal;
}
Пример #18
0
struct s_attributes *p_object_setup(struct s_object *object, struct s_method *virtual_table, struct s_attributes *attributes) {
    struct s_virtual_table *node;
    if ((node = (struct s_virtual_table *) d_malloc(sizeof(struct s_virtual_table)))) {
        node->virtual_table = virtual_table;
        node->type = attributes->type;
        f_list_append(&(object->virtual_tables), (struct s_list_node *)node, e_list_insert_head);
        f_list_append(&(object->attributes), (struct s_list_node *)attributes, e_list_insert_head);
    } else
        d_die(d_error_malloc);
    return attributes;
}
Пример #19
0
/*
 * routine which allocates, reads, and inits a polymodel's model_data
 */
void polygon_model_data_read(polymodel *pm, PHYSFS_file *fp)
{
	pm->model_data = d_malloc(pm->model_data_size);
	Assert(pm->model_data != NULL);
	PHYSFS_read(fp, pm->model_data, sizeof(ubyte), pm->model_data_size);
#ifdef WORDS_NEED_ALIGNMENT
	align_polygon_model_data(pm);
#endif
#ifdef WORDS_BIGENDIAN
	swap_polygon_model_data(pm->model_data);
#endif
}
Пример #20
0
d_define_method(container, add_drawable)(struct s_object *self, struct s_object *drawable, double position_x, double position_y) {
  d_using(container);
  struct s_container_drawable *current_container;
  if ((current_container = (struct s_container_drawable *)d_malloc(sizeof(struct s_container_drawable)))) {
    current_container->drawable = d_retain(drawable);
    current_container->position_x = position_x;
    current_container->position_y = position_y;
    f_list_append(&(container_attributes->entries), (struct s_list_node *)current_container, e_list_insert_tail);
  } else
    d_die(d_error_malloc);
  return self;
}
Пример #21
0
boost::shared_array<T>
d_array(size_t len, bool clear, const char* name)
{
	void* d_ptr = NULL;
	size_t bytes = len * sizeof(T);
	d_malloc(&d_ptr, bytes, name);
	boost::shared_array<T> ret(static_cast<T*>(d_ptr), d_free);
	if(clear) {
		d_memset(d_ptr, 0, bytes);
	}
	return ret;
}
Пример #22
0
void LoadTerrain (char *filename)
{
	grs_bitmap	bmHeight;
	int			iff_error;
	int			i, j;
	ubyte			h, hMin, hMax;

LogErr ("            loading terrain height map\n");
iff_error = iff_read_bitmap (filename, &bmHeight, BM_LINEAR);
if (iff_error != IFF_NO_ERROR) {
#if TRACE		
	con_printf (1, "File %s - IFF error: %s", filename, iff_errormsg (iff_error));
#endif		
	Error ("File %s - IFF error: %s", filename, iff_errormsg (iff_error));
}
if (gameData.render.terrain.pHeightMap)
	d_free (gameData.render.terrain.pHeightMap)
else
	atexit (FreeTerrainHeightMap);		//first time
gameData.render.terrain.nGridW = bmHeight.bm_props.w;
gameData.render.terrain.nGridH = bmHeight.bm_props.h;
Assert (gameData.render.terrain.nGridW <= TERRAIN_GRID_MAX_SIZE);
Assert (gameData.render.terrain.nGridH <= TERRAIN_GRID_MAX_SIZE);
gameData.render.terrain.pHeightMap = bmHeight.bm_texBuf;
hMax = 0;
hMin = 255;
for (i = 0; i < gameData.render.terrain.nGridW; i++)
	for (j = 0; j < gameData.render.terrain.nGridH; j++) {
		h = HEIGHT (i, j);
		if (h > hMax)
			hMax = h;
		if (h < hMin)
			hMin = h;
		}
for (i = 0; i < gameData.render.terrain.nGridW; i++) {
	for (j = 0; j < gameData.render.terrain.nGridH; j++) {
		HEIGHT (i, j) -= hMin;
		}
	}
//	d_free (bmHeight.bm_texBuf);
gameData.render.terrain.bmP = gameData.endLevel.terrain.bmP;
#if 0 //the following code turns the (palettized) terrain texture into a white TGA texture for testing
gameData.render.terrain.bmP->bm_props.rowsize *= 4;
gameData.render.terrain.bmP->bm_props.flags |= BM_FLAG_TGA;
d_free (gameData.render.terrain.bmP->bm_texBuf);
gameData.render.terrain.bmP->bm_texBuf = d_malloc (gameData.render.terrain.bmP->bm_props.h * gameData.render.terrain.bmP->bm_props.rowsize);
memset (gameData.render.terrain.bmP->bm_texBuf, 0xFF, gameData.render.terrain.bmP->bm_props.h * gameData.render.terrain.bmP->bm_props.rowsize);
#endif
LogErr ("            building terrain light map\n");
BuildTerrainLightMap ();
}
Пример #23
0
/*
 * routine which allocates, reads, and inits a polymodel's model_data
 */
void polygon_model_data_read(polymodel *pm, CFILE *fp)
{
	pm->model_data = d_malloc(pm->model_data_size);
	Assert(pm->model_data != NULL);
	cfread(pm->model_data, sizeof(ubyte), pm->model_data_size, fp );
#ifdef WORDS_NEED_ALIGNMENT
	align_polygon_model_data(pm);
#endif
#ifdef WORDS_BIGENDIAN
	swap_polygon_model_data(pm->model_data);
#endif
	//verify(pm->model_data);
	g3_init_polygon_model(pm->model_data);
}
Пример #24
0
/*
 * routine which allocates, reads, and inits a polymodel's model_data
 */
void PolyModelDataRead (polymodel *pm, polymodel *pdm, CFILE *fp)
{
    if (pm->model_data)
        d_free (pm->model_data);
    pm->model_data = d_malloc (pm->model_data_size);
    Assert (pm->model_data != NULL);
    CFRead (pm->model_data, sizeof (ubyte), pm->model_data_size, fp);
    if (pdm) {
        if (pdm->model_data)
            d_free (pdm->model_data);
        pdm->model_data = d_malloc (pm->model_data_size);
        Assert (pdm->model_data != NULL);
        memcpy (pdm->model_data, pm->model_data, pm->model_data_size);
    }
#ifdef WORDS_NEED_ALIGNMENT
    AlignPolyModelData (pm);
#endif
#if defined (WORDS_BIGENDIAN) || defined (__BIG_ENDIAN__)
    G3SwapPolyModelData (pm->model_data);
#endif
    //verify (pm->model_data);
    G3InitPolyModel (pm->model_data);
}
Пример #25
0
Файл: state.c Проект: btb/d2x
//	-----------------------------------------------------------------------------------
//	Imagine if C had a function to copy a file...
int copy_file(char *old_file, char *new_file)
{
	sbyte   *buf = NULL;
	int		buf_size;
	PHYSFS_file *in_file, *out_file;

	out_file = PHYSFS_openWrite(new_file);

	if (out_file == NULL)
		return -1;

	in_file = PHYSFS_openRead(old_file);

	if (in_file == NULL)
		return -2;

	buf_size = (int)PHYSFS_fileLength(in_file);
	while (buf_size && !(buf = d_malloc(buf_size)))
		buf_size /= 2;
	if (buf_size == 0)
		return -5;	// likely to be an empty file

	while (!PHYSFS_eof(in_file))
	{
		int bytes_read;

		bytes_read = (int)PHYSFS_read(in_file, buf, 1, buf_size);
		if (bytes_read < 0)
			Error("Cannot read from file <%s>: %s", old_file, PHYSFS_getLastError());

		Assert(bytes_read == buf_size || PHYSFS_eof(in_file));

		if (PHYSFS_write(out_file, buf, 1, bytes_read) < bytes_read)
			Error("Cannot write to file <%s>: %s", new_file, PHYSFS_getLastError());
	}

	d_free(buf);

	if (!PHYSFS_close(in_file))
	{
		PHYSFS_close(out_file);
		return -3;
	}

	if (!PHYSFS_close(out_file))
		return -4;

	return 0;
}
Пример #26
0
/***********************************************************************
 *
 * Method     : d_avlTreeInsert
 * Algorithm  :
 *    1st : find insertion place by a iterative tree walk.
 *    2nd : insert new node only if not already occupied.
 *    3rd : rebalance tree.
 * If the item is in the tree
 * Then the existing item is returned
 * Else it is added and NULL is returned
 *
 ***********************************************************************/
c_voidp
d_avlTreeInsert (
    d_avlNode * rootNodePntr,
    c_voidp     data,
    int (*      compareFunction)() )
{
    d_avlNode    node;
    d_avlNode *  nodeplace;
    d_avlNode *  stack[D_AVLTREE_MAXHEIGHT];
    d_avlNode ** stackPtr = &stack[0];
    c_long       stack_count = 0;
    c_long       comparison;

    assert(rootNodePntr != NULL);
    assert(data != NULL);
    assert(compareFunction != (int(*)())NULL);

    nodeplace = rootNodePntr;

    for (;;) {
        node = *nodeplace;
        if (node == NULL) {
            break;
        }
        *stackPtr = nodeplace;
        stackPtr++;
        stack_count++;
        comparison = compareFunction(node->data, data);
        if (comparison > 0) {
            nodeplace = &node->left;
        } else if (comparison < 0) {
            nodeplace = &node->right;
        } else {
            return node->data;
        }
    }
    node = (d_avlNode)d_malloc((os_uint32)C_SIZEOF(d_avlNode), "TreeNode");
    if (node == NULL) {
        return data;    /* cannot insert it */
    } else {
        node->left = NULL;
        node->right = NULL;
        node->height = 1;
        node->data = data;
        *nodeplace = node;
        d_avlTreeRebalance(stackPtr,stack_count);
    }
    return NULL;
}
Пример #27
0
int f_telnet_initialize(struct s_telnet **telnet) {
  int flag = 1;
  if ((*telnet = (struct s_telnet *)d_malloc(sizeof(struct s_telnet)))) {
    memset(&((*telnet)->address), 0, sizeof(struct sockaddr_in));
    if (((*telnet)->socket.socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) != d_telnet_stream_null)
      if (setsockopt((*telnet)->socket.socket, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int)) != d_telnet_stream_null) {
        (*telnet)->address.sin_family = AF_INET;
        (*telnet)->address.sin_port = htons(d_telnet_port);
        (*telnet)->address.sin_addr.s_addr = htonl(INADDR_ANY);
        if (bind((*telnet)->socket.socket, (struct sockaddr *)&((*telnet)->address), sizeof(struct sockaddr_in)) == 0)
          if (listen((*telnet)->socket.socket, d_telnet_queue) == 0)
            (*telnet)->socket.initialized = d_true;
      }
  }
  return (*telnet)->socket.initialized;
}
Пример #28
0
DSocket* d_socket_connect_by_ip(char* ip, int port, DError** error) {

    int iResult;
    WSADATA wsaData;
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed: %d\n", iResult);
        return NULL;
    }

    DSocket* new_socket = d_malloc(sizeof (DSocket));


    struct sockaddr_in sock_adress;

    if ((sock_adress.sin_addr.s_addr = inet_addr(ip)) == -1) {
        if (error)
            *error = DERROR("IP adress %s is invalid", ip);
        goto error;
    };

    sock_adress.sin_family = AF_INET; /* Protocol IP */
    sock_adress.sin_port = htons(port);

    new_socket->socket_desc = socket(AF_INET, SOCK_STREAM, 0);


    if (new_socket->socket_desc == INVALID_SOCKET) {
        if (error)
            *error = DERROR("Cant create socket, %s", strerror(errno));
        goto error;
    }

    if (connect(new_socket->socket_desc, (const struct sockaddr*) &sock_adress, sizeof (sock_adress)) == SOCKET_ERROR) {
        if (error)
            *error = DERROR("Connection to %s:%d failed, %s", ip, port, strerror(errno));
        goto error;
    }

    return new_socket;

error:
    if (new_socket) d_socket_close(new_socket);
    return NULL;

}
Пример #29
0
void send_ipc(char *message)
{
	con_printf(CON_DEBUG,"sendipc %s\n", message);
	if (ipc_queue_id<0)
	{
		ipc_queue_id=msgget ((key_t) ('l'<<24) | ('d'<<16) | ('e'<<8) | 's', 
				     IPC_CREAT | 0660);
		snd=d_malloc(sizeof(long) + 32);
		snd->mtype=1;
		player_thread=SDL_CreateThread((int (*)(void *))play_hmi, NULL);
	}
	if (strlen(message) < 16)
	{
		sprintf(snd->mtext,"%s",message);
		msgsnd(ipc_queue_id,snd,16,0);
	}
}
Пример #30
0
static int create_videobuf_handler(unsigned char major, unsigned char minor, unsigned char *data, int len, void *context)
{
	short w, h;
	short count, truecolor;

	if (videobuf_created)
		return 1;
	else
		videobuf_created = 1;

	w = get_short(data);
	h = get_short(data+2);

	if (minor > 0) {
		count = get_short(data+4);
	} else {
		count = 1;
	}

	if (minor > 1) {
		truecolor = get_short(data+6);
	} else {
		truecolor = 0;
	}

	g_width = w << 3;
	g_height = h << 3;

	/* TODO: * 4 causes crashes on some files */
	g_vBackBuf1 = g_vBuffers = d_malloc(g_width * g_height * 8);
	if (truecolor) {
		g_vBackBuf2 = (unsigned short *)g_vBackBuf1 + (g_width * g_height);
	} else {
		g_vBackBuf2 = (unsigned char *)g_vBackBuf1 + (g_width * g_height);
	}

	memset(g_vBackBuf1, 0, g_width * g_height * 4);

#ifdef DEBUG
	fprintf(stderr, "DEBUG: w,h=%d,%d count=%d, tc=%d\n", w, h, count, truecolor);
#endif

	g_truecolor = truecolor;

	return 1;
}