/* ================ idCollisionModelManagerLocal::ParseBrushes ================ */ void idCollisionModelManagerLocal::ParseBrushes( idLexer *src, cm_model_t *model ) { cm_brush_t *b; int i, numPlanes; idVec3 normal; idToken token; if ( src->CheckTokenType( TT_NUMBER, 0, &token ) ) { model->brushBlock = (cm_brushBlock_t *) Mem_Alloc( sizeof( cm_brushBlock_t ) + token.GetIntValue() ); model->brushBlock->bytesRemaining = token.GetIntValue(); model->brushBlock->next = ( (byte *) model->brushBlock ) + sizeof( cm_brushBlock_t ); } src->ExpectTokenString( "{" ); while ( !src->CheckTokenString( "}" ) ) { // parse brush numPlanes = src->ParseInt(); b = AllocBrush( model, numPlanes ); b->numPlanes = numPlanes; src->ExpectTokenString( "{" ); for ( i = 0; i < b->numPlanes; i++ ) { src->Parse1DMatrix( 3, normal.ToFloatPtr() ); b->planes[i].SetNormal( normal ); b->planes[i].SetDist( src->ParseFloat() ); } src->ExpectTokenString( "}" ); src->Parse1DMatrix( 3, b->bounds[0].ToFloatPtr() ); src->Parse1DMatrix( 3, b->bounds[1].ToFloatPtr() ); src->ReadToken( &token ); if ( token.type == TT_NUMBER ) { b->contents = token.GetIntValue(); // old .cm files use a single integer } else { b->contents = ContentsFromString( token ); } b->checkcount = 0; b->primitiveNum = 0; // filter brush into tree R_FilterBrushIntoTree( model, model->node, NULL, b ); } }
/* ===================== R_InitFrameData ===================== */ void R_InitFrameData( void ) { int size; frameData_t *frame; frameMemoryBlock_t *block; R_ShutdownFrameData(); frameData = (frameData_t *)Mem_ClearedAlloc( sizeof( *frameData )); frame = frameData; size = MEMORY_BLOCK_SIZE; block = (frameMemoryBlock_t *)Mem_Alloc( size + sizeof( *block ) ); if ( !block ) { common->FatalError( "R_InitFrameData: Mem_Alloc() failed" ); } block->size = size; block->used = 0; block->next = NULL; frame->memory = block; frame->memoryHighwater = 0; R_ToggleSmpFrame(); }
/* ================ idCollisionModelManagerLocal::ParseEdges ================ */ void idCollisionModelManagerLocal::ParseEdges( idLexer *src, cm_model_t *model ) { int i; src->ExpectTokenString( "{" ); model->numEdges = src->ParseInt(); model->maxEdges = model->numEdges; model->edges = (cm_edge_t *) Mem_Alloc( model->maxEdges * sizeof( cm_edge_t ) ); for ( i = 0; i < model->numEdges; i++ ) { src->ExpectTokenString( "(" ); model->edges[i].vertexNum[0] = src->ParseInt(); model->edges[i].vertexNum[1] = src->ParseInt(); src->ExpectTokenString( ")" ); model->edges[i].side = 0; model->edges[i].sideSet = 0; model->edges[i].internal = src->ParseInt(); model->edges[i].numUsers = src->ParseInt(); model->edges[i].normal = vec3_origin; model->edges[i].checkcount = 0; model->numInternalEdges += model->edges[i].internal; } src->ExpectTokenString( "}" ); }
/* ================ R_WritePalTGA ================ */ void R_WritePalTGA( const char *filename, const byte *data, const byte *palette, int width, int height, bool flipVertical ) { byte *buffer; int i; int bufferSize = (width * height) + (256 * 3) + 18; int palStart = 18; int imgStart = 18 + (256 * 3); buffer = (byte *)Mem_Alloc( bufferSize ); memset( buffer, 0, 18 ); buffer[1] = 1; // color map type buffer[2] = 1; // uncompressed color mapped image buffer[5] = 0; // number of palette entries (lo) buffer[6] = 1; // number of palette entries (hi) buffer[7] = 24; // color map bpp buffer[12] = width&255; buffer[13] = width>>8; buffer[14] = height&255; buffer[15] = height>>8; buffer[16] = 8; // pixel size if ( !flipVertical ) { buffer[17] = (1<<5); // flip bit, for normal top to bottom raster order } // store palette, swapping rgb to bgr for ( i=palStart ; i<imgStart ; i+=3 ) { buffer[i] = palette[i-palStart+2]; // blue buffer[i+1] = palette[i-palStart+1]; // green buffer[i+2] = palette[i-palStart+0]; // red } // store the image data for ( i=imgStart ; i<bufferSize ; i++ ) { buffer[i] = data[i-imgStart]; } fileSystem->WriteFile( filename, buffer, bufferSize ); Mem_Free (buffer); }
/* ============================= idGameBustOutWindow::LoadBoardFiles ============================= */ void idGameBustOutWindow::LoadBoardFiles( void ) { int i; int w,h; ID_TIME_T time; int boardSize; byte *currentBoard; if ( boardDataLoaded ) { return; } boardSize = 9 * 12 * 4; levelBoardData = (byte*)Mem_Alloc( boardSize * numLevels ); currentBoard = levelBoardData; for ( i=0; i<numLevels; i++ ) { byte *pic; idStr name = "guis/assets/bustout/level"; name += (i+1); name += ".tga"; R_LoadImage( name, &pic, &w, &h, &time, false ); if ( pic != NULL ) { if ( w != 9 || h != 12 ) { common->DWarning( "Hell Bust-Out level image not correct dimensions! (%d x %d)", w, h ); } memcpy( currentBoard, pic, boardSize ); Mem_Free(pic); } currentBoard += boardSize; } boardDataLoaded = true; }
s32 __FAT_Initialize(u32 *queuehandle) { /* Heap space */ //static u32 heapspace[0x8000] ATTRIBUTE_ALIGN(32); static u32 heapspace[0x7000] ATTRIBUTE_ALIGN(32); void *buffer = NULL; s32 ret; /* Initialize memory heap */ ret = Mem_Init(heapspace, sizeof(heapspace)); if (ret < 0) return ret; /* Initialize timer subsystem */ ret = Timer_Init(); if (ret < 0) return ret; /* Allocate queue buffer */ buffer = Mem_Alloc(0x80); if (!buffer) return IPC_ENOMEM; /* Create message queue */ ret = os_message_queue_create(buffer, 32); if (ret < 0) return ret; /* Register device */ os_device_register(DEVICE_FAT, ret); os_device_register("$", ret); /* Copy queue handler */ *queuehandle = ret; return 0; }
int MA_AddMaterial( const char *materialName ) { maMaterialNode_t **destNode; maGlobal.model->materialNodes.Get( materialName, &destNode ); if( destNode ) { maMaterialNode_t *matNode = *destNode; //Iterate down the tree until we get a file while( matNode && !matNode->file ) { matNode = matNode->child; } if( matNode && matNode->file ) { //Got the file maMaterial_t *material; material = ( maMaterial_t * ) Mem_Alloc( sizeof( maMaterial_t ) ); memset( material, 0, sizeof( maMaterial_t ) ); //Remove the OS stuff idStr qPath; qPath = fileSystem->OSPathToRelativePath( matNode->file->path ); strcpy( material->name, qPath.c_str() ); maGlobal.model->materials.Append( material ); return maGlobal.model->materials.Num() - 1; } } return -1; }
/* ==================== EdgeIntersection Creates a new optVertex_t where the line segments cross. This should only be called if PointsStraddleLine returned true Will return NULL if the lines are colinear ==================== */ static optVertex_t* EdgeIntersection( const optVertex_t* p1, const optVertex_t* p2, const optVertex_t* l1, const optVertex_t* l2, optimizeGroup_t* opt ) { float f; idDrawVert* v; idVec3 dir1, dir2, cross1, cross2; dir1 = p1->pv - l1->pv; dir2 = p1->pv - l2->pv; cross1 = dir1.Cross( dir2 ); dir1 = p2->pv - l1->pv; dir2 = p2->pv - l2->pv; cross2 = dir1.Cross( dir2 ); if( cross1[2] - cross2[2] == 0 ) { return NULL; } f = cross1[2] / ( cross1[2] - cross2[2] ); // FIXME: how are we freeing this, since it doesn't belong to a tri? v = ( idDrawVert* )Mem_Alloc( sizeof( *v ), TAG_TOOLS ); memset( v, 0, sizeof( *v ) ); v->xyz = p1->v.xyz * ( 1.0 - f ) + p2->v.xyz * f; idVec3 normal = p1->v.GetNormal() * ( 1.0 - f ) + p2->v.GetNormal() * f; normal.Normalize(); v->SetNormal( normal ); idVec2 st; st.x = p1->v.GetTexCoordS() * ( 1.0 - f ) + p2->v.GetTexCoordS() * f; st.y = p1->v.GetTexCoordT() * ( 1.0 - f ) + p2->v.GetTexCoordT() * f; v->SetTexCoord( st ); return FindOptVertex( v, opt ); }
/* ================ CL_InitParticles ================ */ void CL_InitParticles( void ) { int i; cl_particles = Mem_Alloc( cls.mempool, sizeof( particle_t ) * GI->max_particles ); CL_ClearParticles (); // this is used for EF_BRIGHTFIELD for( i = 0; i < NUMVERTEXNORMALS; i++ ) { cl_avelocities[i][0] = Com_RandomLong( 0, 255 ) * 0.01f; cl_avelocities[i][1] = Com_RandomLong( 0, 255 ) * 0.01f; cl_avelocities[i][2] = Com_RandomLong( 0, 255 ) * 0.01f; } tracerred = Cvar_Get( "tracerred", "0.8", 0, "tracer red component weight ( 0 - 1.0 )" ); tracergreen = Cvar_Get( "tracergreen", "0.8", 0, "tracer green component weight ( 0 - 1.0 )" ); tracerblue = Cvar_Get( "tracerblue", "0.4", 0, "tracer blue component weight ( 0 - 1.0 )" ); traceralpha = Cvar_Get( "traceralpha", "0.5", 0, "tracer alpha amount ( 0 - 1.0 )" ); tracerspeed = Cvar_Get( "tracerspeed", "6000", 0, "tracer speed" ); tracerlength = Cvar_Get( "tracerlength", "0.8", 0, "tracer length factor" ); traceroffset = Cvar_Get( "traceroffset", "30", 0, "tracer starting offset" ); }
void *idClass::operator new( size_t s, int, int, char *, int ) { int *p; s += sizeof( int ); p = ( int * )Mem_Alloc( s ); *p = s; memused += s; numobjects++; #ifdef ID_DEBUG_UNINITIALIZED_MEMORY unsigned long *ptr = ( unsigned long * )p; int size = s; assert( ( size & 3 ) == 0 ); size >>= 3; for( int i = 1; i < size; i++ ) { ptr[i] = 0xcdcdcdcd; } #endif return p + 1; }
/* ================ Sys_GetClipboardData ================ */ char *Sys_GetClipboardData(void) { char *data = NULL; char *cliptext; if (OpenClipboard(NULL) != 0) { HANDLE hClipboardData; if ((hClipboardData = GetClipboardData(CF_TEXT)) != 0) { if ((cliptext = (char *)GlobalLock(hClipboardData)) != 0) { data = (char *)Mem_Alloc(GlobalSize(hClipboardData) + 1); strcpy(data, cliptext); GlobalUnlock(hClipboardData); strtok(data, "\n\r\b"); } } CloseClipboard(); } return data; }
/* Get the netmask bits */ uint8_t * cidr_get_mask(const CIDR *addr) { uint8_t *toret; if(addr==NULL) { errno = EFAULT; return(NULL); } toret = Mem_Alloc(16*sizeof(uint8_t)); if(toret==NULL) { errno = ENOMEM; return(NULL); } /* Copy 'em in */ memcpy(toret, addr->mask, sizeof(addr->mask)); return(toret); }
/* ================ idCollisionModelManagerLocal::ParsePolygons ================ */ void idCollisionModelManagerLocal::ParsePolygons( idLexer *src, cm_model_t *model ) { cm_polygon_t *p; int i, numEdges; idVec3 normal; idToken token; if ( src->CheckTokenType( TT_NUMBER, 0, &token ) ) { model->polygonBlock = (cm_polygonBlock_t *) Mem_Alloc( sizeof( cm_polygonBlock_t ) + token.GetIntValue() ); model->polygonBlock->bytesRemaining = token.GetIntValue(); model->polygonBlock->next = ( (byte *) model->polygonBlock ) + sizeof( cm_polygonBlock_t ); } src->ExpectTokenString( "{" ); while ( !src->CheckTokenString( "}" ) ) { // parse polygon numEdges = src->ParseInt(); p = AllocPolygon( model, numEdges ); p->numEdges = numEdges; src->ExpectTokenString( "(" ); for ( i = 0; i < p->numEdges; i++ ) { p->edges[i] = src->ParseInt(); } src->ExpectTokenString( ")" ); src->Parse1DMatrix( 3, normal.ToFloatPtr() ); p->plane.SetNormal( normal ); p->plane.SetDist( src->ParseFloat() ); src->Parse1DMatrix( 3, p->bounds[0].ToFloatPtr() ); src->Parse1DMatrix( 3, p->bounds[1].ToFloatPtr() ); src->ExpectTokenType( TT_STRING, 0, &token ); // get material p->material = declManager->FindMaterial( token ); p->contents = p->material->GetContentFlags(); p->checkcount = 0; // filter polygon into tree R_FilterPolygonIntoTree( model, model->node, NULL, p ); } }
DRESULT disk_read(BYTE drv, BYTE *buff, DWORD sector, BYTE count) { void *buffer; u32 len; s32 ret = 0; /* Buffer length */ len = (count * SECTOR_SZ); /* Allocate buffer */ buffer = Mem_Alloc(count * 512); if (!buffer) return RES_ERROR; /* Read sectors */ switch (drv) { case DRIVE_SDHC: /* Read SD sectors */ ret = sdio_ReadSectors(sector, count, buffer); break; case DRIVE_EHCI: /* Read USB sectors */ ret = ehci_ReadSectors(sector, count, buffer); break; } /* Copy buffer */ if (ret) memcpy(buff, buffer, len); /* Free buffer */ Mem_Free(buffer); return (ret) ? RES_OK : RES_ERROR; }
/* ============ idScriptObject::SetType Allocates an object and initializes memory. ============ */ bool idScriptObject::SetType( const char *typeName ) { size_t size; idTypeDef *newtype; // lookup the type newtype = gameLocal.program.FindType( typeName ); // only allocate memory if the object type changes if( newtype != type ) { Free(); if( !newtype ) { gameLocal.DWarning( "idScriptObject::SetType: Unknown type '%s'", typeName ); return false; } if( !newtype->Inherits( &type_object ) ) { gameLocal.DWarning( "idScriptObject::SetType: Can't create object of type '%s'. Must be an object type.", newtype->Name() ); return false; } // set the type type = newtype; // allocate the memory size = type->Size(); data = ( byte * )Mem_Alloc( size ); } // init object memory ClearObject(); return true; }
static void WriteTGA24 (const char *filename, const byte * data, int width, int height, int offset) { int i, size; byte *buffer; qFILE file; size = width * height * 3; /* allocate a buffer and set it up */ buffer = (byte *)Mem_Alloc(size + TGA_HEADER_SIZE); memset(buffer, 0, TGA_HEADER_SIZE); buffer[2] = 2; buffer[12] = width & 255; buffer[13] = width >> 8; buffer[14] = height & 255; buffer[15] = height >> 8; buffer[16] = 24; /* create top-down TGA */ buffer[17] = 32; /* swap rgb to bgr */ for (i = 0; i < size; i += 3) { buffer[i + TGA_HEADER_SIZE] = data[i*2 + offset + 2]; /* blue */ buffer[i + TGA_HEADER_SIZE + 1] = data[i*2 + offset + 1]; /* green */ buffer[i + TGA_HEADER_SIZE + 2] = data[i*2 + offset + 0]; /* red */ } /* write it and free the buffer */ if (FS_OpenFile(filename, &file, FILE_WRITE) > 0) Sys_Error("Unable to open %s for writing", filename); FS_Write(buffer, size + TGA_HEADER_SIZE, &file); /* close the file */ FS_CloseFile(&file); Mem_Free(buffer); }
void * idClass::operator new( size_t s, int, int, char *, int ) { int *p; s += sizeof( int ); //RAVEN BEGIN //amccarthy: Added memory allocation tag p = (int *)Mem_Alloc( s, MA_CLASS ); //RAVEN END *p = s; memused += s; numobjects++; #ifdef ID_DEBUG_MEMORY unsigned long *ptr = (unsigned long *)p; int size = s; assert( ( size & 3 ) == 0 ); size >>= 3; for ( int i = 1; i < size; i++ ) { ptr[i] = 0xcdcdcdcd; } #endif return p + 1; }
void MA_ParseFileNode(idParser& parser) { //Get the header info from the node maNodeHeader_t header; MA_ParseNodeHeader(parser, &header); //Read the transform attributes idToken token; while(parser.ReadToken(&token)) { if(IsNodeComplete(token)) { parser.UnreadToken(&token); break; } if(!token.Icmp("setAttr")) { maAttribHeader_t attribHeader; MA_ParseAttribHeader(parser, &attribHeader); if(strstr(attribHeader.name, ".ftn")) { parser.SkipUntilString("string"); parser.ReadToken(&token); if(!token.Icmp("(")) { parser.ReadToken(&token); } maFileNode_t* fileNode; fileNode = (maFileNode_t*)Mem_Alloc( sizeof( maFileNode_t ) ); strcpy(fileNode->name, header.name); strcpy(fileNode->path, token.c_str()); maGlobal.model->fileNodes.Set(fileNode->name, fileNode); } else { parser.SkipRestOfLine(); } } } }
/* ================ Sys_ListFiles ================ */ int Sys_ListFiles( const char* directory, const char* extension, idStrList& list ) { struct dirent* d; DIR* fdir; bool dironly = false; char search[MAX_OSPATH]; struct stat st; bool debug; list.Clear(); debug = cvarSystem->GetCVarBool( "fs_debug" ); // DG: we use fnmatch for shell-style pattern matching // so the pattern should at least contain "*" to match everything, // the extension will be added behind that (if !dironly) idStr pattern( "*" ); // passing a slash as extension will find directories if( extension[0] == '/' && extension[1] == 0 ) { dironly = true; } else { // so we have *<extension>, the same as in the windows code basically pattern += extension; } // DG end // NOTE: case sensitivity of directory path can screw us up here if( ( fdir = opendir( directory ) ) == NULL ) { if( debug ) { common->Printf( "Sys_ListFiles: opendir %s failed\n", directory ); } return -1; } // DG: use readdir_r instead of readdir for thread safety // the following lines are from the readdir_r manpage.. fscking ugly. int nameMax = pathconf( directory, _PC_NAME_MAX ); if( nameMax == -1 ) nameMax = 255; int direntLen = offsetof( struct dirent, d_name ) + nameMax + 1; struct dirent* entry = ( struct dirent* )Mem_Alloc( direntLen, TAG_CRAP ); if( entry == NULL ) { common->Warning( "Sys_ListFiles: Mem_Alloc for entry failed!" ); closedir( fdir ); return 0; } while( readdir_r( fdir, entry, &d ) == 0 && d != NULL ) { // DG end idStr::snPrintf( search, sizeof( search ), "%s/%s", directory, d->d_name ); if( stat( search, &st ) == -1 ) continue; if( !dironly ) { // DG: the original code didn't work because d3 bfg abuses the extension // to match whole filenames and patterns in the savegame-code, not just file extensions... // so just use fnmatch() which supports matching shell wildcard patterns ("*.foo" etc) // if we should ever need case insensitivity, use FNM_CASEFOLD as third flag if( fnmatch( pattern.c_str(), d->d_name, 0 ) != 0 ) continue; // DG end } if( ( dironly && !( st.st_mode & S_IFDIR ) ) || ( !dironly && ( st.st_mode & S_IFDIR ) ) ) continue; list.Append( d->d_name ); } closedir( fdir ); Mem_Free( entry ); if( debug ) { common->Printf( "Sys_ListFiles: %d entries in %s\n", list.Num(), directory ); } return list.Num(); }
/** * * nfs_read_core_conf: read the configuration ite; for the worker theads. * * Reads the configuration ite; for the worker theads. * * @param in_config [IN] configuration file handle * @param pparam [OUT] read parameters * * @return 0 if ok, -1 if failed, 1 is stanza is not there. * */ int nfs_read_core_conf(config_file_t in_config, nfs_core_parameter_t * pparam) { int var_max; int var_index; int err; char *key_name; char *key_value; config_item_t block; /* Is the config tree initialized ? */ if(in_config == NULL || pparam == NULL) return CACHE_INODE_INVALID_ARGUMENT; /* Get the config BLOCK */ if((block = config_FindItemByName(in_config, CONF_LABEL_NFS_CORE)) == NULL) { LogDebug(COMPONENT_CONFIG, "Cannot read item \"%s\" from configuration file", CONF_LABEL_NFS_CORE); return 1; } else if(config_ItemType(block) != CONFIG_ITEM_BLOCK) { /* Expected to be a block */ LogDebug(COMPONENT_CONFIG, "Item \"%s\" is expected to be a block", CONF_LABEL_NFS_CORE); return 1; } var_max = config_GetNbItems(block); for(var_index = 0; var_index < var_max; var_index++) { config_item_t item; item = config_GetItemByIndex(block, var_index); /* Get key's name */ if((err = config_GetKeyValue(item, &key_name, &key_value)) != 0) { LogCrit(COMPONENT_CONFIG, "Error reading key[%d] from section \"%s\" of configuration file.", var_index, CONF_LABEL_NFS_CORE); return CACHE_INODE_INVALID_ARGUMENT; } if(!strcasecmp(key_name, "Nb_Worker")) { pparam->nb_worker = atoi(key_value); } else if(!strcasecmp(key_name, "Nb_Call_Before_Queue_Avg")) { pparam->nb_call_before_queue_avg = atoi(key_value); } else if(!strcasecmp(key_name, "Nb_MaxConcurrentGC")) { pparam->nb_max_concurrent_gc = atoi(key_value); } else if(!strcasecmp(key_name, "DupReq_Expiration")) { pparam->expiration_dupreq = atoi(key_value); } else if(!strcasecmp(key_name, "Drop_IO_Errors")) { pparam->drop_io_errors = StrToBoolean(key_value); } else if(!strcasecmp(key_name, "Drop_Inval_Errors")) { pparam->drop_inval_errors = StrToBoolean(key_value); } else if(!strcasecmp(key_name, "Drop_Delay_Errors")) { pparam->drop_delay_errors = StrToBoolean(key_value); } else if(!strcasecmp(key_name, "NFS_Port")) { pparam->port[P_NFS] = (unsigned short)atoi(key_value); } else if(!strcasecmp(key_name, "MNT_Port")) { pparam->port[P_MNT] = (unsigned short)atoi(key_value); } else if(!strcasecmp(key_name, "NLM_Port")) { #ifdef _USE_NLM pparam->port[P_NLM] = (unsigned short)atoi(key_value); #endif } else if(!strcasecmp(key_name, "Rquota_Port")) { #ifdef _USE_QUOTA pparam->port[P_RQUOTA] = (unsigned short)atoi(key_value); #endif } else if(!strcasecmp(key_name, "NFS_Program")) { pparam->program[P_NFS] = atoi(key_value); } else if(!strcasecmp(key_name, "MNT_Program")) { pparam->program[P_MNT] = atoi(key_value); } else if(!strcasecmp(key_name, "NLM_Program")) { #ifdef _USE_NLM pparam->program[P_NLM] = atoi(key_value); #endif } else if(!strcasecmp(key_name, "Rquota_Program")) { #ifdef _USE_QUOTA pparam->program[P_RQUOTA] = atoi(key_value); #endif } else if(!strcasecmp(key_name, "NFS_Protocols")) { # define MAX_NFSPROTO 10 /* large enough !!! */ # define MAX_NFSPROTO_LEN 256 /* so is it !!! */ char *nfsvers_list[MAX_NFSPROTO]; int idx, count; /* reset nfs versions flags (clean defaults) */ pparam->core_options &= ~(CORE_OPTION_ALL_VERS); /* allocate nfs vers strings */ for(idx = 0; idx < MAX_NFSPROTO; idx++) nfsvers_list[idx] = (char *)Mem_Alloc(MAX_NFSPROTO_LEN); /* * Search for coma-separated list of nfsprotos */ count = nfs_ParseConfLine(nfsvers_list, MAX_NFSPROTO, key_value, find_comma, find_endLine); if(count < 0) { LogCrit(COMPONENT_CONFIG, "NFS_Protocols list too long (>%d)", MAX_NFSPROTO); /* free sec strings */ for(idx = 0; idx < MAX_NFSPROTO; idx++) Mem_Free((caddr_t) nfsvers_list[idx]); return -1; } /* add each Nfs protocol flag to the option field. */ for(idx = 0; idx < count; idx++) { if(!strcmp(nfsvers_list[idx], "4")) { pparam->core_options |= CORE_OPTION_NFSV4; } /* only NFSv4 is supported for the FSAL_PROXY */ #if ! defined( _USE_PROXY ) || defined ( _HANDLE_MAPPING ) else if(!strcmp(nfsvers_list[idx], "2")) { pparam->core_options |= CORE_OPTION_NFSV2; } else if(!strcmp(nfsvers_list[idx], "3")) { pparam->core_options |= CORE_OPTION_NFSV3; } #endif /* _USE_PROXY */ else { LogCrit(COMPONENT_CONFIG, "Invalid NFS Protocol \"%s\". Values can be: 2, 3, 4.", nfsvers_list[idx]); return -1; } } /* free sec strings */ for(idx = 0; idx < MAX_NFSPROTO; idx++) Mem_Free((caddr_t) nfsvers_list[idx]); /* check that at least one nfs protocol has been specified */ if((pparam->core_options & (CORE_OPTION_ALL_VERS)) == 0) { LogCrit(COMPONENT_CONFIG, "Empty NFS_Protocols list"); return -1; } } else if(!strcasecmp(key_name, "Bind_Addr")) { int rc; memset(&pparam->bind_addr.sin_addr, 0, sizeof(pparam->bind_addr.sin_addr)); rc = inet_pton(AF_INET, key_value, &pparam->bind_addr.sin_addr); if(rc <= 0) { /* Revert to INADDR_ANY in case of any error */ pparam->bind_addr.sin_addr.s_addr = INADDR_ANY; /* All the interfaces on the machine are used */ } } else if(!strcasecmp(key_name, "Core_Dump_Size")) { pparam->core_dump_size = atol(key_value); } else if(!strcasecmp(key_name, "Nb_Max_Fd")) { pparam->nb_max_fd = atoi(key_value); } else if(!strcasecmp(key_name, "Stats_File_Path")) { strncpy(pparam->stats_file_path, key_value, MAXPATHLEN); } else if(!strcasecmp(key_name, "Stats_Update_Delay")) { pparam->stats_update_delay = atoi(key_value); } else if(!strcasecmp(key_name, "Long_Processing_Threshold")) { pparam->long_processing_threshold = atoi(key_value); } else if(!strcasecmp( key_name, "TCP_Fridge_Expiration_Delay" ) ) { pparam->tcp_fridge_expiration_delay = atoi(key_value); } else if(!strcasecmp(key_name, "Dump_Stats_Per_Client")) { pparam->dump_stats_per_client = StrToBoolean(key_value); } else if(!strcasecmp(key_name, "Stats_Per_Client_Directory")) { strncpy(pparam->stats_per_client_directory, key_value, MAXPATHLEN); } else if(!strcasecmp(key_name, "FSAL_Shared_Library")) { strncpy(pparam->fsal_shared_library, key_value, MAXPATHLEN); } else { LogCrit(COMPONENT_CONFIG, "Unknown or unsettable key: %s (item %s)", key_name, CONF_LABEL_NFS_CORE); return -1; } } return 0; } /* nfs_read_core_conf */
/* ==================== ModPlug_LoadmodplugFile Load an modplug file into memory ==================== */ qboolean ModPlug_LoadModPlugFile (const char *filename, sfx_t *sfx) { unsigned char *data; fs_offset_t filesize; ModPlugFile *mf; modplug_stream_persfx_t* per_sfx; ModPlug_Settings s; if (!modplug_dll) return false; // Already loaded? if (sfx->fetcher != NULL) return true; // Load the file data = FS_LoadFile (filename, snd_mempool, false, &filesize); if (data == NULL) return false; if (developer_loading.integer >= 2) Con_Printf ("Loading ModPlug file \"%s\"\n", filename); qModPlug_GetSettings(&s); s.mFlags = MODPLUG_ENABLE_OVERSAMPLING | MODPLUG_ENABLE_NOISE_REDUCTION | MODPLUG_ENABLE_REVERB; s.mChannels = 2; s.mBits = 16; s.mFrequency = 44100; s.mResamplingMode = MODPLUG_RESAMPLE_SPLINE; s.mLoopCount = -1; qModPlug_SetSettings(&s); // Open it with the modplugFile API if (!(mf = qModPlug_Load (data, filesize))) { Con_Printf ("error while opening ModPlug file \"%s\"\n", filename); Mem_Free(data); return false; } #ifndef SND_MODPLUG_STATIC if(qModPlug_SetMasterVolume) #endif qModPlug_SetMasterVolume(mf, 512); // max volume, DP scales down! if (developer_loading.integer >= 2) Con_Printf ("\"%s\" will be streamed\n", filename); per_sfx = (modplug_stream_persfx_t *)Mem_Alloc (snd_mempool, sizeof (*per_sfx)); strlcpy(per_sfx->name, sfx->name, sizeof(per_sfx->name)); sfx->memsize += sizeof (*per_sfx); per_sfx->file = data; per_sfx->filesize = filesize; sfx->memsize += filesize; per_sfx->format.speed = 44100; // modplug always works at that rate per_sfx->format.width = 2; // We always work with 16 bits samples per_sfx->format.channels = 2; // stereo rulez ;) (MAYBE default to mono because Amiga MODs sound better then?) per_sfx->sfx = sfx; sfx->fetcher_data = per_sfx; sfx->fetcher = &modplug_fetcher; sfx->flags |= SFXFLAG_STREAMED; sfx->total_length = 2147384647; // they always loop sfx->loopstart = sfx->total_length; // modplug does it return true; }
/* ==================== ModPlug_FetchSound ==================== */ static const snd_buffer_t* ModPlug_FetchSound (void *sfxfetcher, void **chfetcherpointer, unsigned int *start, unsigned int nbsampleframes) { modplug_stream_perchannel_t* per_ch = (modplug_stream_perchannel_t *)*chfetcherpointer; modplug_stream_persfx_t* per_sfx = (modplug_stream_persfx_t *)sfxfetcher; snd_buffer_t* sb; int newlength, done, ret; unsigned int real_start; unsigned int factor; // If there's no fetcher structure attached to the channel yet if (per_ch == NULL) { size_t buff_len, memsize; snd_format_t sb_format; sb_format.speed = snd_renderbuffer->format.speed; sb_format.width = per_sfx->format.width; sb_format.channels = per_sfx->format.channels; buff_len = STREAM_BUFFER_SIZE(&sb_format); memsize = sizeof (*per_ch) - sizeof (per_ch->sb.samples) + buff_len; per_ch = (modplug_stream_perchannel_t *)Mem_Alloc (snd_mempool, memsize); // Open it with the modplugFile API per_ch->mf = qModPlug_Load(per_sfx->file, per_sfx->filesize); if (!per_ch->mf) { Con_Printf("error while reading ModPlug stream \"%s\"\n", per_sfx->name); Mem_Free (per_ch); return NULL; } #ifndef SND_MODPLUG_STATIC if(qModPlug_SetMasterVolume) #endif qModPlug_SetMasterVolume(per_ch->mf, 512); // max volume, DP scales down! per_ch->bs = 0; per_ch->sb_offset = 0; per_ch->sb.format = sb_format; per_ch->sb.nbframes = 0; per_ch->sb.maxframes = buff_len / (per_ch->sb.format.channels * per_ch->sb.format.width); *chfetcherpointer = per_ch; } real_start = *start; sb = &per_ch->sb; factor = per_sfx->format.width * per_sfx->format.channels; // If the stream buffer can't contain that much samples anyway if (nbsampleframes > sb->maxframes) { Con_Printf ("ModPlug_FetchSound: stream buffer too small (%u sample frames required)\n", nbsampleframes); return NULL; } // If the data we need has already been decompressed in the sfxbuffer, just return it if (per_ch->sb_offset <= real_start && per_ch->sb_offset + sb->nbframes >= real_start + nbsampleframes) { *start = per_ch->sb_offset; return sb; } newlength = (int)(per_ch->sb_offset + sb->nbframes) - real_start; // If we need to skip some data before decompressing the rest, or if the stream has looped if (newlength < 0 || per_ch->sb_offset > real_start) { unsigned int time_start; unsigned int modplug_start; /* MODs loop on their own, so any position is valid! if (real_start > (unsigned int)per_sfx->total_length) { Con_Printf ("ModPlug_FetchSound: asked for a start position after the end of the sfx! (%u > %u)\n", real_start, per_sfx->total_length); return NULL; } */ // We work with 200ms (1/5 sec) steps to avoid rounding errors time_start = real_start * 5 / snd_renderbuffer->format.speed; modplug_start = time_start * (1000 / 5); Con_DPrintf("warning: mod file needed to seek (to %d)\n", modplug_start); qModPlug_Seek(per_ch->mf, modplug_start); sb->nbframes = 0; real_start = (unsigned int) ((float)modplug_start / 1000 * snd_renderbuffer->format.speed); if (*start - real_start + nbsampleframes > sb->maxframes) { Con_Printf ("ModPlug_FetchSound: stream buffer too small after seek (%u sample frames required)\n", *start - real_start + nbsampleframes); per_ch->sb_offset = real_start; return NULL; } } // Else, move forward the samples we need to keep in the sound buffer else { memmove (sb->samples, sb->samples + (real_start - per_ch->sb_offset) * factor, newlength * factor); sb->nbframes = newlength; } per_ch->sb_offset = real_start; // We add more than one frame of sound to the buffer: // 1- to ensure we won't lose many samples during the resampling process // 2- to reduce calls to ModPlug_FetchSound to regulate workload newlength = (int)(per_sfx->format.speed*STREAM_BUFFER_FILL); if ((size_t) ((double) newlength * (double)sb->format.speed / (double)per_sfx->format.speed) + sb->nbframes > sb->maxframes) { Con_Printf ("ModPlug_FetchSound: stream buffer overflow (%u + %u = %u sample frames / %u)\n", (unsigned int) ((double) newlength * (double)sb->format.speed / (double)per_sfx->format.speed), sb->nbframes, (unsigned int) ((double) newlength * (double)sb->format.speed / (double)per_sfx->format.speed) + sb->nbframes, sb->maxframes); return NULL; } newlength *= factor; // convert from sample frames to bytes if(newlength > (int)sizeof(resampling_buffer)) newlength = sizeof(resampling_buffer); // Decompress in the resampling_buffer done = 0; while ((ret = qModPlug_Read (per_ch->mf, (char *)&resampling_buffer[done], (int)(newlength - done))) > 0) done += ret; if(done < newlength) { // Argh. We didn't get as many samples as we wanted. Probably // libmodplug forgot what mLoopCount==-1 means... basically, this means // we can't loop like this. Try to let DP fix it later... per_sfx->sfx->total_length = (real_start + ((size_t)done / (size_t)factor)); per_sfx->sfx->loopstart = 0; if(newlength != done) Con_DPrintf("ModPlug_Fetch: wanted: %d, got: %d\n", newlength, done); } Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format); *start = per_ch->sb_offset; return sb; }
void SCR_CaptureVideo_Ogg_BeginVideo(void) { cls.capturevideo.format = CAPTUREVIDEOFORMAT_OGG_VORBIS_THEORA; cls.capturevideo.formatextension = "ogv"; cls.capturevideo.videofile = FS_OpenRealFile(va("%s.%s", cls.capturevideo.basename, cls.capturevideo.formatextension), "wb", false); cls.capturevideo.endvideo = SCR_CaptureVideo_Ogg_EndVideo; cls.capturevideo.videoframes = SCR_CaptureVideo_Ogg_VideoFrames; cls.capturevideo.soundframe = SCR_CaptureVideo_Ogg_SoundFrame; cls.capturevideo.formatspecific = Mem_Alloc(tempmempool, sizeof(capturevideostate_ogg_formatspecific_t)); { LOAD_FORMATSPECIFIC_OGG(); int num, denom, i; ogg_page pg; ogg_packet pt, pt2, pt3; theora_comment tc; vorbis_comment vc; theora_info ti; format->serial1 = rand(); qogg_stream_init(&format->to, format->serial1); if(cls.capturevideo.soundrate) { do { format->serial2 = rand(); } while(format->serial1 == format->serial2); qogg_stream_init(&format->vo, format->serial2); } format->videopage.len = format->audiopage.len = 0; qtheora_info_init(&ti); ti.frame_width = cls.capturevideo.width; ti.frame_height = cls.capturevideo.height; ti.width = (ti.frame_width + 15) & ~15; ti.height = (ti.frame_height + 15) & ~15; //ti.offset_x = ((ti.width - ti.frame_width) / 2) & ~1; //ti.offset_y = ((ti.height - ti.frame_height) / 2) & ~1; for(i = 0; i < 2; ++i) { format->yuv[i].y_width = ti.width; format->yuv[i].y_height = ti.height; format->yuv[i].y_stride = ti.width; format->yuv[i].uv_width = ti.width / 2; format->yuv[i].uv_height = ti.height / 2; format->yuv[i].uv_stride = ti.width / 2; format->yuv[i].y = (unsigned char *) Mem_Alloc(tempmempool, format->yuv[i].y_stride * format->yuv[i].y_height); format->yuv[i].u = (unsigned char *) Mem_Alloc(tempmempool, format->yuv[i].uv_stride * format->yuv[i].uv_height); format->yuv[i].v = (unsigned char *) Mem_Alloc(tempmempool, format->yuv[i].uv_stride * format->yuv[i].uv_height); } format->yuvi = -1; // -1: no frame valid yet, write into 0 FindFraction(cls.capturevideo.framerate / cls.capturevideo.framestep, &num, &denom, 1001); ti.fps_numerator = num; ti.fps_denominator = denom; FindFraction(1 / vid_pixelheight.value, &num, &denom, 1000); ti.aspect_numerator = num; ti.aspect_denominator = denom; ti.colorspace = OC_CS_UNSPECIFIED; ti.pixelformat = OC_PF_420; ti.quick_p = true; // http://mlblog.osdir.com/multimedia.ogg.theora.general/2004-07/index.shtml ti.dropframes_p = false; ti.target_bitrate = cl_capturevideo_ogg_theora_bitrate.integer * 1000; ti.quality = cl_capturevideo_ogg_theora_quality.integer; if(ti.target_bitrate <= 0) { if(ti.quality < 0) { ti.target_bitrate = -1; ti.keyframe_data_target_bitrate = (unsigned int)-1; ti.quality = 63; } else { ti.target_bitrate = -1; ti.keyframe_data_target_bitrate = (unsigned int)-1; ti.quality = bound(0, ti.quality, 63); } } else { if(ti.quality < 0) { ti.target_bitrate = bound(45000, ti.target_bitrate, 2000000); ti.keyframe_data_target_bitrate = (int) (ti.target_bitrate * max(1, cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier.value)); ti.quality = -1; } else { ti.target_bitrate = bound(45000, ti.target_bitrate, 2000000); ti.keyframe_data_target_bitrate = (int) (ti.target_bitrate * max(1, cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier.value)); ti.quality = -1; } } // this -1 magic is because ti.keyframe_frequency and ti.keyframe_mindistance use different metrics ti.keyframe_frequency = bound(1, cl_capturevideo_ogg_theora_keyframe_maxinterval.integer, 1000); ti.keyframe_mindistance = bound(1, cl_capturevideo_ogg_theora_keyframe_mininterval.integer, (int) ti.keyframe_frequency) - 1; ti.noise_sensitivity = bound(0, cl_capturevideo_ogg_theora_noise_sensitivity.integer, 6); ti.sharpness = bound(0, cl_capturevideo_ogg_theora_sharpness.integer, 2); ti.keyframe_auto_threshold = bound(0, cl_capturevideo_ogg_theora_keyframe_auto_threshold.integer, 100); ti.keyframe_frequency_force = ti.keyframe_frequency; ti.keyframe_auto_p = (ti.keyframe_frequency != ti.keyframe_mindistance + 1); qtheora_encode_init(&format->ts, &ti); qtheora_info_clear(&ti); // vorbis? if(cls.capturevideo.soundrate) { qvorbis_info_init(&format->vi); qvorbis_encode_init_vbr(&format->vi, cls.capturevideo.soundchannels, cls.capturevideo.soundrate, bound(-1, cl_capturevideo_ogg_vorbis_quality.value, 10) * 0.099); qvorbis_comment_init(&vc); qvorbis_analysis_init(&format->vd, &format->vi); qvorbis_block_init(&format->vd, &format->vb); } qtheora_comment_init(&tc); /* create the remaining theora headers */ qtheora_encode_header(&format->ts, &pt); qogg_stream_packetin(&format->to, &pt); if (qogg_stream_pageout (&format->to, &pg) != 1) fprintf (stderr, "Internal Ogg library error.\n"); FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len); FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len); qtheora_encode_comment(&tc, &pt); qogg_stream_packetin(&format->to, &pt); qtheora_encode_tables(&format->ts, &pt); qogg_stream_packetin (&format->to, &pt); qtheora_comment_clear(&tc); if(cls.capturevideo.soundrate) { qvorbis_analysis_headerout(&format->vd, &vc, &pt, &pt2, &pt3); qogg_stream_packetin(&format->vo, &pt); if (qogg_stream_pageout (&format->vo, &pg) != 1) fprintf (stderr, "Internal Ogg library error.\n"); FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len); FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len); qogg_stream_packetin(&format->vo, &pt2); qogg_stream_packetin(&format->vo, &pt3); qvorbis_comment_clear(&vc); } for(;;) { int result = qogg_stream_flush (&format->to, &pg); if (result < 0) fprintf (stderr, "Internal Ogg library error.\n"); // TODO Host_Error if (result <= 0) break; FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len); FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len); } if(cls.capturevideo.soundrate) for(;;) { int result = qogg_stream_flush (&format->vo, &pg); if (result < 0) fprintf (stderr, "Internal Ogg library error.\n"); // TODO Host_Error if (result <= 0) break; FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len); FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len); } } }
/* ==================== R_BuildMeshForDecal creates mesh for decal on first rendering ==================== */ msurfmesh_t *R_DecalCreateMesh( decalinfo_t *decalinfo, decal_t *pdecal, msurface_t *surf ) { float *v; uint i, bufSize; qboolean createSTverts = false; int numVerts, numElems; byte *buffer; msurfmesh_t *mesh; if( pdecal->mesh ) { // already have mesh return pdecal->mesh; } v = R_DecalSetupVerts( pdecal, surf, pdecal->texture, &numVerts ); if( !numVerts ) return NULL; // probably this never happens // allocate mesh numElems = (numVerts - 2) * 3; bufSize = sizeof( msurfmesh_t ) + numVerts * sizeof( glvert_t ) + numElems * sizeof( word ); buffer = Mem_Alloc( cls.mempool, bufSize ); mesh = (msurfmesh_t *)buffer; buffer += sizeof( msurfmesh_t ); mesh->numVerts = numVerts; mesh->numElems = numElems; // setup pointers mesh->verts = (glvert_t *)buffer; buffer += numVerts * sizeof( glvert_t ); mesh->elems = (word *)buffer; buffer += numElems * sizeof( word ); mesh->surf = surf; // NOTE: meshchains can be linked with one surface // create indices for( i = 0; i < mesh->numVerts - 2; i++ ) { mesh->elems[i*3+0] = 0; mesh->elems[i*3+1] = i + 1; mesh->elems[i*3+2] = i + 2; } #ifdef __arm__ float inv_w = 1.0f / surf->texinfo->texture->width; float inv_h = 1.0f / surf->texinfo->texture->height; #endif // fill the mesh for( i = 0; i < numVerts; i++, v += VERTEXSIZE ) { glvert_t *out = &mesh->verts[i]; VectorCopy( v, out->vertex ); VectorCopy( decalinfo->m_Basis[0], out->tangent ); VectorCopy( decalinfo->m_Basis[1], out->binormal ); VectorCopy( decalinfo->m_Basis[2], out->normal ); out->stcoord[0] = v[3]; out->stcoord[1] = v[4]; out->lmcoord[0] = v[5]; out->lmcoord[1] = v[6]; out->sccoord[0] = (( DotProduct( v , surf->texinfo->vecs[0] ) + surf->texinfo->vecs[0][3] ) #ifdef __arm__ * inv_w ); #else / surf->texinfo->texture->width ); #endif out->sccoord[1] = (( DotProduct( v , surf->texinfo->vecs[1] ) + surf->texinfo->vecs[1][3] ) #ifdef __arm__ * inv_h ); #else / surf->texinfo->texture->height );
/* ==================== CL_AllocRemapInfo Allocate new remap info per entity and make copy of remap textures ==================== */ void CL_AllocRemapInfo( int topcolor, int bottomcolor ) { remap_info_t *info; studiohdr_t *phdr; mstudiotexture_t *src, *dst; int i, size; if( !RI.currententity ) return; i = ( RI.currententity == &clgame.viewent ) ? clgame.maxEntities : RI.currententity->curstate.number; if( !RI.currentmodel || RI.currentmodel->type != mod_studio ) { // entity has changed model by another type, release remap info if( clgame.remap_info[i] ) { CL_FreeRemapInfo( clgame.remap_info[i] ); clgame.remap_info[i] = NULL; } return; // missed or hide model, ignore it } // model doesn't contains remap textures if( RI.currentmodel->numtextures <= 0 ) { // entity has changed model with no remap textures if( clgame.remap_info[i] ) { CL_FreeRemapInfo( clgame.remap_info[i] ); clgame.remap_info[i] = NULL; } return; } phdr = (studiohdr_t *)Mod_Extradata( RI.currentmodel ); if( !phdr ) return; // missed header ??? src = (mstudiotexture_t *)(((byte *)phdr) + phdr->textureindex); dst = (clgame.remap_info[i] ? clgame.remap_info[i]->ptexture : NULL); // NOTE: we must copy all the structures 'mstudiotexture_t' for easy access when model is rendering if( !CL_CmpStudioTextures( phdr->numtextures, src, dst ) || clgame.remap_info[i]->model != RI.currentmodel ) { // this code catches studiomodel change with another studiomodel with remap textures // e.g. playermodel 'barney' with playermodel 'gordon' if( clgame.remap_info[i] ) CL_FreeRemapInfo( clgame.remap_info[i] ); // free old info size = sizeof( remap_info_t ) + ( sizeof( mstudiotexture_t ) * phdr->numtextures ); info = clgame.remap_info[i] = Mem_Alloc( clgame.mempool, size ); info->ptexture = (mstudiotexture_t *)(info + 1); // textures are immediately comes after remap_info } else { // studiomodel is valid, nothing to change return; } info->numtextures = phdr->numtextures; info->model = RI.currentmodel; info->topcolor = topcolor; info->bottomcolor = bottomcolor; src = (mstudiotexture_t *)(((byte *)phdr) + phdr->textureindex); dst = info->ptexture; // copy unchanged first Q_memcpy( dst, src, sizeof( mstudiotexture_t ) * phdr->numtextures ); // make local copies for remap textures for( i = 0; i < info->numtextures; i++ ) { if( dst[i].flags & STUDIO_NF_COLORMAP ) CL_DuplicateTexture( &dst[i], topcolor, bottomcolor ); } }
/* * CM_LoadMap * Loads in the map and all submodels * * for spawning a server with no map at all, call like this: * CM_LoadMap( "", qfalse, &checksum ); // no real map */ cmodel_t *CM_LoadMap( cmodel_state_t *cms, const char *name, qboolean clientload, unsigned *checksum ) { int length; unsigned *buf; char *header; const modelFormatDescr_t *descr; bspFormatDesc_t *bspFormat = NULL; assert( cms ); assert( name && strlen( name ) < MAX_CONFIGSTRING_CHARS ); assert( checksum ); cms->map_clientload = clientload; if( !strcmp( cms->map_name, name ) && ( clientload || !Cvar_Value( "flushmap" ) ) ) { *checksum = cms->checksum; if( !clientload ) { memset( cms->map_areaportals, 0, cms->numareas * cms->numareas * sizeof( *cms->map_areaportals ) ); CM_FloodAreaConnections( cms ); } return cms->map_cmodels; // still have the right version } CM_Clear( cms ); if( !name || !name[0] ) { cms->numleafs = 1; cms->numcmodels = 2; *checksum = 0; return cms->map_cmodels; // cinematic servers won't have anything at all } // // load the file // length = FS_LoadFile( name, ( void ** )&buf, NULL, 0 ); if( !buf ) Com_Error( ERR_DROP, "Couldn't load %s", name ); cms->checksum = Com_MD5Digest32( ( const qbyte * )buf, length ); *checksum = cms->checksum; // call the apropriate loader descr = Q_FindFormatDescriptor( cm_supportedformats, ( const qbyte * )buf, (const bspFormatDesc_t **)&bspFormat ); if( !descr ) Com_Error( ERR_DROP, "CM_LoadMap: unknown fileid for %s", name ); if( !bspFormat ) Com_Error( ERR_DROP, "CM_LoadMap: %s: unknown bsp format" ); // copy header into temp variable to be saveed in a cvar header = Mem_TempMalloc( descr->headerLen + 1 ); memcpy( header, buf, descr->headerLen ); header[descr->headerLen] = '\0'; // store map format description in cvars Cvar_ForceSet( "cm_mapHeader", header ); Cvar_ForceSet( "cm_mapVersion", va( "%i", LittleLong( *((int *)((qbyte *)buf + descr->headerLen)) ) ) ); Mem_TempFree( header ); descr->loader( cms, NULL, buf, bspFormat ); CM_InitBoxHull( cms ); CM_InitOctagonHull( cms ); if( cms->numareas ) { cms->map_areas = Mem_Alloc( cms->mempool, cms->numareas * sizeof( *cms->map_areas ) ); cms->map_areaportals = Mem_Alloc( cms->mempool, cms->numareas * cms->numareas * sizeof( *cms->map_areaportals ) ); memset( cms->map_areaportals, 0, cms->numareas * cms->numareas * sizeof( *cms->map_areaportals ) ); CM_FloodAreaConnections( cms ); } memset( cms->nullrow, 255, MAX_CM_LEAFS / 8 ); Q_strncpyz( cms->map_name, name, sizeof( cms->map_name ) ); return cms->map_cmodels; }
/* ================ FS_Init ================ */ void CFileSystem::Init() { mpLowLevelFileSystem->Init(); tStringList dirs; bool hasDefaultDir = false; int i; // Init memory fs_mempool = Mem_AllocPool( "FileSystem Pool" ); // add a path separator to the end of the basedir if it lacks one if( fs_basedir[0] && fs_basedir[Q_strlen(fs_basedir) - 1] != '/' && fs_basedir[Q_strlen(fs_basedir) - 1] != '\\' ) Q_strncat( fs_basedir, "/", sizeof( fs_basedir )); fs_searchpaths = NULL; mpConsole->AddCommand("fs_rescan", FS_Rescan_f, "rescan filesystem search pathes"); mpConsole->AddCommand("fs_path", FS_Path_f, "show filesystem search pathes"); mpConsole->AddCommand("fs_clearpaths", FS_ClearPaths_f, "clear filesystem search pathes"); // ignore commandlineoption "-game" for other stuff if( host.type == HOST_NORMAL || host.type == HOST_DEDICATED ) { stringlistinit( &dirs ); listdirectory( &dirs, "./" ); stringlistsort( &dirs ); SI.numgames = 0; if( !Sys_GetParmFromCmdLine( "-game", gs_basedir )) Q_strcpy( gs_basedir, SI.ModuleName ); // default dir if( FS_CheckNastyPath( gs_basedir, true )) { DevMsg( D_ERROR, "FS_Init: invalid game directory \"%s\"\n", gs_basedir ); Q_strcpy( gs_basedir, SI.ModuleName ); // default dir }; // validate directories for( i = 0; i < dirs.numstrings; i++ ) { if( !Q_stricmp( SI.ModuleName, dirs.strings[i] )) hasDefaultDir = true; if( !Q_stricmp( gs_basedir, dirs.strings[i] )) break; } if( i == dirs.numstrings ) { DevMsg( D_INFO, "FS_Init: game directory \"%s\" not exist\n", gs_basedir ); if(hasDefaultDir) Q_strncpy( gs_basedir, SI.ModuleName, sizeof( gs_basedir )); // default dir }; // build list of game directories here FS_AddGameDirectory( "./", 0 ); for( i = 0; i < dirs.numstrings; i++ ) { if(!mpLowLevelFileSystem->SysFolderExists( dirs.strings[i] ) || (!Q_stricmp( dirs.strings[i], ".." ) && !fs_ext_path )) continue; if( !SI.games[SI.numgames] ) SI.games[SI.numgames] = (gameinfo_t *)Mem_Alloc( fs_mempool, sizeof( gameinfo_t )); if( FS_ParseGameInfo( dirs.strings[i], SI.games[SI.numgames] )) SI.numgames++; // added }; stringlistfreecontents( &dirs ); }; MsgDev( D_NOTE, "FS_Init: done\n" ); };
/* * TV_Init * * Only called at plat.exe startup, not for each game */ void TV_Init( void ) { Com_Printf( "Initializing " APPLICATION " TV server\n" ); tv_mempool = Mem_AllocPool( NULL, "TV" ); TV_AddCommands(); Cvar_Get( "protocol", va( "%i", APP_PROTOCOL_VERSION ), CVAR_SERVERINFO | CVAR_NOSET ); Cvar_Get( "gamename", Cvar_String( "gamename" ), CVAR_SERVERINFO | CVAR_NOSET ); tv_password = Cvar_Get( "tv_password", "", 0 ); tv_ip = Cvar_Get( "tv_ip", "", CVAR_ARCHIVE | CVAR_NOSET ); tv_port = Cvar_Get( "tv_port", va( "%i", PORT_TV_SERVER ), CVAR_ARCHIVE | CVAR_NOSET ); tv_ip6 = Cvar_Get( "tv_ip6", "::", CVAR_ARCHIVE | CVAR_NOSET ); tv_port6 = Cvar_Get( "tv_port6", va( "%i", PORT_TV_SERVER ), CVAR_ARCHIVE | CVAR_NOSET ); #ifdef TCP_ALLOW_TVCONNECT tv_udp = Cvar_Get( "tv_udp", "1", CVAR_SERVERINFO | CVAR_NOSET ); tv_tcp = Cvar_Get( "tv_tcp", "1", CVAR_SERVERINFO | CVAR_NOSET ); #else tv_udp = Cvar_Get( "tv_udp", "1", CVAR_NOSET ); #endif #ifndef TCP_ALLOW_TVCONNECT Cvar_FullSet( "tv_tcp", "0", CVAR_READONLY, true ); #endif tv_reconnectlimit = Cvar_Get( "tv_reconnectlimit", "3", CVAR_ARCHIVE ); tv_timeout = Cvar_Get( "tv_timeout", "125", 0 ); tv_zombietime = Cvar_Get( "tv_zombietime", "2", 0 ); tv_name = Cvar_Get( "tv_name", APPLICATION "[TV]", CVAR_SERVERINFO | CVAR_ARCHIVE ); tv_compresspackets = Cvar_Get( "tv_compresspackets", "1", 0 ); tv_maxclients = Cvar_Get( "tv_maxclients", "32", CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_NOSET ); tv_maxmvclients = Cvar_Get( "tv_maxmvclients", "4", CVAR_ARCHIVE | CVAR_SERVERINFO | CVAR_NOSET ); tv_public = Cvar_Get( "tv_public", "1", CVAR_ARCHIVE | CVAR_SERVERINFO ); tv_rcon_password = Cvar_Get( "tv_rcon_password", "", 0 ); tv_autorecord = Cvar_Get( "tv_autorecord", "", CVAR_ARCHIVE ); tv_lobbymusic = Cvar_Get( "tv_lobbymusic", "", CVAR_ARCHIVE ); tv_masterservers = Cvar_Get( "tv_masterservers", DEFAULT_MASTER_SERVERS_IPS, CVAR_LATCH ); tv_masterservers_steam = Cvar_Get( "tv_masterservers_steam", DEFAULT_MASTER_SERVERS_STEAM_IPS, CVAR_LATCH ); // flood control tv_floodprotection_messages = Cvar_Get( "tv_floodprotection_messages", "10", 0 ); tv_floodprotection_messages->modified = true; tv_floodprotection_seconds = Cvar_Get( "tv_floodprotection_seconds", "4", 0 ); tv_floodprotection_seconds->modified = true; tv_floodprotection_penalty = Cvar_Get( "tv_floodprotection_delay", "20", 0 ); tv_floodprotection_penalty->modified = true; if( tv_maxclients->integer < 0 ) Cvar_ForceSet( "tv_maxclients", "0" ); if( tv_maxclients->integer ) { tvs.clients = ( client_t * )Mem_Alloc( tv_mempool, sizeof( client_t ) * tv_maxclients->integer ); } else { tvs.clients = NULL; } tvs.lobby.spawncount = rand(); tvs.lobby.snapFrameTime = 100; // IPv4 if( !NET_StringToAddress( tv_ip->string, &tvs.address ) ) Com_Error( ERR_FATAL, "Couldn't understand address of tv_ip cvar: %s\n", NET_ErrorString() ); NET_SetAddressPort( &tvs.address, tv_port->integer ); if( tv_udp->integer ) { if( !NET_OpenSocket( &tvs.socket_udp, SOCKET_UDP, &tvs.address, true ) ) { Com_Printf( "Error: Couldn't open UDP socket: %s\n", NET_ErrorString() ); Cvar_ForceSet( tv_udp->name, "0" ); } } // IPv6 if( !NET_StringToAddress( tv_ip6->string, &tvs.addressIPv6 ) ) Com_Error( ERR_FATAL, "Couldn't understand address of tv_ip6 cvar: %s\n", NET_ErrorString() ); NET_SetAddressPort( &tvs.addressIPv6, tv_port6->integer ); if( tvs.addressIPv6.type != NA_NOTRANSMIT ) { if( !NET_OpenSocket( &tvs.socket_udp6, SOCKET_UDP, &tvs.addressIPv6, true ) ) { Com_Printf( "Error: Couldn't open UDP6 socket: %s\n", NET_ErrorString() ); } } #ifdef TCP_ALLOW_TVCONNECT if( tv_tcp->integer ) { bool err = true; if( !NET_OpenSocket( &tvs.socket_tcp, SOCKET_TCP, &tvs.address, true ) ) { Com_Printf( "Error: Couldn't open TCP socket: %s\n", NET_ErrorString() ); } else { NET_SetSocketNoDelay( &tvs.socket_tcp, 1 ); if( !NET_Listen( &tvs.socket_tcp ) ) { Com_Printf( "Error: Couldn't listen to TCP socket: %s\n", NET_ErrorString() ); } else { err = false; } } if( tvs.addressIPv6.type != NA_NOTRANSMIT ) { if( !NET_OpenSocket( &tvs.socket_tcp6, SOCKET_TCP, &tvs.addressIPv6, true ) ) { Com_Printf( "Error: Couldn't open TCP6 socket: %s\n", NET_ErrorString() ); } else { NET_SetSocketNoDelay( &tvs.socket_tcp6, 1 ); if( !NET_Listen( &tvs.socket_tcp6 ) ) { Com_Printf( "Error: Couldn't listen to TCP6 socket: %s\n", NET_ErrorString() ); } else { err = false; } } } if( err ) { Cvar_ForceSet( tv_tcp->name, "0" ); } } #endif TV_Downstream_InitMaster(); }
/* ================== CIN_LoadPCX TODO: fill in cinematic_t ================== */ static bool CIN_LoadPCX (cinematic_t *cin, const char *name, int flags){ pcxHeader_t *header; byte *data, *pcxData; byte *in, *out; byte palette[768]; int x, y, length; int dataByte, runLength; // Load the file length = FS_ReadFile(name, (void **)&data); if (!data) return false; // Parse the PCX header header = (pcxHeader_t *)data; header->xMin = LittleShort(header->xMin); header->yMin = LittleShort(header->yMin); header->xMax = LittleShort(header->xMax); header->yMax = LittleShort(header->yMax); header->hRes = LittleShort(header->hRes); header->vRes = LittleShort(header->vRes); header->bytesPerLine = LittleShort(header->bytesPerLine); header->paletteType = LittleShort(header->paletteType); in = &header->data; if (header->manufacturer != 0x0A || header->version != 5 || header->encoding != 1) Com_Error(ERR_DROP, "CIN_LoadPCX: invalid PCX header (%s)\n", name); if (header->bitsPerPixel != 8 || header->colorPlanes != 1) Com_Error(ERR_DROP, "CIN_LoadPCX: only 8 bit PCX images supported (%s)\n", name); if (header->xMax <= 0 || header->yMax <= 0 || header->xMax >= 640 || header->yMax >= 480) Com_Error(ERR_DROP, "CIN_LoadPCX: bad image size (%i x %i) (%s)\n", header->xMax, header->yMax, name); Mem_Copy(palette, (byte *)data + length - 768, 768); pcxData = out = (byte *)Mem_Alloc((header->xMax+1) * (header->yMax+1) * 4, TAG_TEMPORARY); for (y = 0; y <= header->yMax; y++){ for (x = 0; x <= header->xMax; ){ dataByte = *in++; if ((dataByte & 0xC0) == 0xC0){ runLength = dataByte & 0x3F; dataByte = *in++; } else runLength = 1; while (runLength-- > 0){ out[0] = palette[dataByte*3+0]; out[1] = palette[dataByte*3+1]; out[2] = palette[dataByte*3+2]; out[3] = 255; out += 4; x++; } } } if (in - data > length){ Com_DPrintf(S_COLOR_YELLOW "CIN_LoadPCX: PCX file was malformed (%s)\n", name); FS_FreeFile(data); Mem_Free(pcxData); pcxData = NULL; return false; } // Free the file data FS_FreeFile(data); // Fill it in cin->playing = true; cin->isRoQ = false; Str_Copy(cin->name, name, sizeof(cin->name)); cin->flags = flags; cin->file = 0; cin->size = 0; cin->offset = 0; cin->startTime = 0; cin->frameRate = 0; cin->frameCount = -1; // Resample video if needed CIN_ResampleVideo(cin); return true; }
int main() { assert(Mem_Init(4096) == 0); void *ptr[4]; void *first, *best, *worst; assert(Mem_Alloc(8, FIRSTFIT) != NULL); ptr[0] = Mem_Alloc(40, FIRSTFIT); assert(Mem_Alloc(8, FIRSTFIT) != NULL); ptr[1] = Mem_Alloc(56, FIRSTFIT); assert(Mem_Alloc(8, FIRSTFIT) != NULL); first = Mem_Alloc(256, FIRSTFIT); assert(Mem_Alloc(8, FIRSTFIT) != NULL); best = Mem_Alloc(128, FIRSTFIT); assert(Mem_Alloc(8, FIRSTFIT) != NULL); ptr[2] = Mem_Alloc(32, FIRSTFIT); assert(Mem_Alloc(8, FIRSTFIT) != NULL); worst = Mem_Alloc(512, FIRSTFIT); assert(Mem_Alloc(8, FIRSTFIT) != NULL); ptr[3] = Mem_Alloc(32, FIRSTFIT); Mem_Dump(); int count = 0; while(Mem_Alloc(128, FIRSTFIT) != NULL) { printf("%d\n", count); count++; Mem_Dump(); } assert(m_error == E_NO_SPACE); assert(Mem_Free(ptr[2]) == 0); assert(Mem_Free(ptr[3]) == 0); Mem_Dump(); assert(Mem_Free(first) == 0); Mem_Dump(); assert(Mem_Free(best) == 0); Mem_Dump(); assert(Mem_Free(ptr[1]) == 0); Mem_Dump(); assert(Mem_Free(worst) == 0); Mem_Dump(); assert(Mem_Free(ptr[0]) == 0); Mem_Dump(); assert(Mem_Alloc(128, BESTFIT) == best); Mem_Dump(); exit(0); }