Ejemplo n.º 1
0
void Foam::proxySurfaceWriter::write
(
    const fileName& outputDir,
    const fileName& surfaceName,
    const pointField& points,
    const faceList& faces,
    const bool verbose
) const
{
    // avoid bad values
    if (ext_.empty())
    {
        return;
    }

    if (!isDir(outputDir))
    {
        mkDir(outputDir);
    }

    fileName outName(outputDir/surfaceName + "." + ext_);

    if (verbose)
    {
        Info<< "Writing geometry to " << outName << endl;
    }

    MeshedSurfaceProxy<face>(points, faces).write(outName);
}
Ejemplo n.º 2
0
//---------------------------------------------------------------
// Purpose: 
//---------------------------------------------------------------
void CEntityOutputWnd::UpdateEventComboBox()
{
	CString oldText;
	m_cbEvt.GetWindowText(oldText);

	m_cbEvt.ResetContent();

	for(int id : m_list.GetEditIds()) //iterate over selected outputs
	{
		COutputListWnd::OutputSourceList *sourceList = m_list.GetSourceEnts(id);
		for(const std::pair<CEditorEntity*, CEntityOutput*> &outputPair : *sourceList) //iterate over output source entities
		{
			CEditorEntity *ent = outputPair.first;
			CEntityRegisterEntity *regEnt = GetEntityRegister()->GetEntity(ent->GetClassnameA());
			if(regEnt)
			{
				size_t numOuts = regEnt->GetNumOutputs();
				for(size_t i = 0; i < numOuts; i++) //iterate over the possible outputs of this source entity
				{
					const CEntityRegisterOutput *regOut = regEnt->GetOutput(i);
					CString outName(CA2T(regOut->name.c_str()));
					if( m_cbEvt.FindString(-1, outName) == CB_ERR )
						m_cbEvt.AddString(outName);
				}
			}				
		}
	}

	m_cbEvt.SetWindowText(oldText);
}
Ejemplo n.º 3
0
String getUniqueName( const char *inName )
{
   String outName( inName );

   if ( outName.isEmpty() )
      return String::EmptyString;

   SimObject *dummy;

   if ( !Sim::findObject( outName, dummy ) )
      return outName;

   S32 suffixNumb = -1;
   String nameStr( String::GetTrailingNumber( outName, suffixNumb ) );
   suffixNumb = mAbs( suffixNumb ) + 1;

   #define MAX_TRIES 100

   for ( U32 i = 0; i < MAX_TRIES; i++ )
   {   
      outName = String::ToString( "%s%d", nameStr.c_str(), suffixNumb );

      if ( !Sim::findObject( outName, dummy ) )
         return outName;         

      suffixNumb++;
   }

   Con::errorf( "Sim::getUniqueName( %s ) - failed after %d attempts", inName, MAX_TRIES );
   return String::EmptyString;
}
INode* plDistribComponent_old::IMakeOne(plDistribInstTab& nodes)
{
    if( !nodes.Count() )
        return nil;

    int iStartNode = 0;

    NameMaker *nn = GetCOREInterface()->NewNameMaker();

    while( iStartNode < nodes.Count() )
    {
        TriObject* triObj = CreateNewTriObject();
        Mesh* outMesh = &triObj->mesh;

        *outMesh = *nodes[iStartNode].fMesh;

        INode *outNode = GetCOREInterface()->CreateObjectNode(triObj);

        Matrix3 l2w = nodes[0].fObjectTM;
        Matrix3 w2l = Inverse(l2w);

        MeshDelta meshDelta(*outMesh);

        int i;
        for( i = iStartNode; i < nodes.Count(); i++ )
        {
            Mesh* nextMesh = nodes[i].fMesh;

            Matrix3 relativeTransform = nodes[i].fObjectTM * w2l;

            meshDelta.AttachMesh(*outMesh, *nextMesh, relativeTransform, 0);

            meshDelta.Apply(*outMesh);

            const int kFaceCutoff = 1000;
            if( outMesh->getNumFaces() > kFaceCutoff )
                break;
        }
        iStartNode = i;

        outNode->SetNodeTM(TimeValue(0), l2w);
        outNode->CopyProperties(nodes[0].fNode);
        outNode->SetMtl(nodes[0].fNode->GetMtl());
        outNode->SetObjOffsetPos(Point3(0,0,0));
        Quat identQuat;
        identQuat.Identity();
        outNode->SetObjOffsetRot(identQuat);
        outNode->SetObjOffsetScale(ScaleValue(Point3(1.f, 1.f, 1.f)));

        TSTR outName(TSTR("Preview"));
        nn->MakeUniqueName(outName);
        outNode->SetName(outName);

        fCompPB->Append(kReplicants, 1, &outNode);
    }

    return nil;
}
Ejemplo n.º 5
0
//--------------------------------------------------------------------------
// end of special-label procedures
//----------------------------------------------------------------------
uchar outOffName(ushort off)
{
  if ( !off || off == curSeg.CodeSize) return(putMethodLabel(off) );
  if ( off < curSeg.CodeSize ) {
    uchar err = 0;
    if(outName(curSeg.startEA + curSeg.CodeSize, 0,
               curSeg.startEA, off, &err)) return(0); // good
    if ( err) return(1 ); // bad
  }
  return(putShort(off, 0));
}
Ejemplo n.º 6
0
//--------------------------------------------------------------------------
uchar putScope(ushort scope, uint32 doff)
{
  if ( !scope || scope == curSeg.CodeSize) return(putMethodLabel(scope) );

  if ( scope < curSeg.CodeSize ) {
    uchar err = 0;
    if(outName(curSeg.DataBase + doff, 0,
               curSeg.startEA, scope, &err)) return(0);
    if ( err) return(1 );
  }

  return(putShort(scope, 0));
}
Ejemplo n.º 7
0
void BaseProgramRenderPass::Link()
{
	RETURN_IF(mProgramState->Program()==0||mIsLinked);
	SAFE_DELETE_DICTIONARY_VALUE(mUniforms);
	SAFE_DELETE_DICTIONARY_VALUE(mAttributes);

	uint program=mProgramState->Program();
	Render::Instance().LinkProgram(program);
	int outLinkStatus=Render::Instance().GetProgramStatus(program,GraphicsProgramStatus::LinkStatus);

	if (!outLinkStatus)
	{
		//link error
		int outInfoLogLength=Render::Instance().GetProgramStatus(program,GraphicsProgramStatus::InfoLogLength);

		HeapString infoLog((size_t)outInfoLogLength+1,true);
		Render::Instance().GetProgramInfoLog(program,infoLog);
		Log::FormatError("Failed to link effect:{}",infoLog.Buffer());
		Uninitialize();
		return ;
	}

	Render::Instance().ValidateProgram(program);
	int outValidateStatus=Render::Instance().GetProgramStatus(program,GraphicsProgramStatus::ValidateStatus);

	if (!outValidateStatus)
	{
		//link error
		int outInfoLogLength=Render::Instance().GetProgramStatus(program,GraphicsProgramStatus::InfoLogLength);

		HeapString infoLog((size_t)outInfoLogLength+1,true);
		Render::Instance().GetProgramInfoLog(program,infoLog);
		Log::FormatError("Failed to validate effect:{}",infoLog.Buffer());
		Uninitialize();
		return;
	}
	RenderStateMachine::Instance().Push(mProgramState);

	//add all uniforms
	uint uniformCount=(uint)Render::Instance().GetProgramStatus(program,GraphicsProgramStatus::ActiveUniformCount);
	uint maxUniformNameLength=(uint)Render::Instance().GetProgramStatus(program,GraphicsProgramStatus::MaxActiveUniformNameLength);
	HeapString outName((size_t)maxUniformNameLength+1,true);
	FOR_EACH_SIZE(i,uniformCount)
	{
		int outSize;
		uint outDataType;
		Render::Instance().GetActiveUniformName(program,static_cast<uint>(i),outSize,outDataType,outName);
		int index= Render::Instance().GetUniformLocation(program,outName);	//NOTE: Cannot use i as index
		ShaderUniform* uniform=new ShaderUniform(this,index,outName,(GraphicsUniformDataType)outDataType);
		mUniforms.Add(outName,uniform);
	}
Ejemplo n.º 8
0
int main(int argc, char **argv) {
	if (argc != 2) {
		std::cerr << "usage:\n  " << argv[0] << " <directory name with language examples in txt format>\n";
		return 0;
	}
	ZLibrary::init(argc, argv);

	std::string directoryName = argv[1];
	shared_ptr<ZLDir> directory = ZLFile(directoryName).directory(false);
	if (directory.isNull()) { 
		std::cerr << "cannot open directory  " << directoryName << "\n";
		return 0;
	}
	std::vector<std::string> fileNames;
	directory->collectFiles(fileNames, false);
	ZLMapBasedStatistics tempStatistics, resultStatistics;
	int counter = 0;
	for (std::vector<std::string>::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) {
		ZLFile file(directory->itemPath(*it));
		if (file.extension() != "txt") {
			continue;
		} else {
			++counter;
		}
		ZLStatisticsGenerator("\n\r ").generate(file.path(), CHAR_SEQUENCE_SIZE, tempStatistics);
		if (counter == 1) {
			resultStatistics = tempStatistics;
			continue;
		}
		resultStatistics.retain(tempStatistics);
	}
	std::string outName (argv[1]);
	outName += "pattern.stat";
	shared_ptr<ZLOutputStream> streamOut = ZLFile(outName).outputStream();
	streamOut->open();
	ZLMapBasedStatistics restrictedResultStatistics = resultStatistics.top(TOP_AMOUNT);
	restrictedResultStatistics.scaleToShort();
	ZLStatisticsXMLWriter(*streamOut).writeStatistics(restrictedResultStatistics);
	streamOut->close();
	ZLibrary::shutdown();
	return 0;
}
Ejemplo n.º 9
0
void Decoder::decode(std::string inFileName,std::string outFileName,bool mode)
{
    //open input file
    std::string inName(inFileName);
    if (inName.rfind(".ebast",inName.size()-6) == std::string::npos) {
        std::cerr << "This isn't a ebast File" << std::endl;
        exit(1);
    }
    inFile.open(inFileName, std::ios::in | std::ios::binary);
    if (!inFile.is_open()) {
        std::cerr << "Unable to read File" << std::endl;
        exit(1);
    }
    
    //open output file
    std::string outName(outFileName);
    outName += ".txt";
    if(std::ifstream(outName.c_str()))
    {
        std::cerr<<outName<<" already exists!"<<std::endl;
        exit(1);
    }
    
    outFile.open(outName.c_str(),std::ios::out | std::ios::binary);
    if (!outFile.is_open()) {
        std::cerr << "Unable to create File" << std::endl;
        exit(1);
    }
    
    //reading frequency table from file
    huffmanTree->setRoot(readHeader());
    if (mode) {
        print(huffmanTree->getRoot());
    }
    //make file
    makeFile();
    
}
Ejemplo n.º 10
0
int main(int argc, char** argv){

    //Usage message
    if(argc > 1 && strcmp(argv[1], "--help") == 0){
        std::cerr << "Usage(all parameters optional): " << std::endl << argv[0] <<
            " camX camY camZ imWidth imHeight outImage.png rot" << std::endl;
        return 0;
    }

    //Parse command line parameters
    int index = 1; //which arg are we currently parsing?
    float camX, camY, camZ, rotDeg;
    camX = camY = camZ = rotDeg = 0.0f;
    int width, height;
    width = height = 64;
    std::string outName("default.ppm");
    if(index < argc)
        camX = atof(argv[index++]);
    if(index < argc)
        camY = atof(argv[index++]);
    if(index < argc)
        camZ = atof(argv[index++]);

    if(index < argc)
        width  = atoi(argv[index++]);
    if(index < argc)
        height = atoi(argv[index++]);
    Assert(width > 0 && height > 0);
    if(index < argc)
        outName = std::string(argv[index++]);
    if(index < argc)
        rotDeg = atof(argv[index++]);
    
   
    //Construct camera placement transformation
    Transform moveTrans  = Transform::translate(Vector(camX, camY, camZ));
    Transform rotTrans   = Transform::rotateZ(rotDeg);
    Transform camToWorld = moveTrans * rotTrans;

    //Generate scene
    std::vector<Shape*> shapes;
    std::vector<Light*> lights;
    Camera* cam = SceneGen::genCornellBox(shapes, lights);

    //Setup image plane and sampler
    const float pixelWidth  = 1.0f;
    const float pixelHeight = 1.0f;
    ImageSampler* sampler = new JitteredSampler(width, height, spp,
        pixelWidth / 2.0f, pixelHeight / 2.0f); //Jitter x and jitter Y
    ImageSensor* ccd = new ImageSensor(width, height, NULL ,
        new GaussianFilter(3.0f, pixelWidth, pixelHeight)
    );

    //Acceleration structure
    AccelStructure* accelScene = new NoAccelStructure();
    accelScene->buildAccelStructure(shapes);

    //Full scene
    Scene* scene = new Scene(accelScene, lights);

    //Setup integrator and renderer
    Integrator* integrator = new DirectLightIntegrator();
    Renderer* rt = new Renderer();
    //Renderer* rt = new ParallelRenderer(32, 32, 4);

    //Render a picture
    std::cout << "Rendering scene..." << std::endl;
    HDRImage* im = rt->render(sampler, cam, ccd, scene, integrator);
    std::cout << "Done rendering scene." << std::endl;

    //Cleanup memory
    delete rt;
    delete sampler;
    delete cam;
    delete ccd;
    delete scene;
    delete integrator;


    //Potentially tonemap the image
    LDRImage* tmapim = NULL;
    if(StringUtils::endsWith(outName, ".pfm")){
        std::cout << "Skipping tone mapping and saving an HDR image directly..." << std::endl;

        bool ok = ImageIO::writePFM(outName, im);
        if(!ok){
            std::cerr << "ERROR - could not write image: " << outName << std::endl;
        }
    }else{

        std::cout << "Tone mapping..." << std::endl;
        tmapim = ToneMap::toneMapMaxToWhite(im, true);

        ToneMap::makeWhiteBorder(tmapim);
        std::cout << "Done tone mapping." << std::endl;

        //Save to disk
        std::cout << "Outputting image to " << outName << "..." << std::endl;
        bool ok = ImageIO::writePPM(outName, tmapim, "LDR ppm from colins command line renderer");
        if(!ok){
            std::cerr << "ERROR - could not write image: " << outName << std::endl;
        }
    }
    delete im; im = NULL;
    delete tmapim; tmapim = NULL;
    std::cout << "Done outputting image." << std::endl;

    return 0;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
	QString workDir;
#ifdef Q_OS_MAC
    if (QDir(QString()).absolutePath() == "/") {
		QString first = argc ? QString::fromLocal8Bit(argv[0]) : QString();
		if (!first.isEmpty()) {
			QFileInfo info(first);
			if (info.exists()) {
				QDir result(info.absolutePath() + "/../../..");
				workDir = result.absolutePath() + '/';
			}
		}
	}
#endif

	QString remove;
	int version = 0;
	QFileInfoList files;
	for (int i = 0; i < argc; ++i) {
		if (string("-path") == argv[i] && i + 1 < argc) {
			QString path = workDir + QString(argv[i + 1]);
			QFileInfo info(path);
			files.push_back(info);
			if (remove.isEmpty()) remove = info.canonicalPath() + "/";
		} else if (string("-version") == argv[i] && i + 1 < argc) {
			version = QString(argv[i + 1]).toInt();
		} else if (string("-dev") == argv[i]) {
			DevChannel = true;
		} else if (string("-beta") == argv[i] && i + 1 < argc) {
			BetaVersion = QString(argv[i + 1]).toULongLong();
			if (BetaVersion > version * 1000ULL && BetaVersion < (version + 1) * 1000ULL) {
				DevChannel = false;
				BetaSignature = countBetaVersionSignature(BetaVersion);
				if (BetaSignature.isEmpty()) {
					return -1;
				}
			} else {
				cout << "Bad -beta param value passed, should be for the same version: " << version << ", beta: " << BetaVersion << "\n";
				return -1;
			}
		}
	}

	if (files.isEmpty() || remove.isEmpty() || version <= 1016 || version > 999999999) {
#ifdef Q_OS_WIN
		cout << "Usage: Packer.exe -path {file} -version {version} OR Packer.exe -path {dir} -version {version}\n";
#elif defined Q_OS_MAC
		cout << "Usage: Packer.app -path {file} -version {version} OR Packer.app -path {dir} -version {version}\n";
#else
		cout << "Usage: Packer -path {file} -version {version} OR Packer -path {dir} -version {version}\n";
#endif
		return -1;
	}

	bool hasDirs = true;
	while (hasDirs) {
		hasDirs = false;
		for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) {
			QFileInfo info(*i);
			QString fullPath = info.canonicalFilePath();
			if (info.isDir()) {
				hasDirs = true;
				files.erase(i);
				QDir d = QDir(info.absoluteFilePath());
				QString fullDir = d.canonicalPath();
				QStringList entries = d.entryList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
				files.append(d.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot));
				break;
			} else if (!info.isReadable()) {
				cout << "Can't read: " << info.absoluteFilePath().toUtf8().constData() << "\n";
				return -1;
			} else if (info.isHidden()) {
				hasDirs = true;
				files.erase(i);
				break;
			}
		}
	}
	for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) {
		QFileInfo info(*i);
		if (!info.canonicalFilePath().startsWith(remove)) {
			cout << "Can't find '" << remove.toUtf8().constData() << "' in file '" << info.canonicalFilePath().toUtf8().constData() << "' :(\n";
			return -1;
		}
	}

	QByteArray result;
	{
		QBuffer buffer(&result);
		buffer.open(QIODevice::WriteOnly);
		QDataStream stream(&buffer);
		stream.setVersion(QDataStream::Qt_5_1);

		if (BetaVersion) {
			stream << quint32(0x7FFFFFFF);
			stream << quint64(BetaVersion);
		} else {
			stream << quint32(version);
		}

		stream << quint32(files.size());
		cout << "Found " << files.size() << " file" << (files.size() == 1 ? "" : "s") << "..\n";
		for (QFileInfoList::iterator i = files.begin(); i != files.end(); ++i) {
			QFileInfo info(*i);
			QString fullName = info.canonicalFilePath();
			QString name = fullName.mid(remove.length());
			cout << name.toUtf8().constData() << " (" << info.size() << ")\n";

			QFile f(fullName);
			if (!f.open(QIODevice::ReadOnly)) {
				cout << "Can't open '" << fullName.toUtf8().constData() << "' for read..\n";
				return -1;
			}
			QByteArray inner = f.readAll();
			stream << name << quint32(inner.size()) << inner;
#if defined Q_OS_MAC || defined Q_OS_LINUX
			stream << (QFileInfo(fullName).isExecutable() ? true : false);
#endif
		}
		if (stream.status() != QDataStream::Ok) {
			cout << "Stream status is bad: " << stream.status() << "\n";
			return -1;
		}
	}

	int32 resultSize = result.size();
	cout << "Compression start, size: " << resultSize << "\n";

	QByteArray compressed, resultCheck;
#ifdef Q_OS_WIN // use Lzma SDK for win
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = LZMA_PROPS_SIZE, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hPropsLen + hOriginalSizeLen; // header

	compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size

	size_t compressedLen = compressed.size() - hSize;
	size_t outPropsSize = LZMA_PROPS_SIZE;
	uchar *_dest = (uchar*)(compressed.data() + hSize);
	size_t *_destLen = &compressedLen;
	const uchar *_src = (const uchar*)(result.constData());
	size_t _srcLen = result.size();
	uchar *_outProps = (uchar*)(compressed.data() + hSigLen + hShaLen);
	int res = LzmaCompress(_dest, _destLen, _src, _srcLen, _outProps, &outPropsSize, 9, 64 * 1024 * 1024, 4, 0, 2, 273, 2);
	if (res != SZ_OK) {
		cout << "Error in compression: " << res << "\n";
		return -1;
	}
	compressed.resize(int(hSize + compressedLen));
	memcpy(compressed.data() + hSigLen + hShaLen + hPropsLen, &resultSize, hOriginalSizeLen);

	cout << "Compressed to size: " << compressedLen << "\n";

	cout << "Checking uncompressed..\n";

	int32 resultCheckLen;
	memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen + hPropsLen, hOriginalSizeLen);
	if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) {
		cout << "Bad result len: " << resultCheckLen << "\n";
		return -1;
	}
	resultCheck.resize(resultCheckLen);

	size_t resultLen = resultCheck.size();
	SizeT srcLen = compressedLen;
	int uncompressRes = LzmaUncompress((uchar*)resultCheck.data(), &resultLen, (const uchar*)(compressed.constData() + hSize), &srcLen, (const uchar*)(compressed.constData() + hSigLen + hShaLen), LZMA_PROPS_SIZE);
	if (uncompressRes != SZ_OK) {
		cout << "Uncompress failed: " << uncompressRes << "\n";
		return -1;
	}
	if (resultLen != size_t(result.size())) {
		cout << "Uncompress bad size: " << resultLen << ", was: " << result.size() << "\n";
		return -1;
	}
#else // use liblzma for others
	const int32 hSigLen = 128, hShaLen = 20, hPropsLen = 0, hOriginalSizeLen = sizeof(int32), hSize = hSigLen + hShaLen + hOriginalSizeLen; // header

	compressed.resize(hSize + resultSize + 1024 * 1024); // rsa signature + sha1 + lzma props + max compressed size

	size_t compressedLen = compressed.size() - hSize;

	lzma_stream stream = LZMA_STREAM_INIT;

	int preset = 9 | LZMA_PRESET_EXTREME;
	lzma_ret ret = lzma_easy_encoder(&stream, preset, LZMA_CHECK_CRC64);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
			case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error initializing the encoder: " << msg << " (error code " << ret << ")\n";
		return -1;
	}

	stream.avail_in = resultSize;
	stream.next_in = (uint8_t*)result.constData();
	stream.avail_out = compressedLen;
	stream.next_out = (uint8_t*)(compressed.data() + hSize);

	lzma_ret res = lzma_code(&stream, LZMA_FINISH);
	compressedLen -= stream.avail_out;
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_DATA_ERROR: msg = "File size limits exceeded"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error in compression: " << msg << " (error code " << res << ")\n";
		return -1;
	}

	compressed.resize(int(hSize + compressedLen));
	memcpy(compressed.data() + hSigLen + hShaLen, &resultSize, hOriginalSizeLen);

	cout << "Compressed to size: " << compressedLen << "\n";

	cout << "Checking uncompressed..\n";

	int32 resultCheckLen;
	memcpy(&resultCheckLen, compressed.constData() + hSigLen + hShaLen, hOriginalSizeLen);
	if (resultCheckLen <= 0 || resultCheckLen > 1024 * 1024 * 1024) {
		cout << "Bad result len: " << resultCheckLen << "\n";
		return -1;
	}
	resultCheck.resize(resultCheckLen);

	size_t resultLen = resultCheck.size();

	stream = LZMA_STREAM_INIT;

	ret = lzma_stream_decoder(&stream, UINT64_MAX, LZMA_CONCATENATED);
	if (ret != LZMA_OK) {
		const char *msg;
		switch (ret) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_OPTIONS_ERROR: msg = "Specified preset is not supported"; break;
			case LZMA_UNSUPPORTED_CHECK: msg = "Specified integrity check is not supported"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error initializing the decoder: " << msg << " (error code " << ret << ")\n";
		return -1;
	}

	stream.avail_in = compressedLen;
	stream.next_in = (uint8_t*)(compressed.constData() + hSize);
	stream.avail_out = resultLen;
	stream.next_out = (uint8_t*)resultCheck.data();

	res = lzma_code(&stream, LZMA_FINISH);
	if (stream.avail_in) {
		cout << "Error in decompression, " << stream.avail_in << " bytes left in _in of " << compressedLen << " whole.\n";
		return -1;
	} else if (stream.avail_out) {
		cout << "Error in decompression, " << stream.avail_out << " bytes free left in _out of " << resultLen << " whole.\n";
		return -1;
	}
	lzma_end(&stream);
	if (res != LZMA_OK && res != LZMA_STREAM_END) {
		const char *msg;
		switch (res) {
			case LZMA_MEM_ERROR: msg = "Memory allocation failed"; break;
			case LZMA_FORMAT_ERROR: msg = "The input data is not in the .xz format"; break;
			case LZMA_OPTIONS_ERROR: msg = "Unsupported compression options"; break;
			case LZMA_DATA_ERROR: msg = "Compressed file is corrupt"; break;
			case LZMA_BUF_ERROR: msg = "Compressed data is truncated or otherwise corrupt"; break;
			default: msg = "Unknown error, possibly a bug"; break;
		}
		cout << "Error in decompression: " << msg << " (error code " << res << ")\n";
		return -1;
	}
#endif
	if (memcmp(result.constData(), resultCheck.constData(), resultLen)) {
		cout << "Data differ :(\n";
		return -1;
	}
	/**/
	result = resultCheck = QByteArray();

	cout << "Counting SHA1 hash..\n";

	uchar sha1Buffer[20];
	memcpy(compressed.data() + hSigLen, hashSha1(compressed.constData() + hSigLen + hShaLen, uint32(compressedLen + hPropsLen + hOriginalSizeLen), sha1Buffer), hShaLen); // count sha1

	uint32 siglen = 0;

	cout << "Signing..\n";
	RSA *prKey = PEM_read_bio_RSAPrivateKey(BIO_new_mem_buf(const_cast<char*>((DevChannel || BetaVersion) ? PrivateDevKey : PrivateKey), -1), 0, 0, 0);
	if (!prKey) {
		cout << "Could not read RSA private key!\n";
		return -1;
	}
	if (RSA_size(prKey) != hSigLen) {
		cout << "Bad private key, size: " << RSA_size(prKey) << "\n";
		RSA_free(prKey);
		return -1;
	}
	if (RSA_sign(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (uchar*)(compressed.data()), &siglen, prKey) != 1) { // count signature
		cout << "Signing failed!\n";
		RSA_free(prKey);
		return -1;
	}
	RSA_free(prKey);

	if (siglen != hSigLen) {
		cout << "Bad signature length: " << siglen << "\n";
		return -1;
	}

	cout << "Checking signature..\n";
	RSA *pbKey = PEM_read_bio_RSAPublicKey(BIO_new_mem_buf(const_cast<char*>((DevChannel || BetaVersion) ? PublicDevKey : PublicKey), -1), 0, 0, 0);
	if (!pbKey) {
		cout << "Could not read RSA public key!\n";
		return -1;
	}
	if (RSA_verify(NID_sha1, (const uchar*)(compressed.constData() + hSigLen), hShaLen, (const uchar*)(compressed.constData()), siglen, pbKey) != 1) { // verify signature
		RSA_free(pbKey);
		cout << "Signature verification failed!\n";
		return -1;
	}
	cout << "Signature verified!\n";
	RSA_free(pbKey);
#ifdef Q_OS_WIN
	QString outName(QString("tupdate%1").arg(BetaVersion ? BetaVersion : version));
#elif defined Q_OS_MAC
	QString outName(QString("tmacupd%1").arg(BetaVersion ? BetaVersion : version));
#elif defined Q_OS_LINUX32
    QString outName(QString("tlinux32upd%1").arg(BetaVersion ? BetaVersion : version));
#elif defined Q_OS_LINUX64
    QString outName(QString("tlinuxupd%1").arg(BetaVersion ? BetaVersion : version));
#else
#error Unknown platform!
#endif
	if (BetaVersion) {
		outName += "_" + BetaSignature;
	}
	QFile out(outName);
	if (!out.open(QIODevice::WriteOnly)) {
		cout << "Can't open '" << outName.toUtf8().constData() << "' for write..\n";
		return -1;
	}
	out.write(compressed);
	out.close();

	if (BetaVersion) {
		QString keyName(QString("tbeta_%1_key").arg(BetaVersion));
		QFile key(keyName);
		if (!key.open(QIODevice::WriteOnly)) {
			cout << "Can't open '" << keyName.toUtf8().constData() << "' for write..\n";
			return -1;
		}
		key.write(BetaSignature.toUtf8());
		key.close();
	}

	cout << "Update file '" << outName.toUtf8().constData() << "' written successfully!\n";

	return 0;
}
Ejemplo n.º 12
0
bool idaapi outop(op_t& x)
{
  uchar warn = 0;

  switch ( x.type ) {
    case o_near:
      if ( x.ref ) ++warn;
      else {
        if ( outName(cmd.ea + x.offb, x.n, curSeg.startEA, x.addr, &warn) ) break;
        if ( warn ) goto badop;
      }
      if ( putVal(x, OOF_ADDR | OOF_NUMBER | OOFS_NOSIGN | OOFW_32, warn) ) break;
      //PASS THRU
    case o_void:
badop:
      return(false);

    case o_imm:
      if ( x.ref == 2 ) ++warn;
      if ( putVal(x, OOFW_IMM | OOF_NUMBER | (x.ref ? OOFS_NOSIGN : OOF_SIGNED ),
                warn)) break;
      goto badop;

    case o_mem:
      if ( jasmin() ) goto putVarNum;
      if ( x.ref ) {
putAddr:
        ++warn;
      } else {
        if ( outName(cmd.ea + x.offb, x.n, curSeg.DataBase, x.addr, &warn) ) break;
        if ( warn ) goto badop;
      }
putVarNum:
      if ( putVal(x, OOF_ADDR | OOF_NUMBER | OOFS_NOSIGN | OOFW_16, warn) ) break;
      goto badop;

    case o_cpool:
      if ( !x.cp_ind) OUT_KEYWORD("NULL" );
      else {
        if ( x.ref ) goto putAddr;
        if ( !OutConstant(x) ) goto badop;
      }
      break;

    case o_array:
      if ( !x.ref ) {
        int i = (uchar)x.cp_type - (T_BOOLEAN-1); // -1 - correct tp_decl
        if ( i < 0 || i > T_LONG - (T_BOOLEAN-1) || chkOutKeyword(tp_decl[i].str, tp_decl[i].size) )
          goto badop;
      } else {
        static const char tt_bogust[] = "BOGUST_TYPE-";

        if ( !checkLine(sizeof(tt_bogust) + 2) ) goto badop;
        out_tagon(COLOR_ERROR);
        outcnt += out_snprintf("%c%s%u", WARN_SYM, tt_bogust, (uchar)x.cp_type);
        out_tagoff(COLOR_ERROR);
      }
      break;

    default:
      warning("out: %a: bad optype %d", cmd.ip, x.type);
      break;
  }
  return(true);
}
Ejemplo n.º 13
0
int main(int argc, char *argv[]){
    QTime t;
    t.start();
    //START APP
    QApplication app(argc,argv);
    app.setWindowIcon(QIcon(":/data/img/11412394_407750046078820_6932822019341529347_n.jpg"));
    QApplication::setApplicationName("Huffman");
    QApplication::setApplicationVersion("ÚNICO");
    QQmlApplicationEngine engine;
    QQmlContext *interpreter = engine.rootContext();
    Huffman huff;
    DHuffman deHuff;
    QCommandLineParser parser;
    //Parser
    parser.addHelpOption();
    parser.addVersionOption();
    parser.setApplicationDescription("Huffman Parsers");
    parser.addPositionalArgument("in-file.x", QCoreApplication::translate("main", "File being compressed."));
    parser.addPositionalArgument("out-name.huff", QCoreApplication::translate("main", "Name to save archive."));
    //parser.addPositionalArgument("dir", QCoreApplication::translate("main", "Dir being compressed"));
    parser.addPositionalArgument("local", QCoreApplication::translate("main", "Local to save archive."));
    QCommandLineOption compress("c",QApplication::translate("main","Compress <in-file.x>."),
                                QApplication::translate("main","in-file.x"));
    parser.addOption(compress);
    QCommandLineOption outName("o",QApplication::translate("main","Save as <out-name.huff>."),
                               QApplication::translate("main","out-file.huff"));
    parser.addOption(outName);
    QCommandLineOption local("d",QApplication::translate("main","Decompress in <local>."),
                             QApplication::translate("main","local"));
    parser.addOption(local);
    QCommandLineOption startGui({"g", "gui"},QApplication::translate("main","Start gui."));
    parser.addOption(startGui);
    parser.process(app);

    //ARGUMENTS
    if(parser.isSet(startGui)){
        interpreter->setContextProperty("_huff",&huff);
        interpreter->setContextProperty("_dehuff",&deHuff);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    }
    else if(parser.isSet(compress) && parser.isSet(outName))
    {
        cout << "case 1" << endl;
        huff.Huff(parser.value(compress),parser.value(outName));
    }
    else if(parser.isSet(compress))
    {
        cout << "case 2" << endl;
        huff.Huff(parser.value(compress),parser.value(compress));
    }
    else{
        if(app.arguments().size() == 1)
            qDebug() << qPrintable(parser.helpText());
        else if(parser.isSet(local))
            deHuff.DHuff(app.arguments().at(1),parser.value(local));
        else
            deHuff.DHuff(app.arguments().at(1),app.arguments().at(1));
    }
    //END APP
    qDebug("%s <> Tempo de execução: %d ms",Q_FUNC_INFO,t.elapsed());
    return app.exec();
}
Ejemplo n.º 14
0
void MergeFastqWorkerFactory::init() {
    Descriptor desc( ACTOR_ID, MergeFastqWorker::tr("FASTQ Merger"),
        MergeFastqWorker::tr("Merges input sequences to one output file") );

    QList<PortDescriptor*> p;
    {
        Descriptor inD(BaseNGSWorker::INPUT_PORT, MergeFastqWorker::tr("Input File"),
            MergeFastqWorker::tr("Set of FASTQ reads files"));
        Descriptor outD(BaseNGSWorker::OUTPUT_PORT, MergeFastqWorker::tr("Output File"),
            MergeFastqWorker::tr("Output FASTQ file"));

        QMap<Descriptor, DataTypePtr> inM;
        inM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE();
        p << new PortDescriptor(inD, DataTypePtr(new MapDataType("cf.input-url", inM)), true);

        QMap<Descriptor, DataTypePtr> outM;
        outM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE();
        p << new PortDescriptor(outD, DataTypePtr(new MapDataType("cf.output-url", outM)), false, true);
    }

    QList<Attribute*> a;
    {
        Descriptor outDir(BaseNGSWorker::OUT_MODE_ID, MergeFastqWorker::tr("Output directory"),
            MergeFastqWorker::tr("Select an output directory. <b>Custom</b> - specify the output directory in the 'Custom directory' parameter. "
            "<b>Workflow</b> - internal workflow directory. "
            "<b>Input file</b> - the directory of the input file."));

        Descriptor customDir(BaseNGSWorker::CUSTOM_DIR_ID, MergeFastqWorker::tr("Custom directory"),
            MergeFastqWorker::tr("Select the custom output directory."));

        Descriptor outName(BaseNGSWorker::OUT_NAME_ID, MergeFastqWorker::tr("Output file name"),
            MergeFastqWorker::tr("A name of an output file. If default of empty value is provided the output name is the name of the first file with additional extention."));


        a << new Attribute(outDir, BaseTypes::NUM_TYPE(), false, QVariant(FileAndDirectoryUtils::WORKFLOW_INTERNAL));
        Attribute* customDirAttr = new Attribute(customDir, BaseTypes::STRING_TYPE(), false, QVariant(""));
        customDirAttr->addRelation(new VisibilityRelation(BaseNGSWorker::OUT_MODE_ID, FileAndDirectoryUtils::CUSTOM));
        a << customDirAttr;
        a << new Attribute( outName, BaseTypes::STRING_TYPE(), false, QVariant(BaseNGSWorker::DEFAULT_NAME));
    }

    QMap<QString, PropertyDelegate*> delegates;
    {
        QVariantMap directoryMap;
        QString fileDir = MergeFastqWorker::tr("Input file");
        QString workflowDir = MergeFastqWorker::tr("Workflow");
        QString customD = MergeFastqWorker::tr("Custom");
        directoryMap[fileDir] = FileAndDirectoryUtils::FILE_DIRECTORY;
        directoryMap[workflowDir] = FileAndDirectoryUtils::WORKFLOW_INTERNAL;
        directoryMap[customD] = FileAndDirectoryUtils::CUSTOM;
        delegates[BaseNGSWorker::OUT_MODE_ID] = new ComboBoxDelegate(directoryMap);

        delegates[BaseNGSWorker::CUSTOM_DIR_ID] = new URLDelegate("", "", false, true);

    }

    ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a);
    proto->setEditor(new DelegateEditor(delegates));
    proto->setPrompter(new MergeFastqPrompter());

    WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_NGS_BASIC(), proto);
    DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID);
    localDomain->registerEntry(new MergeFastqWorkerFactory());
}
Ejemplo n.º 15
0
void QualityTrimWorkerFactory::init() {
    Descriptor desc( ACTOR_ID, QualityTrimWorker::tr("FASTQ Quality Trimmer"),
        QualityTrimWorker::tr("The workflow scans each input sequence from the end to find the first position where the quality is greater or equal to the minimum quality threshold. "
                              "Then it trims the sequence to that position. If a the whole sequence has quality less than the threshold or the length of the output sequence less than "
                              "the minimum length threshold then the sequence is skipped.") );

    QList<PortDescriptor*> p;
    {
        Descriptor inD(BaseNGSWorker::INPUT_PORT, QualityTrimWorker::tr("Input File"),
            QualityTrimWorker::tr("Set of FASTQ reads files"));
        Descriptor outD(BaseNGSWorker::OUTPUT_PORT, QualityTrimWorker::tr("Output File"),
            QualityTrimWorker::tr("Output FASTQ files"));

        QMap<Descriptor, DataTypePtr> inM;
        inM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE();
        p << new PortDescriptor(inD, DataTypePtr(new MapDataType("cf.input-url", inM)), true);

        QMap<Descriptor, DataTypePtr> outM;
        outM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE();
        p << new PortDescriptor(outD, DataTypePtr(new MapDataType("cf.output-url", outM)), false, true);
    }

    QList<Attribute*> a;
    {
        Descriptor outDir(BaseNGSWorker::OUT_MODE_ID, QualityTrimWorker::tr("Output directory"),
            QualityTrimWorker::tr("Select an output directory. <b>Custom</b> - specify the output directory in the 'Custom directory' parameter. "
            "<b>Workflow</b> - internal workflow directory. "
            "<b>Input file</b> - the directory of the input file."));

        Descriptor customDir(BaseNGSWorker::CUSTOM_DIR_ID, QualityTrimWorker::tr("Custom directory"),
            QualityTrimWorker::tr("Select the custom output directory."));

        Descriptor outName(BaseNGSWorker::OUT_NAME_ID, QualityTrimWorker::tr("Output file name"),
            QualityTrimWorker::tr("A name of an output file. If default of empty value is provided the output name is the name of the first file with additional extention."));

        Descriptor qualT(QUALITY_ID, QualityTrimWorker::tr("Quality threshold"),
            QualityTrimWorker::tr("Quality threshold for trimming."));

        Descriptor lenT(LEN_ID, QualityTrimWorker::tr("Min Length"),
            QualityTrimWorker::tr("Too short reads are discarded by the filter."));

        Descriptor bothD(BOTH_ID, QualityTrimWorker::tr("Trim both ends"),
            QualityTrimWorker::tr("Trim the both ends of a read or not. Usually, you need to set <b>True</b> for <b>Sanger</b> sequencing and <b>False</b> for <b>NGS</b>"));

        a << new Attribute(outDir, BaseTypes::NUM_TYPE(), false, QVariant(FileAndDirectoryUtils::WORKFLOW_INTERNAL));
        Attribute* customDirAttr = new Attribute(customDir, BaseTypes::STRING_TYPE(), false, QVariant(""));
        customDirAttr->addRelation(new VisibilityRelation(BaseNGSWorker::OUT_MODE_ID, FileAndDirectoryUtils::CUSTOM));
        a << customDirAttr;
        a << new Attribute( outName, BaseTypes::STRING_TYPE(), false, QVariant(BaseNGSWorker::DEFAULT_NAME));
        a << new Attribute( qualT, BaseTypes:: NUM_TYPE(), false, QVariant(30));
        a << new Attribute( lenT, BaseTypes::NUM_TYPE(), false, QVariant(0));
        a << new Attribute( bothD, BaseTypes::BOOL_TYPE(), false, true);
    }

    QMap<QString, PropertyDelegate*> delegates;
    {
        QVariantMap directoryMap;
        QString fileDir = QualityTrimWorker::tr("Input file");
        QString workflowDir = QualityTrimWorker::tr("Workflow");
        QString customD = QualityTrimWorker::tr("Custom");
        directoryMap[fileDir] = FileAndDirectoryUtils::FILE_DIRECTORY;
        directoryMap[workflowDir] = FileAndDirectoryUtils::WORKFLOW_INTERNAL;
        directoryMap[customD] = FileAndDirectoryUtils::CUSTOM;
        delegates[BaseNGSWorker::OUT_MODE_ID] = new ComboBoxDelegate(directoryMap);

        delegates[BaseNGSWorker::CUSTOM_DIR_ID] = new URLDelegate("", "", false, true);

        QVariantMap len; len["minimum"] = 0; len["maximum"] = INT_MAX;
        delegates[QUALITY_ID] = new SpinBoxDelegate(len);
        delegates[LEN_ID] = new SpinBoxDelegate(len);
    }

    ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a);
    proto->setEditor(new DelegateEditor(delegates));
    proto->setPrompter(new QualityTrimPrompter());

    WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_NGS_BASIC(), proto);
    DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID);
    localDomain->registerEntry(new QualityTrimWorkerFactory());
}
Ejemplo n.º 16
0
int main(int argc, char* argv[])
{
  if ( argc != 4 ) {
    printf("Usage: %s configFile outputName randomSeed\n", argv[0]);
    printf("You entered %i arguments.\n", argc-1);
    return 0;
  }
   
  const char* configFile = argv[1];
  const char* outArg = argv[2];
  const long int randomSeed = atol(argv[3]);

  char outTrajFile[256];
  char outCurrFile[256];
  sprintf(outTrajFile, "%s.pdb", outArg);
  sprintf(outCurrFile, "curr_%s.dat", outArg);

  printf("Brownian Dynamics initiated with command:\n");
  for (int i = 0; i < argc; i++) printf("%s\n", argv[i]);
 
  // Read the parameter file.
  Reader config(configFile);
  printf("Read config file %s.\n", configFile);
  const int numParams = config.length();
  const int numParts = config.countParameter("particle");
  BrownianParticle* part = new BrownianParticle[numParts];
  String* partGridFile = new String[numParts];
  
  // Set the defaults.
  String outName("out");
  double timestep = 1e-4;
  long int steps = 100;
  int interparticleForce = 1;
  int fullElect = 1;
  double kT = 1.0;
  double coulombConst = 566.440698/92.0;
  double electricField = 0.0;
  double cutoff = 10.0;
  int outPeriod = 200;
  
  // Set other parameters.
  const int decompPeriod = 4;
  const double switchLen = 2.0;
  const double switchStart = cutoff-switchLen;
  const double maxInitialPot = 0.5;

  int currPart = -1;
  for (int i = 0; i < numParams; i++) {
    String param = config.getParameter(i);
    String value = config.getValue(i);

    if (param == String("outName")) outName = value;
    else if (param == String("timestep")) timestep = strtod(value.val(), NULL);
    else if (param == String("steps")) steps = atol(value.val());
    else if (param == String("interparticleForce")) interparticleForce = atoi(value.val());
    else if (param == String("fullElect")) fullElect = atoi(value.val());
    else if (param == String("kT")) kT = strtod(value.val(), NULL);
    else if (param == String("coulombConst")) coulombConst = strtod(value.val(), NULL);
    else if (param == String("electricField")) electricField = strtod(value.val(), NULL);
    else if (param == String("cutoff")) cutoff = strtod(value.val(), NULL);
    else if (param == String("outPeriod")) outPeriod = atoi(value.val());
    else if (param == String("particle")) { currPart++; part[currPart] = BrownianParticle(value); }
    else if (param == String("num")) part[currPart].num = atoi(value.val());
    else if (param == String("gridFile")) partGridFile[currPart] = value;
    else if (param == String("diffusion")) part[currPart].diffusion = strtod(value.val(), NULL);
    else if (param == String("charge")) part[currPart].charge = strtod(value.val(), NULL);
    else if (param == String("radius")) part[currPart].radius = strtod(value.val(), NULL);
    else if (param == String("eps")) part[currPart].eps = strtod(value.val(), NULL);
  }
   
  // Write the parameters.
  printf("\nParameters: \n");
  printf("outName %s\n", outName.val());
  printf("timestep %.10g\n", timestep);
  printf("steps %ld\n", steps);
  printf("interparticleForce %d\n", interparticleForce);
  printf("fullElect %d\n", fullElect);
  printf("kT %.10g\n", kT);
  printf("coulombConst %.10g\n", coulombConst);
  printf("electricField %.10g\n", electricField);
  printf("cutoff %.10g\n", cutoff);
  printf("outPeriod %d\n", outPeriod);
  
  // Write the particles.
  printf("\nParticles:\n");
  
  for (int i = 0; i < numParts; i++) {
    printf("particle %s\n", part[i].name.val());
    printf("num %d\n", part[i].num);
    printf("gridFile %s\n", partGridFile[i].val());
    printf("diffusion %.10g\n", part[i].diffusion);
    printf("charge %.10g\n", part[i].charge);
    printf("radius %.10g\n", part[i].radius);
    printf("eps %.10g\n\n", part[i].eps);
  }

  // Load the potential grids.
  printf("Loading the potential grids...\n");
  for (int i = 0; i < numParts; i++) {
    part[i].grid = new Grid(partGridFile[i].val());
    printf("Loaded %s.\n", partGridFile[i].val());
    printf("System size %s.\n", part[i].grid->getExtent().toString().val());
  }

  // Instantiate the Brownian Dynamics object.
  BrownTown brown(kT, timestep, *(part[0].grid));
  brown.setPeriodic(1,1,1);

 // Seed the random number generator. 
 long int randomSeed1 = randomSeed;
  for (int i = 0; i < 4; i++) randomSeed1 *= randomSeed1 + 1;
  int seed = (unsigned int)time((time_t *)NULL) + randomSeed1;
  printf("\nRandom number generator seed: %i\n", seed);
  Random randoGen(seed);

  // Get the total number of particles.
  int num = 0;
  for (int i = 0; i < numParts; i++) num += part[i].num;

  // Get the system dimensions.
  Vector3 sysDim = part[0].grid->getExtent();
  Vector3 origin = part[0].grid->getOrigin();
  Vector3 destin = part[0].grid->getDestination();
  
  // Set initial conditions.
  Vector3* pos = new Vector3[num];
  Vector3* pos1 = new Vector3[num];
  Vector3* posLast = new Vector3[num];
  int* type = new int[num];
  String* name = new String[num];
  int pn = 0;
  int p = 0;
  for (int i = 0; i < num; i++) {
    type[i] = p;
    name[i] = part[p].name;

    // Get the initial positions.
     do {
      pos[i] = brown.wrap(Vector3(sysDim.x*randoGen.uniform(),
				  sysDim.y*randoGen.uniform(),
				  sysDim.z*randoGen.uniform()));
    } while (part[type[i]].grid->interpolatePotential(pos[i]) > maxInitialPot);
    //pos[i] = part[0].grid->getCenter();
    pos1[i] = pos[i];
    posLast[i] = pos[i];

    pn++;
    if (pn >= part[p].num) {
      p++;
      pn = 0;
    }

  }

  // Trajectory PDB
  writePdbTraj(outTrajFile, pos, name, num, sysDim, 0.0); 
  //FILE* out = fopen(outCurrFile, "w");

  // Prepare the force object.
  ComputeForce internal(num, part, numParts, *(part[0].grid), switchStart, switchLen, coulombConst);
  internal.decompose(pos);
  Vector3* forceInternal = new Vector3[num];
  for (int i = 0; i < num; i++) forceInternal[i] = 0.0;
  Vector3 rando = randoGen.gaussian_vector();
  ////////////////////////////////////////////////////////////////
  // Run the Brownian Dynamics steps.
  clock_t clock0 = clock();
  for (long int s = 0; s < steps; s++) {
    // Compute the internal forces.
    if (interparticleForce) {
       switch (fullElect) {
      case 0:
	// Remake the cell decomposition.
	if (s % decompPeriod == 0) internal.decompose(pos);
	// Compute using the cell decomposition.
	internal.compute(forceInternal, pos, type);
	break;
      case 1:
	// Compute long range electrostatic forces.
	internal.computeFull(forceInternal, pos, type);
	break;
      case 2:
	// Compute only hardcore forces.
	internal.computeHardcoreFull(forceInternal, pos, type);
	break;
      }
    }
    
    // Loop through the particles.
    for (int i = 0; i < num; i++) {
      // Compute the external forces.
      Vector3 forceExternal = Vector3(0.0, 0.0, part[type[i]].charge*electricField);
      Vector3 forceGrid = part[type[i]].grid->interpolateForce(pos[i]);
      //Vector3 forceGrid = 0.0;

      // Compute the total force.
      Vector3 force = forceInternal[i] + forceExternal + forceGrid;

      // Get the random kick.
      Vector3 rando = randoGen.gaussian_vector();

      // Step
      pos1[i] = brown.stepPeriodic(pos[i], force, rando, part[type[i]].diffusion);
    }

    if (s % outPeriod == 0) {
      appendPdbTraj(outTrajFile, pos1, name, num, sysDim, 0.0);

      //computeCurrent(pos1, posLast);
      for (int i = 0; i < num; i++) posLast[i] = pos1[i];

      if (s % (10*outPeriod) == 0) {
	double percent = (100.0*s)/steps;
	clock_t clock1 = clock();
	double stepTime = diffclock(clock0, clock1)/(10*outPeriod);
	printf("step %ld, time %g, %.2f percent complete, %.1f ms/step\n", s, s*timestep, percent, stepTime);
	clock0 = clock1;
      }
    }
    
    // Swap the position pointers.
    Vector3* temp = pos;
    pos = pos1;
    pos1 = temp;
  }
  //fclose(out);


  delete[] pos;
  delete[] pos1;
  delete[] posLast;
  delete[] type;
  delete[] name;
  delete[] part;
  delete[] partGridFile;
  delete[] forceInternal;

  return 0;
}