Example #1
0
void TextComparator::Split(Array<TextSection>& dest, int start1, int end1, int start2, int end2) const
{
	ASSERT(start1 <= end1 && start2 <= end2);
	while(start1 < end1 && start2 < end2) {
		int new1 = -1, new2 = -1, count = 0;
		for(int i = start1; i + count < end1; i++)
			if(Find(i, end1, start2, end2, new2, count))
				new1 = i;
		if(count == 0)
			break; // no match at all
		ASSERT(new1 >= start1 && new1 + count <= end1);
		ASSERT(new2 >= start2 && new2 + count <= end2);
		dest.Add(TextSection(new1, count, new2, count, true));
		if(new1 - start1 >= end1 - new1 - count) { // head is longer - recurse for tail
			Split(dest, new1 + count, end1, new2 + count, end2);
			end1 = new1;
			end2 = new2;
		}
		else { // tail is longer - recurse for head
			Split(dest, start1, new1, start2, new2);
			start1 = new1 + count;
			start2 = new2 + count;
		}
		ASSERT(start1 <= end1 && start2 <= end2);
	}
	if(start1 < end1 || start2 < end2)
		dest.Add(TextSection(start1, end1 - start1, start2, end2 - start2, false));
}
Array *Array::SortArrayElementsByKey() {
    Array *newARRAY = new(AllocArray(PIF))Array(PIF);

#ifdef STDMAP_KEYS
    if (Keys) {
        KeyMap::iterator end = Keys->end();
        AnsiString key;
        ARRAY_COUNT_TYPE i = 0;
        for (KeyMap::iterator iter = Keys->begin(); iter != end; ++iter) {
            newARRAY->Add(Get(iter->second));
            key = (char *)iter->first;
            newARRAY->AddKey(&key, i++);
        }
    }
#else
    CleanIndex(true);
    for (ARRAY_COUNT_TYPE i = 0; i < KeysCount; i++) {
        AnsiString key = Keys [i].KEY;
        newARRAY->Add(Get(Keys [i].index));
        newARRAY->AddKey(&key, i);
    }
#endif

    return newARRAY;
}
Example #3
0
    TEST_FIXTURE(ConstructTestArray, Operator_Add_Container_NoResize) {
        Arr.Clear();
        Arr.SetResizeCount(0U);
        Arr.Resize(2U, false, false);

        // constructing container for adding
        Array<int> AppendArr;
        AppendArr.Add(1);
        AppendArr.Add(2);
        AppendArr.Add(3);
        AppendArr.Add(4);

        // adds elements until Arr is full
        Arr += AppendArr;
        CHECK_EQUAL(2U, Arr.GetNumOfElements());
        CHECK_EQUAL(1, Arr.Get(0U));
        CHECK_EQUAL(2, Arr.Get(1U));

        // no elements added, Arr is full
        Arr+=AppendArr;
        CHECK_EQUAL(2U, Arr.GetNumOfElements());

        // set resizecount back to default
        Arr.SetResizeCount(10U);
    }
Example #4
0
void Script::GetAssociatedFilenames(Array<String> &lstFilenames)
{
	// We want to have a list of script filenames which were included within this script
	// -> It appears that there's no "easy" way in Lua to get this kind of information :/

	// Contains "Application", "Interaction" and so on (no final filenames)
	Array<String> lstRequire;

	// Get a list of loaded "require"-files
	{ // -> The files loaded within a Lua script by using "require" can be accessed by using the
		//    global control table variable "_LOADED". See http://www.lua.org/pil/8.1.html for details.
		lua_getfield(m_pLuaState, LUA_REGISTRYINDEX, "_LOADED");
		if (lua_istable(m_pLuaState, -1)) {
			lua_pushnil(m_pLuaState);
			while (lua_next(m_pLuaState, -2)) {
				if (lua_isstring(m_pLuaState, -2))
					lstRequire.Add(lua_tostring(m_pLuaState, -2));
				lua_pop(m_pLuaState, 1);
			}
		}

		// Pop the table from the Lua stack
		lua_pop(m_pLuaState, 1);
	}

	// Get the content of "package.path" used by "require" to search for a Lua loader
	// -> The content looks like "?.lua;C:\SomePath\?.lua;"
	const String sPackagePath = GetGlobalVariable("path", "package");

	// Iterate over the "require"-list
	const String sToReplace = "?.";
	for (uint32 i=0; i<lstRequire.GetNumOfElements(); i++) {
		// Get the current "require"
		const String sRequire = lstRequire[i] + '.';

		// Get the index of the first ";" within the package path
		int nPreviousIndex = 0;
		int nIndex = sPackagePath.IndexOf(';');
		while (nIndex>-1) {
			// Get current package search path, we now have e.g. "C:\SomePath\?.lua"
			String sFilename = sPackagePath.GetSubstring(nPreviousIndex, nIndex-nPreviousIndex);

			// Replace "?." with the "require"-name
			sFilename.Replace(sToReplace, sRequire);

			// Does this file exist?
			if (File(sFilename).Exists()) {
				// We found a match!
				lstFilenames.Add(sFilename);

				// Get us out of the while-loop
				nIndex = -1;
			} else {
				// Get the index of the next ";" within the package path
				nPreviousIndex = nIndex + 1;
				nIndex = sPackagePath.IndexOf(';', nPreviousIndex);
			}
		}
	}
}
Example #5
0
bool JPCInstance::QueryOptions( Array<ImageOptions>& imageOptions, Array<void*>& formatOptions )
{
   m_queriedOptions = true;

   // Format-independent options

   ImageOptions options;
   if ( !imageOptions.IsEmpty() )
      options = *imageOptions;

   // Format-specific options

   JPEG2000FormatOptions* jpc = nullptr;

   if ( !formatOptions.IsEmpty() )
   {
      JPEG2000FormatOptions* o = JPEG2000FormatOptions::FromGenericDataBlock( *formatOptions );
      if ( o != nullptr )
         jpc = o;
   }

   bool reusedFormatOptions = jpc != nullptr;
   if ( !reusedFormatOptions )
      jpc = new JPEG2000FormatOptions( IsCodeStream() );

   if ( !IsCodeStream() )
   {
      // Override embedding options, if requested.

      JP2Format::EmbeddingOverrides overrides = JP2Format::DefaultEmbeddingOverrides();

      if ( overrides.overrideICCProfileEmbedding )
         options.embedICCProfile = overrides.embedICCProfiles;
   }

   JPEG2000OptionsDialog dlg( options, m_jp2Options, IsCodeStream() );

   if ( dlg.Execute() == StdDialogCode::Ok )
   {
      jpc->options = dlg.jp2Options;

      if ( imageOptions.IsEmpty() )
         imageOptions.Add( dlg.options );
      else
         *imageOptions = dlg.options;

      if ( formatOptions.IsEmpty() )
         formatOptions.Add( (void*)jpc );
      else
         *formatOptions = (void*)jpc;

      return true;
   }

   if ( !reusedFormatOptions )
      delete jpc;

   return false;
}
Example #6
0
bool JPEGInstance::QueryOptions( Array<ImageOptions>& imageOptions, Array<void*>& formatOptions )
{
   m_queriedOptions = true;

   /*
    * Format-independent options
    */
   ImageOptions options;
   if ( !imageOptions.IsEmpty() )
      options = *imageOptions;

   /*
    * Format-specific options
    */
   JPEGFormat::FormatOptions* jpeg = nullptr;

   if ( !formatOptions.IsEmpty() )
   {
      JPEGFormat::FormatOptions* o = JPEGFormat::FormatOptions::FromGenericDataBlock( *formatOptions );
      if ( o != nullptr )
         jpeg = o;
   }

   bool reusedFormatOptions = jpeg != nullptr;
   if ( !reusedFormatOptions )
      jpeg = new JPEGFormat::FormatOptions;

   /*
    * Override embedding options, if requested.
    */
   JPEGFormat::EmbeddingOverrides overrides = JPEGFormat::DefaultEmbeddingOverrides();

   if ( overrides.overrideICCProfileEmbedding )
      options.embedICCProfile = overrides.embedICCProfiles;

   JPEGOptionsDialog dlg( options, jpeg->options );

   if ( dlg.Execute() == StdDialogCode::Ok )
   {
      jpeg->options = dlg.jpegOptions;

      if ( imageOptions.IsEmpty() )
         imageOptions.Add( dlg.options );
      else
         *imageOptions = dlg.options;

      if ( formatOptions.IsEmpty() )
         formatOptions.Add( (void*)jpeg );
      else
         *formatOptions = (void*)jpeg;

      return true;
   }

   if ( !reusedFormatOptions )
      delete jpeg;

   return false;
}
Example #7
0
void CreateDurations(void)
{
  if(GlobalRhythmSixteenth) Durations.Add() = Ratio(1, 16);
  if(GlobalRhythmTripletEighth) Durations.Add() = Ratio(1, 12);
  if(GlobalRhythmEighth) Durations.Add() = Ratio(1, 8);
  if(GlobalRhythmTripletQuarter) Durations.Add() = Ratio(1, 6);
  if(GlobalRhythmQuarter) Durations.Add() = Ratio(1, 4);
}
Example #8
0
void JacobianIKFixedPoint::GetResults(Array<float>& results)
{	
	// retrieve the node's world position
	Vector3 position = mNode->GetWorldPos();

	// the constraint result is the node position
	results.Add(position.x);
	results.Add(position.y); // ahm yes ... (Benny)
	results.Add(position.z);
}
Example #9
0
bool CreateBinkFix(BINK* bnk)
{
	char Buffer[256];
	GothicReadIniString("GAME", "scaleVideos", "1", Buffer, 256, "Gothic.ini");
	scaleVideos = atoi(Buffer);

	if(!bnk || !scaleVideos)
		return false;

	POINT GothicWindowSize = { 0, 0 };
	if(!GetGothicWindowSize(GothicWindowSize))
		return false;

	uInt Index = GetBinkIndex(bnk);
	if(!Index)
	{
		BinkFix& Fix = Binks.Add();
		Fix.Image = Fix.Resized = NULL;

		Fix.Bink = bnk;
		Fix.SrcWidth = bnk->Width;
		Fix.SrcHeight = bnk->Height;
		Fix.DstWidth = GothicWindowSize.x;
		Fix.DstHeight = GothicWindowSize.y;

		ValidateAspect(Fix, 0, 0);

		bnk->Width = Fix.DstWidth;
		bnk->Height = Fix.DstHeight;
	}
	return true;
}
Example #10
0
void RichPara::PackParts(Stream& out, const RichPara::CharFormat& chrstyle,
                         const Array<RichPara::Part>& part, CharFormat& cf,
                         Array<RichObject>& obj) const
{
	for(int i = 0; i < part.GetCount(); i++) {
		const Part& p = part[i];
		Charformat(out, cf, p.format, chrstyle);
		cf = p.format;
		if(p.field) {
			out.Put(FIELD);
			String s = ~p.field;
			out % s;
			s = p.fieldparam;
			out % s;
			StringStream oout;
			CharFormat subf = cf;
			PackParts(oout, chrstyle, p.fieldpart, subf, obj);
			s = oout;
			out % s;
		}
		else
		if(p.object) {
			obj.Add(p.object);
			out.Put(OBJECT);
		}
		else
			out.Put(ToUtf8(p.text));
	}
}
Example #11
0
void Ctrl::GetWorkArea(Array<Rect>& rc)
{
	GuiLock __;
	GdkScreen *s = gdk_screen_get_default();
	int n = gdk_screen_get_n_monitors(s);
	rc.Clear();
	Vector<int> netwa;
	for(int i = 0; i < n; i++) {
		GdkRectangle rr;
		Rect r;
#if GTK_CHECK_VERSION (3, 3, 5) // U++ does not work with gtk3 yet, but be prepared
		gdk_screen_get_monitor_workarea(s, i, &rr);
		r = RectC(r.x, r.y, r.width, r.height);
#else
		gdk_screen_get_monitor_geometry (s, i, &rr);
		r = RectC(rr.x, rr.y, rr.width, rr.height);
	#ifdef GDK_WINDOWING_X11
		if(i == 0)
			netwa = GetPropertyInts(gdk_screen_get_root_window(gdk_screen_get_default()),
			                        "_NET_WORKAREA");
		if(netwa.GetCount())
			r = r & RectC(netwa[0], netwa[1], netwa[2], netwa[3]);
	#endif
#endif
		rc.Add(r);
	}
}
Example #12
0
Array< Tuple2<String, String> > ODBCSession::EnumDSN()
{
	Array< Tuple2<String, String> > out;
	try {
		SQLHENV MIenv;
		SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &MIenv);
		SQLSetEnvAttr(MIenv, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);
		SQLRETURN ret;
		char l_dsn[256];
		char l_desc[256];
		short int l_len1,l_len2,l_next;
		l_next=SQL_FETCH_FIRST;
		while(SQL_SUCCEEDED(ret = SQLDataSources(MIenv, l_next, (SQLCHAR *)l_dsn, sizeof(l_dsn),
		                                         &l_len1, (SQLCHAR *)l_desc, sizeof(l_desc), &l_len2))) {
			Tuple2<String, String>& listdsn = out.Add();
			listdsn.a = l_dsn;
			listdsn.b = l_desc;
			l_next = SQL_FETCH_NEXT;
		}
	}
	catch(Exc e) {
		LLOG("ODBC::GetDSN->" << e);
	}
	return out;
}
Example #13
0
void Script::GetGlobalVariables(Array<String> &lstGlobalVariables, const String &sNamespace)
{
	// Is there a Lua state? If so, get a nested Lua table
	if (m_pLuaState && GetNestedTable(sNamespace)) {
		// Push the first key onto the Lua stack
		lua_pushnil(m_pLuaState);

		// Iterate through the Lua table
		while (lua_next(m_pLuaState, 1) != 0) {
			// Lua stack content: The 'key' is at index -2 and the 'value' at index -1

			// Check the 'key' type (at index -2) - must be a string
			if (lua_isstring(m_pLuaState, -2)) {
				// Check whether or not the 'value' (at index -1) is a global variable
				// (something like "_VERSION" is passing this test as well, but that's probably ok because it's just a Lua build in global variable)
				if (lua_isnumber(m_pLuaState, -1) || lua_isstring(m_pLuaState, -1)) {
					// Add the global variable to our list
					lstGlobalVariables.Add(lua_tostring(m_pLuaState, -2));
				}
			}

			// Next, please (removes 'value'; keeps 'key' for next iteration)
			lua_pop(m_pLuaState, 1);
		}

		// Pop the table from the Lua stack
		lua_pop(m_pLuaState, 1);
	}
}
Example #14
0
void Emitter::Update(double elapsed)
{	
	Array<int> deleteParticles;

	if (emitting) 
	{
		int nParticles = (minrate + (maxrate - minrate) * (float)rand() / RAND_MAX) * elapsed;	
        for (int i = 0; i < nParticles; i++) 
            particles.Add(CreateParticle());        
	}	    

    for (int i = 0; i < particles.Size(); i++) 
	{
		particles[i]->Update(elapsed);

		for (uint8 a = 0; a < affectors.Size(); a++)
			if (affectors[a]->IsCollide(particles[i])) affectors[a]->AffectParticle(particles[i]);

        if ( particles[i]->GetLifetime() <= 0 )
            deleteParticles.Add(i);
	}

    for (int i = 0; i < deleteParticles.Size(); i++ ) 
    {    		
		for (uint8 a = 0; a < affectors.Size(); a++)
			affectors[a]->DeleteAffectedParticle(particles[i]);

		particles.RemoveAt(i);
	}
							
}
Example #15
0
//----------------------------------------------------------------------------------------------------------------------------------------------------
Array<VirtualMemorySpan> Process::GetMemoryInfo()
{
  Array<VirtualMemorySpan> Spans;
  MEMORY_BASIC_INFORMATION MemoryInfo;
  PVOID pAddress = 0;
  TCHAR MappingName[1024];
  while (VirtualQueryEx(m_hProcess, pAddress, &MemoryInfo, sizeof(MemoryInfo) ))
    {
      VirtualMemorySpan S;
      S.Offset = MemoryInfo.BaseAddress;
      S.Length = MemoryInfo.RegionSize;
      S.Access = MemoryInfo.Protect;
      S.State = MemoryInfo.State;
      S.Type = MemoryInfo.Type;
      
      ZeroMemory(MappingName, 1024*sizeof(TCHAR));
      if (GetMappedFileName(m_hProcess, pAddress, MappingName, 1024))
	S.Name = MappingName;
      
      Spans.Add(S);
      
      pAddress = (BYTE*)pAddress + MemoryInfo.RegionSize;
    }
  
  return Spans;
}
int main()
{
	Array<int> myIntArray;
	for(int i = 0; i < 100; i++)
	{
		myIntArray.Add(i);
	}

	for(int i = 0; i < 100; i++)
	{
		cout<<i<<" element: ";
		cout<<myIntArray[i]<<endl;
	}

	int elems[5] = { 2, 3, 4, 5, 10 };
	myIntArray = Array<int>(elems, 5);

	for(int i = 0; i < 5; i++)
	{
		cout<<i<<" element: ";
		cout<<myIntArray[i]<<endl;
	}

	return 0;
}
Example #17
0
        void UnixFileSystemBase::GetFiles(const String& path, Array<FileInfo>& list)
        {
            String prefix = 
                path.Length() > 0 && path.Last() != '/' ? 
                    path + "/" : 
                    path;

            DIR *dp;
            struct dirent *ep;

            if ((dp = opendir(prefix.Ptr())) == NULL)
                XLI_THROW_FILE_NOT_FOUND(prefix);

            if (prefix == "./")
                prefix = "";

            while ((ep = readdir(dp)) != NULL)
            {
                String fn = ep->d_name;
                
                if (fn == "." || fn == "..") 
                    continue;

                FileInfo info;
                if (GetFileInfo(prefix + fn, info))
                    list.Add(info);
            }

            closedir(dp);
        }
Example #18
0
Array<IdentPos> GetLineIdent(const char *line)
{
	Array<IdentPos> out;
	const char *p = line;
	while(*p && *p != '\n')
		if(*p == '\"' || *p == '\'')
		{
			char term = *p++;
			while(*p && *p != term)
				if(*p++ == '\\' && *p)
					p++;
			if(*p == term)
				p++;
		}
		else if(*p == 's' && p[1] == '_' && p[2] == '(' && (IsAlpha(p[3]) || p[3] == '_'))
		{
			IdentPos& pos = out.Add();
			pos.begin = int(p - line);
			const char *b = (p += 3);
			while(IsAlNum(*++p) || *p == '_')
				;
			pos.ident = String(b, p);
			if(*p == ')')
				p++;
			pos.end = int(p - line);
		}
		else if(IsAlpha(*p) || *p == '_')
		{
			while(IsAlNum(*++p) || *p == '_')
				;
		}
		else
			p++;
	return out;
}
Example #19
0
void Emitter::Update(double elapsed)
{

	Array <int> particlesToRemove;
	//eliminacion de particulas

	for( unsigned int i = 0; i < particles.Size(); i++ )
	{
		particles[i]->Update( elapsed );
		
		for( unsigned int a = 0; a < affectors.Size(); a++ ) affectors[a].AddParticles( particles[i] );
			
		if( particles[i]->GetLifetime() <= 0 )
		{
			particlesToRemove.Add( i );
			delete particles[i];
		
			for( unsigned int a = 0; a < affectors.Size(); a++ ) affectors[a].DeleteParticles( particles[i] );			
		}
	}

	for( int i = particlesToRemove.Size() - 1; i >= 0 ; i-- )
	{
		particles.RemoveAt( particlesToRemove[i] );
	}

	//fin eliminacion particulas

	//creacion de particulas

	int32 nParticles = 0;
	double velX, velY, velAng, life;
	uint8 r, g, b;

	if( IsEmitting() )
	{
		nParticles = static_cast<int32>( RangeRand( static_cast<int32>( minrate ), static_cast<int32>( maxrate ) ) * elapsed );
	}

	for( uint32 i = 0; i < (uint32)nParticles; i++ )
	{
		velX = RangeRand( minvelx, maxvelx );
		velY = RangeRand( minvely, maxvely ); 
		velAng = RangeRand( minangvel, maxangvel ); 
		life = RangeRand( minlifetime, maxlifetime) ;
		r = (uint8)RangeRand( minr, maxr );
		g = (uint8)RangeRand( ming, maxg );
		b = (uint8)RangeRand( minb, maxb );

		Particle *particle = new Particle( image, velX, velY, velAng, life, autofade );

		particle->SetPosition( x, y );
		particle->SetColor( r, g, b, 255 );
		particle->SetBlendMode( blendMode );

		particles.Add( particle );
	}
	//fin creacion particulas
}
Example #20
0
void ExternalProcess::Start( const String& program, const StringList& arguments )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   if ( (*API->ExternalProcess->StartExternalProcess)( handle, program.c_str(), argv.Begin(), argv.Length() ) == api_false )
      throw APIFunctionError( "StartExternalProcess" );
}
Example #21
0
void categorizemesh(DataMesh *m)
{
	extern int hack_usealpha;
	int matid = m->GetMat();
	if(matid==shadowmatid)
	{
		shadowmeshes.Add(m);
	}
	else if( MaterialSpecial(matid)|| hack_usealpha)
	{
		alphameshes.Add(m);
	}
	else
	{
		regmeshes.Add(m);
	}
}
Example #22
0
void ExternalProcess::SetEnvironment( const StringList& environment )
{
   Array<const char16_type*> vars;
   for ( StringList::const_iterator i = environment.Begin(); i != environment.End(); ++i )
      vars.Add( i->c_str() );
   if ( (*API->ExternalProcess->SetExternalProcessEnvironment)( handle, vars.Begin(), vars.Length() ) == api_false )
      throw APIFunctionError( "SetExternalProcessEnvironment" );
}
Example #23
0
Joint::Joint(Chuckable *rb,Chuckable *_rb1):Entity("joint"),active(1)
{
	chuckable0 = rb;  
	chuckable1 = _rb1;
	maxforce = FLT_MAX;
	drivetorque = 0.0f;
	directive=0;
	Joints.Add(this);
}
Example #24
0
void ModelRender(Model* model)
{
	models.Add(model);
	for(int j=0;j<model->datameshes.count;j++)
	{
		DataMesh *m = model->datameshes[j];
		assert(m->model==model);
		categorizemesh(m);
	}
}
Example #25
0
::Array< ::String > Class_obj::dupFunctions(String inFuncs[])
{
   if (!inFuncs)
      return null();

   Array<String> result = Array_obj<String>::__new(0,0);
   for(String *s = inFuncs; s->length; s++)
         result->Add( *s );
    return result;
}
Example #26
0
//установка годов в которые среди списка есть релизы
void AnimeList::SetupYears()
{
	parameters.years.Clear();
	parameters.years.Add("All Years");
	parameters.years.SetIndex(0);
	Array<int> year;
	int last;
	bool a = false;
	if(!mainArray.IsEmpty())
	{
		for(int i=0;i<mainArray.GetCount();i++)
		{
			a = false;
			if(year.GetCount() == 0)
			{
				year.Add(mainArray[i].Release.year);
				last = year.GetCount() - 1;
			}
			else
			{
				for(int j=0;j<year.GetCount();j++)
					if(mainArray[i].Release.year == year[j])
					{	
						a = true;
						break;
					}
				if(!a)
				{
					year.Add(mainArray[i].Release.year);
					last = year.GetCount() - 1;
				}
				for(int i=0;i<year.GetCount();i++)
					if(year[last]<year[i])
					{
						year.Swap(i, last);
					}
			}
		}

		for(int i=year.GetCount()-1;i>=0;i--)
			parameters.years.Add(year[i]);
	}
}
Example #27
0
int ExternalProcess::ExecuteProgram( const String& program, const StringList& arguments )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   int retVal = (*API->ExternalProcess->ExecuteProgram)( program.c_str(), argv.Begin(), argv.Length() );
   if ( retVal < -1 )
      ExternalProcessPrivate::Throw( ExternalProcessContext::FailedToStart );
   return retVal;
}
Example #28
0
	App() {
		a.AddColumn("Option");
		for(int i = 0; i < 300; i++) {
			a.Add(bool(i & 4));
			a.SetCtrl(i, 0, option.Add().SetLabel("Option " + AsString(i)));
			option.Top() << [=] { Do(i); };
		}
		a.SetLineCy(Draw::GetStdFontCy() + 8);
		Add(a.SizePos());
		Sizeable();
	}
Example #29
0
/**
*  @brief
*    This function loads a '.ogg' file into a memory buffer and returns
*    the format and frequency
*/
bool LoadOGG(const uint8 nData[], uint32 nSize, Array<uint8> &lstBuffer, ALenum &nFormat, ALsizei &nFrequency)
{
	bool bResult = false; // Error by default

	// Set data pointers
	SoundManager::MemData sMemData;
	sMemData.pnData  = nData;
	sMemData.pnDataE = sMemData.pnData + nSize;

	// Try opening the given file
	OggVorbis_File oggFile;
	ov_callbacks ovc;
	ovc.read_func  = &SoundManager::read_func_mem;
	ovc.seek_func  = &SoundManager::seek_func_mem;
	ovc.close_func = &SoundManager::close_func_mem;
	ovc.tell_func  = &SoundManager::tell_func_mem;
	if (!ov_open_callbacks(&sMemData, &oggFile, nullptr, 0, ovc)) {
		// Get some information about the OGG file
		vorbis_info *pInfo = ov_info(&oggFile, -1);

		// Check the number of channels... always use 16-bit samples
		nFormat = (pInfo->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;

		// The frequency of the sampling rate
		nFrequency = pInfo->rate;

		// Set to no error
		bResult = true;

		// Keep reading until all is read
		static const uint32 BufferSize = 8192;	// 8 KB buffers
		uint8 nArray[BufferSize];				// Local fixed size array
		int nEndian = 0;						// 0 for Little-Endian, 1 for Big-Endian
		int nBitStream;
		long nBytes;
		do {
			// Read up to a buffer's worth of decoded sound data
			nBytes = ov_read(&oggFile, reinterpret_cast<char*>(nArray), BufferSize, nEndian, 2, 1, &nBitStream);
			if (nBytes < 0) {
				// Error!
				bResult = false;
			} else {
				// Append to end of buffer
				lstBuffer.Add(nArray, nBytes);
			}
		} while (nBytes>0);

		// Cleanup
		ov_clear(&oggFile);
	}

	// Done
	return bResult;
}
Example #30
0
ExternalProcess::pid_type ExternalProcess::StartProgram( const String& program, const StringList& arguments, const String& workingDirectory )
{
   Array<const char16_type*> argv;
   for ( StringList::const_iterator i = arguments.Begin(); i != arguments.End(); ++i )
      argv.Add( i->c_str() );
   uint64 pid = 0;
   api_bool ok = (*API->ExternalProcess->StartProgram)( program.c_str(), argv.Begin(), argv.Length(), workingDirectory.c_str(), &pid );
   if ( ok == api_false || pid == 0 )
      ExternalProcessPrivate::Throw( ExternalProcessContext::FailedToStart );
   return pid_type( pid );
}