Пример #1
0
int main(int argc, char *argv[]) {

	int cmd_line_char, long_index;

	struct files requiredFiles;
	struct data taxInfo;

	const struct option longopts[] = {
		{"version", no_argument, 0, 'v'},
		{"help", no_argument, 0, 'h'},
		{"outfile", required_argument, 0, 'o'},
		{"fastq", required_argument, 0, 'f'},
		{"fixrank", required_argument, 0, 'r'},
		{"tax_level", required_argument, 0, 'l'},
		{"name", required_argument, 0, 'n',},
		{0, 0, 0, 0}
	};
	
	while ((cmd_line_char = getopt_long(argc, argv, "vho:f:r:l:n:", longopts, &long_index)) != EOF) {
		switch(cmd_line_char) {
            case 'h':
                printf("To use butter cup, please supply -o outputfile -f fastq file -r fixrank file and -l taxLevel -n tax Name\n");
                printf("./Buttercup -o buttercup.out.fq -f <(zcat /mnt/home/alida/scratch/pplacer/vag_cancer/cancer.extendedFrags.fastq.gz) -r /mnt/home/alida/scratch/pplacer/vag_cancer/classify.fixrank -l genus -n Lactobacillus\n\n");
                exit(0);
			case 'o':
				requiredFiles.outfile = fopen(optarg, "w");
				if (requiredFiles.outfile == NULL) {
					errorOut(&requiredFiles, &taxInfo);
				}
				break;
			case 'f':
				requiredFiles.fastq = fopen(optarg, "r");
				if (requiredFiles.fastq == NULL) {
					errorOut(&requiredFiles, &taxInfo);
				}
				break;
			case 'r':
				requiredFiles.fixrank = fopen(optarg, "r");
				if (requiredFiles.fixrank == NULL) {
					errorOut(&requiredFiles, &taxInfo);
				}
				break;
			case 'l':
				taxInfo.taxlevel = strdup(optarg);
				break;
			case 'n':
				taxInfo.name = strdup(optarg);
				break;
		}
		
	}

	CreateSearchTree(&requiredFiles, &taxInfo);
	
	return 0;

}
Пример #2
0
void shutdownServer( int signal )
{
	if(hasShutdown)
		return;
	hasShutdown = true;
	serverRunning = false;
	serverSock.disconnect();
	saveWeapons("weapons.txt");
	serverFlags.save("serverflags.txt");
	for(int i = playerList.count()-1; i >= 0; i--)
		delete ((CPlayer*)playerList[i]);

	if(lsConnected)
		ListServer_End();

	for(int i = 0; i < levelList.count(); i++)
	{
		CLevel* level = (CLevel*)levelList[i];
		level->saveNpcs();
		delete level;
	}

	for(int i = 0; i < CMap::mapList.count(); i++)
		delete((CMap*)CMap::mapList[i]);

	for(int i = 0; i < weaponList.count(); i++)
		delete ((CWeapon*)weaponList[i]);

	errorOut("serverlog.txt", "Server shutdown.");

	#ifdef PSPSDK
		sceKernelExitGame();
	#endif
}
Пример #3
0
std::string getErrnoString(int errnum)
{
    std::ostringstream msg;
    msg << "errno " << errnum << ": ";
    errorOut(msg, errnum);
    return msg.str();
}
Пример #4
0
/******************************************************************************
 * Determine color contribution of a lightsource (Phong model)
 * Specular part is returned in seperate parameter and added later
 *****************************************************************************/
const ntlColor
ntlLightObject::getShadedColor(const ntlRay &reflectedRay, const ntlVec3Gfx lightDir,
															 ntlMaterial *surf, ntlColor &highlight) const
{
  gfxReal ldot = dot(lightDir, reflectedRay.getNormal()); /* equals cos( angle(L,N) ) */
  ntlColor reflected_color = ntlColor(0.0);  /* adds up to total reflected color */
	if(mpGlob->getDebugOut() > 5) errorOut("Lighting dir:"<<lightDir<<"  norm:"<<reflectedRay.getNormal()<<"  "<<ldot );

  /* lambertian reflection model */
  if (ldot > 0.0) {
		//ldot *= -1.0;
    reflected_color += surf->getDiffuseRefl() * (getColor() * ldot );

    /* specular part */
    /* specular reflection only makes sense, when the light is facing the surface,
       as the highlight is supposed to be a reflection of the lightsource, it cannot
       be reflected on surfaces with ldot<=0, as this means the arc between light 
       and normal is more than 90 degrees. If this isn't done, ugly moiree patterns appear
       in the highlights, and refractions have strange patterns due to highlights on the
       inside of the surface */
    gfxReal spec = dot(reflectedRay.getDirection(), lightDir); // equals cos( angle(R,L) )
    if((spec > 0.0) && (surf->getSpecular()>0)) {
      spec = pow( spec, surf->getSpecExponent() ); /* phong exponent */
      highlight += getColor() * surf->getSpecular() * spec;
			//errorOut( " "<< surf->getName() <<" S "<<highlight<<" "<<spec<<" "<<surf->getSpecular()<<" "<<surf->getSpecExponent() );
    }

  }

  return ntlColor(reflected_color);
}
Пример #5
0
void setUpServerSocket(int &sSocket, struct sockaddr_in &address, int port) {
	sSocket = socket(AF_INET, SOCK_STREAM, 0);
        if(sSocket == ERROR) {
               errorOut("Couldn't start server socket");
        }   
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons(port);
        address.sin_family = AF_INET;
        if(bind(sSocket, (struct sockaddr*)&address, sizeof(address)) == ERROR) {
                errorOut("Couldn't bind address to socket");
        }   
        int addressSize = sizeof(struct sockaddr_in);
        getsockname(sSocket, (struct sockaddr*)&address, (socklen_t*)&addressSize);
        if(listen(sSocket, QUEUE_SIZE) == ERROR) {
		errorOut("Couldn't listen on socket");
        }   

}
Пример #6
0
    void EtherIPC::bail(bool soft) {
        qDebug() << "BAIL[" << soft << "]: " << fError << "\n";

        if ( !soft ) {
            fTimer.stop();
            fRequestQueue.clear();
        }

        fActiveRequest = RequestIPC(None);
        errorOut();
    }
Пример #7
0
bool CLevel::loadZelda(CString& pFileName)
{
	CPacket levelData;
	CString version;
	char* dataFile = getDataFile(pFileName.text());
	if(!strlen(dataFile))
		return false;
	if(!levelData.load(dataFile))
		return false;
	fileName = pFileName;
	modTime = getFileModTime(dataFile);
	version = levelData.readChars(8);

	// Some clients will actually save .zelda levels as .graal.
	// If this is the case, parse it through the .graal loader.
	if (version.copy(0, 2) == "GR")
		return loadGraal(pFileName);

	bool v0 = (version == "unknown");
	bool v1 = (version == "unknown");
	bool v2 = (version == "unknown");
	bool v3 = (version == "Z3-V1.03");
	bool v4 = (version == "Z3-V1.04");

	// If we encountered an unknown version, ask the user to send it in so we can add support for it.
	if (!v3 && !v4)
	{
		errorOut("errorlog.txt", CString() << "Level " << fileName << " is of version " << version << ".  That version is unknown.  Please send us the level so we may add support for it.", true);
		return false;
	}

	loadTiles(levelData, version);
	loadLinks(levelData);
	loadBaddies(levelData);
	loadSigns(levelData);

	//Find our map id
	for(int i = 0; i < CMap::mapList.count(); i++)
	{
		CMap* m = (CMap*)CMap::mapList[i];
		if((levelIndex = m->getLevelpos(pFileName)) >= 0)
		{
			map = m;
			break;
		}
	}

	return true;
}
Пример #8
0
void ListServer_Connect()
{
	if ((lsConnected = listServer.connect(findKey("listip"), atoi(findKey("listport")))) == false)
	{
		errorOut("rclog.txt", "Unable to connect to list server", true);
		return;
	}

	errorOut("rclog.txt", "Connected to the list server successfully\n", true);
	listServer.setSync(false);

	// send gserver info to listserver
	ListServer_Send(CPacket() << (char)SLSNAME << listServerFields[0]  << "\n" << (char)SLSDESC << listServerFields[1]  << "\n" << (char)SLSLANG << listServerFields[2]  << "\n" << (char)SLSVER  << listServerFields[3]  << "\n" << (char)SLSURL  << listServerFields[4]  << "\n" << (char)SLSIP   << listServerFields[5]  << "\n" << (char)SLSPORT << toString(serverPort) << "\n");

	// send players to listserver
	CPacket pPacket;
	for (int i = 0; i < playerList.count(); i++)
	{
		CPlayer *player = (CPlayer *)playerList[i];
		pPacket << (char)player->accountName.length() << player->accountName << player->getProp(NICKNAME) << player->getProp(CURLEVEL) << player->getProp(PLAYERX) << player->getProp(PLAYERY) << player->getProp(PALIGNMENT) << (char)player->type;
	}

	ListServer_Send(CPacket() << (char)SLSCOUNT << (char)playerList.count() << pPacket << "\n");
}
Пример #9
0
/******************************************************************************
 * Illuminate the given point on an object
 *****************************************************************************/
ntlColor ntlLightObject::illuminatePoint(ntlRay &reflectedRay, ntlGeometryObject *closest,
																			 ntlColor &highlight )
{
	/* is this light active? */
	if(!mActive) { return ntlColor(0.0); }

	gfxReal visibility = 1.0;   // how much of light is visible
	ntlVec3Gfx intersectionPos = reflectedRay.getOrigin();
	ntlColor current_color = ntlColor(0.0);
	ntlMaterial *clossurf = closest->getMaterial();

	ntlVec3Gfx lightDir = (mvPosition - intersectionPos);
	gfxReal lightDirNorm = normalize(lightDir);

	// where is the lightsource ?
	ntlRay rayOfLight(intersectionPos, lightDir, 0, 1.0, mpGlob );
	
	if( (1) && (mCastShadows)&&(closest->getReceiveShadows()) ) {
		ntlTriangle *tri;
		ntlVec3Gfx triNormal;
		gfxReal trit;
		mpGlob->getRenderScene()->intersectScene(rayOfLight, trit, triNormal, tri, TRI_CASTSHADOWS);
		if(( trit>0 )&&( trit<lightDirNorm )) visibility = 0.0;
		if(mpGlob->getDebugOut() > 5) errorOut("Omni lighting with "<<visibility );
	}
	
	/* is light partly visible ? */
//? visibility=1.;
	if (visibility>0.0) {
		ntlColor highTemp(0.0); // temporary highlight color to multiply highTemp with offFac
		current_color = getShadedColor(reflectedRay, lightDir, clossurf, highTemp) * visibility;
		highlight += highTemp * visibility;
		if(mpGlob->getDebugOut() > 5) errorOut("Omni lighting color "<<current_color );
	}
	return current_color;
}
Пример #10
0
void
receiver::write() const
{

	std::ofstream myfile;
	std::string full = mSr.name;
	myfile.open(full.c_str(), std::ios::out);

	if (! myfile.is_open()) errorOut("Problem opening receiver file.");
	myfile << "# SALVUS RECEIVER\n";
	myfile << "# XLOC: " << mSr.xLoc << "\n";
	myfile << "# YLOC: " << mSr.yLoc << "\n";
	for (auto i=0; i<mUx.size(); i++)
	{myfile << mUx[i] << " " << mUy[i] << std::endl;}
}
Пример #11
0
void sstvRx::run(DSPFLOAT *dataPtr, unsigned int *inputVolumePtr)
{
  bufferCounter++;
  if(videoFilterPtr==NULL)
    {
      errorOut() << "videoFltr NULL";
      return;
    }
  videoFilterPtr->process(dataPtr);
  bufferVideoDemod.putNoCheck(videoFilterPtr->demodPtr,RXSTRIPE);
  syncFilterPtr->process(dataPtr);
  //  bufferSyncDemod.putNoCheck(syncFilterPtr->demodPtr,RXSTRIPE);
  bufferSync1200Vol.putNoCheck(syncFilterPtr->detect1200Ptr,RXSTRIPE);
  bufferSync1900Vol.putNoCheck(syncFilterPtr->detect1900Ptr,RXSTRIPE);
  //  bufferSyncVol.putNoCheck(syncFilterPtr->test1Ptr,RXSTRIPE);
  //  bufferTest.putNoCheck(syncFilterPtr->test2Ptr,RXSTRIPE);
  bufferInputVol.putNoCheck(inputVolumePtr,RXSTRIPE);

  while (bufferVideoDemod.count())
    {
      syncWideProc.freqPtr=bufferVideoDemod.readPointer();
      syncNarrowProc.freqPtr=bufferVideoDemod.readPointer();
      syncWideProc.syncVolumePtr =bufferSync1200Vol.readPointer();
      syncNarrowProc.syncVolumePtr =bufferSync1900Vol.readPointer();
      syncWideProc.inputVolumePtr=bufferInputVol.readPointer();
      syncNarrowProc.inputVolumePtr=bufferInputVol.readPointer();

      displaySyncEvent* ce;
      if(syncProcPtr)
        {
          ce = new displaySyncEvent(syncProcPtr->syncQuality);
        }
      else
        {
          ce = new displaySyncEvent(0);
        }
      QApplication::postEvent(dispatcherPtr, ce);
#ifndef QT_NO_DEBUG
      scopeViewerData->addData(SCDATA2,dataPtr,syncWideProc.sampleCounter,RXSTRIPE);
      scopeViewerData->addData(SCDATA4,bufferVideoDemod.readPointer(),syncWideProc.sampleCounter,RXSTRIPE);
#endif

      process();
    }
  //  addToLog(QString("After process readIndex:=%1 sampleCounter:=%2").arg(bufferVideoDemod.getReadIndex()).arg(syncProcPtr->sampleCounter),LOGRXFUNC);
}
Пример #12
0
void* handleConnection(void* connPtr){
	struct ConnInfo conn = *((struct ConnInfo*)connPtr);
	int pSocket = conn.socket;
	string root = conn.root;
	linger lin;
	unsigned int y=sizeof(lin);
	lin.l_onoff=1;
	lin.l_linger=10;
	setsockopt(pSocket,SOL_SOCKET, SO_LINGER,&lin,sizeof(lin));
	struct Request request = getRequest(pSocket);
	string path = joinPath(root, request.path);
	respond(pSocket, request.version, path, request.path);
	shutdown(pSocket, SHUT_RDWR);
	if(close(pSocket) == ERROR) {
		errorOut("Couldn't close message socket");
	}
}
void buffered_on_read(struct bufferevent *bev, void *arg) {
	client_t *client = (client_t *)arg;
	char data[4096];
	int nbytes;

	while (bev->input->off > 0) {
		nbytes = (bev->input->off > 4096) ? 4096 : bev->input->off;
		evbuffer_remove(bev->input, data, nbytes);
		evbuffer_add(client->output_buffer, data, nbytes);

	}

	if (bufferevent_write_buffer(bev, client->output_buffer)) {
		errorOut("Error sending data to client on fd %d\n", client->fd);
		closeClient(client);
	}
}
Пример #14
0
void runServer(int port, int numThreads, string root) {
	int sSocket;
	struct sockaddr_in address;
	setUpServerSocket(sSocket, address, port);
	int addressSize = sizeof(struct sockaddr_in);
	pthread_t threads[numThreads];
	int activeThreads = 0;
	while(1) {
		int pSocket = accept(sSocket, (struct sockaddr*)&address, (socklen_t*)&addressSize);
		struct ConnInfo connInfo;
		connInfo.socket = pSocket;
		connInfo.root = root;
		activeThreads++;
		pthread_create(&threads[activeThreads - 1], NULL, handleConnection, (void*)&connInfo);
	}
	//pthread_exit(NULL);
	if(close(sSocket) == ERROR) {
		errorOut("Couldn't close server socket");
	}
}
Пример #15
0
		bool generateOutput(const string& fileContents, const string& outputBitCodeName) {
			// Parse the source file
			//cout << "Parsing..." << endl;
			base_expr_node rootAst;
			if (!parse(fileContents, rootAst)) {
				cerr << "Failed to parse source file!" << endl;
				return false;
			}

			// Generate the code
			//cout << "Generating code..." << endl;
			LLVMContext &context = getGlobalContext();
			unique_ptr<Module> module(new Module("", context));
			IRBuilder<> builder(getGlobalContext());

			ast_codegen codeGenerator(module.get(), builder);

			// Generate code for each expression at the root level
			const base_expr* expr = boost::get<base_expr>(&rootAst);
			for (auto& itr : expr->children) {
				boost::apply_visitor(codeGenerator, itr);
			}

			// Perform an LLVM verify as a sanity check
			string errorInfo;
			raw_string_ostream errorOut(errorInfo);

			if (verifyModule(*module, &errorOut)) {
				cerr << "Failed to generate LLVM IR: " << errorInfo << endl;

				module->print(errorOut, nullptr);
				cerr << "Module:" << endl << errorInfo << endl;
				return false;
			}

			// Dump the LLVM IR to a file
			llvm::raw_fd_ostream outStream(outputBitCodeName.c_str(), errorInfo, llvm::sys::fs::F_None);
			llvm::WriteBitcodeToFile(module.get(), outStream);

			return true;
		}
Пример #16
0
void ListServer_SendServerHQ()
{
	if ( serverRunning == false ) return;
	if ( listServerFields[5] == "localhost" ) return;

	if (!lsConnected)
	{
		ListServer_Connect();
		if (!lsConnected)
			return;
	}

	CPacket packet;
	packet << (char)SLSSERVERHQPASS << serverhq_pass << "\n";
	packet << (char)SLSSERVERHQLEVEL << (char)serverhq_level << "\n";
	if (listServer.sendData(packet) < 0)
	{
		errorOut("serverlog.txt", "Disconnected from list server.");
		lsConnected = false;
	}
}
Пример #17
0
void ListServer_Send(CPacket &pPacket)
{
	if ( serverRunning == false ) return;
	if ( listServerFields[5] == "localhost" ) return;

	if (!lsConnected)
	{
		ListServer_Connect();
		if (!lsConnected)
			return;
	}

	// Make sure a newline is sent after the message.
	if ( pPacket[ pPacket.length() - 1 ] != '\n' )
		pPacket << "\n";

	if ( listServer.sendData( pPacket ) < 0 )
	{
		errorOut("serverlog.txt", "Disconnected from list server.");
		lsConnected = false;
	}
}
Пример #18
0
std::string getErrnoString(int errnum, const char* fn)
{
    if (errnum != 0)
    {
        std::ostringstream msg;
        if (fn && fn[0])
            msg << "error " << errnum << " in function " << fn << ": ";
        else
            msg << "error " << errnum << ": ";
        errorOut(msg, errnum);
        return msg.str();
    }
    else if (fn && fn[0])
    {
        std::ostringstream msg;
        msg << "function " << fn << " failed with unknown error";
        return msg.str();
    }
    else
    {
        return "unknown error";
    }
}
Пример #19
0
/**
 * Called by libevent when there is data to read.
 */
void buffered_on_read(struct bufferevent *bev, void *arg) {
	client_t *client = (client_t *)arg;
	char data[4096];
	int nbytes;

	/* Copy the data from the input buffer to the output buffer in 4096-byte chunks.
	 * There is a one-liner to do the whole thing in one shot, but the purpose of this server
	 * is to show actual real-world reading and writing of the input and output buffers,
	 * so we won't take that shortcut here. */
	while ((nbytes = EVBUFFER_LENGTH(bev->input)) > 0) {
		/* Remove a chunk of data from the input buffer, copying it into our local array (data). */
		if (nbytes > 4096) nbytes = 4096;
		evbuffer_remove(bev->input, data, nbytes); 
		/* Add the chunk of data from our local array (data) to the client's output buffer. */
		evbuffer_add(client->output_buffer, data, nbytes);
	}

	/* Send the results to the client.  This actually only queues the results for sending.
	 * Sending will occur asynchronously, handled by libevent. */
	if (bufferevent_write_buffer(bev, client->output_buffer)) {
		errorOut("Error sending data to client on fd %d\n", client->fd);
		closeClient(client);
	}
}
Пример #20
0
parVectorMap parser::parsear(ifstream* fich, bool verbose) {
  // Inicialización de variables implicadas
  errores = 0;
  countLine = 0;
  estado = 0;
  etiquetasCompletamenteDefinidas = 0;
  etiquetasPendientes = 0;
  traducirEtiqueta("string para ocupar la posición 0, no tiene utilidad");
  bool comentario = false;
  // Inicialización de las expresiones regulares implicadas
  regex coments("(;)(.*)");
  regex igual("^(.*)(=)(.*)$");
  regex estrella("^(.*)(\\*)(.*)$");
  regex tag("^(.*)(:)$");
  regex salto("^[jJ](.*)");
  regex digito("^(.*)[[:digit:]]+");
  regex halt("(halt)|(HALT)");
  // Declaración de variables auxiliares
  string buff;
  string linea;
  instruccionTemp tmpIns;
  std::vector<char> v;
  while (getline(*fich, linea)) {
    countLine++;
    istringstream flujo(linea);
    string token;
    tmpIns = instruccionTemp();
    while (flujo >> token) {
      bool palabraReservada = false;
      if (verbose) {
        cout << endl << token << "\t";
      }
      if (regex_match(token, coments)) {
        // si encontramos ';' saltar a la siguiente línea
        if (verbose) {
          cout << "Comentario, saltando línea";
        }
        comentario = true;
        break;
      } else if (regex_match(token, halt)) {
        if (verbose) {
          cout << "Fin del programa";
        }
        tmpIns.opcode = HALT;
      } else {
        if (regex_match(token, igual) || regex_match(token, estrella)) {
          if (estado == 1 || estado == 5) {
            if (estado == 1) tmpIns.opcode = traducirOpcode(buff);
            // Lo siguiente será un número
            if (token[0] == '=') {
              if (tmpIns.opcode != 1 && tmpIns.opcode != 2) {
                tmpIns.especial = IGUAL;
              } else {
                cout << "[!] Error, la codificación '=' es inválida para las "
                        "instrucciones READ Y STORE\n";
                break;
              }
            } else {
              tmpIns.especial = ESTRELLA;
            }
            if (verbose) {
              cout << "Instrucción compleja '" << token[0] << "' ";
            }
            token = token.substr(1);
            palabraReservada = true;
            estado = 4;
          } else {
            errorOut(token);
          }
        }
        if (regex_match(token, digito)) {
          if (estado == 1) {
            // Fin de instrucción simple
            tmpIns.operando = atoi(token.c_str());
            if (verbose) {
              cout << "Instrucción simple, '" << buff << "' fue el opcode "
                   << traducirOpcode(buff) << endl;
            }
            tmpIns.opcode = traducirOpcode(buff);
            estado = 0;
            palabraReservada = true;
          } else if (estado == 5 || estado == 4) {
            // Fin de instrucción compuesta
            tmpIns.operando = atoi(token.c_str());
            if (verbose) {
              cout << " de valor " << atoi(token.c_str()) << ", '" << buff
                   << "' fue el opcode " << traducirOpcode(buff) << endl;
            }
            tmpIns.opcode = traducirOpcode(buff);
            estado = 0;
            palabraReservada = true;
          } else {
            errorOut(token);
          }
        }
        if (regex_match(token, tag)) {
          if (estado == 1) {
            // Lo siguiente será el descriptor de etiqueta
            etiqueta_indice.insert(pair<short, int>(
                traducirEtiqueta(buff), (vectorInstrucciones.size())));
            if (verbose) {
              cout << "Ahora espero un opcode, '" << buff
                   << "' era la etiqueta de entrada " << traducirEtiqueta(buff);
            }
            estado = 3;
            palabraReservada = true;
          } else if (estado == 0) {
            // lo siguiente será un opcode
            string aux = token.substr(0, token.size() - 1);
            etiqueta_indice.insert(pair<short, int>(
                traducirEtiqueta(aux), (vectorInstrucciones.size())));
            if (verbose) {
              cout << "Ahora espero un opcode, '" << aux
                   << "' es la etiqueta de entrada " << traducirEtiqueta(buff);
            }
            estado = 3;
            palabraReservada = true;
          } else {
            errorOut(token);
          }
        }
        if (regex_match(token, salto)) {
          if (estado == 1 || estado == 3 || estado == 0) {
            // Lo siguiente será el descriptor de etiqueta
            tmpIns.opcode = traducirOpcode(token);
            etiquetasPendientes++;
            if (verbose) {
              cout << "Esto es un salto, ahora espero una etiqueta a la que "
                      "saltar";
            }
            estado = 2;
            palabraReservada = true;
          } else {
            errorOut(token);
          }
        }
        if (!palabraReservada) {
          if (estado == 0) {
            // cargamos en el buffer el token en espera de averiguar si es una
            // instrucción o una etiqueta
            if (verbose) {
              cout << "Guardado en buffer";
            }
            estado = 1;
            buff = token;
          } else if (estado == 3) {
            // lo obtenido es el opcode de la instrucción
            if (verbose) {
              cout << "Este es el opcode " << traducirOpcode(token);
            }
            tmpIns.opcode = traducirOpcode(token);
            estado = 5;
            buff = token;
          } else if (estado == 2) {
            // lo obtenido es la etiqueta a la que se salta
            tmpIns.tagSalida = traducirEtiqueta(token);
            if (verbose) {
              cout << "Esta es la etiqueta de salida " << tmpIns.tagSalida
                   << endl;
            }
            estado = 0;
          } else {
            errorOut(token);
          }
        }
      }
    }
    // construir instrucción
    if (tmpIns.opcode > -1)  //! comentario
      vectorInstrucciones.push_back(crearInstruccion(tmpIns));
    comentario = false;
  }
  parVectorMap resultado;
  if (etiquetasCompletamenteDefinidas < etiquetasPendientes) {
    cout << "[!] Error, existen saltos a etiquetas sin definir" << endl;
    errores++;
  }
  cout << endl << endl;
  if (errores == 0)
    resultado = {etiqueta_indice, vectorInstrucciones};
  else
    resultado = {etiqueta_indice, vector<instruccion*>(0)};
  return resultado;
}
Пример #21
0
int main(int argc, char *argv[])
{
	#ifdef PSPSDK
		pspDebugScreenInit();
		SetupCallbacks();
	#else
		// Shut down the server if we get a kill signal.
		signal( SIGINT, (sighandler_t) shutdownServer );
		signal( SIGTERM, (sighandler_t) shutdownServer );
	#endif

	/* Setup Data-Directory */
	dataDir = CBuffer(argv[0]).replaceAll("\\", "/");
	dataDir = dataDir.copy(0, dataDir.findl('/') + 1);
	programDir = dataDir;
	dataDir << "world/";

	/* Main Initiating */
	adminNames.load( __admin, sizeof(__admin) / sizeof(const char*) );
	colourNames.load( __colours, sizeof(__colours) / sizeof(const char*) );
	clothCommands.load( __cloths, sizeof(__cloths) / sizeof(const char*) );
	defaultFiles.load( __defaultfiles, sizeof(__defaultfiles) / sizeof(const char*) );
	playerIds.add(0);
	playerIds.add(0);
	npcIds.add(0);
	srand((int)time(NULL));

	/* Load Important Files */
	updateFile("rchelp.txt");
	updateFile("rcmessage.txt");
	updateFile("rules.txt");
	updateFile("serverflags.txt");
	updateFile("servermessage.html");
	updateFile("foldersconfig.txt");

	/* Load Settings */
	if (!loadSettings("serveroptions.txt"))
	{
		errorOut("errorlog.txt", "Unable to load server settings..");
		return 1;
	}

	/* Load Weapons */
	if (!loadWeapons("weapons.txt"))
	{
		errorOut("errorlog.txt", "Unable to load weapons from weapons.txt..");
		return 1;
	}

	/* Initialize Sockets */
	serverSock.setType( SOCKET_TYPE_SERVER );
	serverSock.setProtocol( SOCKET_PROTOCOL_TCP );
	serverSock.setOptions( SOCKET_OPTION_NONBLOCKING );
	serverSock.setDescription( "serverSock" );
	CString empty;
	if ( serverSock.init( empty, serverPort ) )
		return 1;

	// Connect server socket.
	if ( serverSock.connect() )
	{
		errorOut("errorlog.txt", CString() << "SOCK ERROR: Unable to listen on port: " << serverPort);
		return 1;
	}

	/* Server Finished Loading */
	printf("GServer 2 by 39ster\nSpecial thanks to Marlon, Agret, Pac300, 39ster and others for porting the \noriginal 1.39 gserver to 2.1\nServer listening on port: %s\nServer version: Build %s\n\n", serverPort.text(), listServerFields[3].text());
	errorOut("serverlog.txt", "Server started");

	if ( listServerFields[5] == "localhost" )
		errorOut("serverlog.txt", "[DEBUG_LOCALHOSTMODE] Localhost mode is activated.\nListserver communication & account authentication are disabled.", true);

	serverRunning = true;

	if ( !(listServerFields[5] == "localhost") )
		if (!lsConnected)
			ListServer_Connect();

	while (serverRunning)
	{
		long long second = time(NULL);

		while (second == time(NULL))
		{
			acceptNewPlayers(serverSock);
			for (int i = 0; i < newPlayers.count(); i ++)
			{
				CPlayer* player = (CPlayer*)newPlayers[i];
				player->main();
				if (player->deleteMe)
				{
					delete player;
					i--;
				}
			}

			for(int i = 0; i < playerList.count(); i++)
			{
				CPlayer* player = (CPlayer*)playerList[i];
				player->main();
				if(player->deleteMe)
				{
					delete player;
					i--;
				}
			}

			// Was moved so it can process faster. - Joey
			ListServer_Main();
			wait(10);
		}

		doTimer();
		gameTime ++;
		NOLEVEL->reset();

		// Every 30 seconds
		if (gameTime % 30 == 0)
		{
			ListServer_Send(CPacket() << (char)SLSPING << "\n");
		}

		// Every 10 seconds
		if (gameTime % 10 == 0)
		{
			CPacket pPacket;
			CString file;

			for (int i = 0; i < playerList.count(); i++)
			{
				CPlayer *player = (CPlayer *)playerList[i];
				file << player->accountName << "," << player->nickName << "," << player->levelName << "," << toString(player->x) << "," << toString(player->y) << "," << toString(player->ap) << "\n";
			}

			file.save("logs/playerlist.txt");
			serverFlags.save("serverflags.txt");
		}

		//Every 5 seconds?
		int current = getNWTime();
		if (nwTime != current)
		{
			nwTime = current;
			for (int i = 0; i < playerList.count(); i++)
			{
				CPacket out;
				out << (char)NEWWORLDTIME;
				out.writeByte4(current);
				((CPlayer*)playerList[i])->sendPacket(out);
			}
		}
	}
}
Пример #22
0
/**
 * @brief	Main routine for SPI example
 * @return	Function should not exit
 */
int main(void)
{
    uint32_t memSize, *devMem;
    ROM_SPIS_INIT_T spisInit;
    ROM_SPIS_SLAVE_T spisConfig;
    int i;

    /* Generic Initialization */
    SystemCoreClockUpdate();
    Board_Init();

    /* Setup I2C pin muxing, enable S{I clock and reset I peripheral */
    Init_SPI_PinMux();
    Chip_Clock_EnablePeriphClock(LPC_SPIS_CLOCK);
    Chip_SYSCON_PeriphReset(LPC_SPIS_RESET);

    /* Get needed size for driver context memory */
    memSize = ROM_SPIS_GetMemSize();
    if (memSize > sizeof(drvData)) {
        errorOut("Can't allocate memory for SPIS driver context\r\n");
    }
    devMem = drvData;	/* Or just use malloc(memSize) */

    /* Initialize driver */
    spisInit.pUserData = (void *) &xferDone;
    spisInit.base = (uint32_t) LPC_SPIS_PORT;
    spisInit.spiPol[0] = 0;	/* Active low select for SSEL0 */
    spisInit.spiPol[1] = 0;
    spisInit.spiPol[2] = 0;
    spisInit.spiPol[3] = 0;
    spisHandle = ROM_SPIS_Init(devMem, &spisInit);
    if (spisHandle == NULL) {
        /* Error initializing SPI */
        errorOut("Error initializing ROM\r\n");
    }

    /* Set SPI transfer configuration */
    spisConfig.mode = ROM_SPI_CLOCK_MODE0;
    spisConfig.lsbFirst = 0;
    spisConfig.dataBits = 8;
    if (ROM_SPIS_SetupSlave(spisHandle, &spisConfig) != LPC_OK) {
        errorOut("SPI configuration is invalid\r\n");
    }

    /* Callback registration  */
    ROM_SPIS_RegisterCallback(spisHandle, ROM_SPIS_ASSERTSSEL_CB, (void *) CBspiSlaveXferCSAssertCB);
    ROM_SPIS_RegisterCallback(spisHandle, ROM_SPIS_DEASSERTSSEL_CB, (void *) CBspiSlaveXferCSDeAssertCB);

    DEBUGSTR("SPI slave example\r\n");

    /* Enable the interrupt for the SPI */
    NVIC_EnableIRQ(LPC_SPIIRQNUM);

    /* Read data as fast as possible in loop */
    while (1) {
        /* Setup transfer buffers and maximum transfer sizes, no transfer flags */
        sXfer.txBuff = tx16;
        sXfer.txSz = BUFFSENDSIZE;
        sXfer.rxBuff = rx16;
        sXfer.rxSz = BUFFSENDSIZE;
        sXfer.flags = 0;

        /* Start transfer. Will return immediately */
        xferDone = false;
        ROM_SPIS_Transfer(spisHandle, &sXfer);

        /* Can monitor transfer status or completion flag to determine
           end of transfer */
        while (xferDone == false) {
            /* Can sleep while waiting for SPI interrupts and end of trnasfer */
            __WFI();
        }

        /* Check status of the transfer */
        if (sXfer.status != LPC_OK) {
            DEBUGOUT("-Error performing transfer = %x\r\n", sXfer.status);
        }
        else {
            DEBUGOUT("-SPI transfer completed: status = %x\r\n", sXfer.status);
            for (i = 0; i < sXfer.rxRecv; i++) {
                DEBUGOUT("T:%04x R:%04x : ", tx16[i], rx16[i]);
            }
            DEBUGSTR("\r\n");
        }
        for (i = 0; i < sXfer.rxRecv; i++) {
            tx16[i] = rx16[i];
        }
    }

    /* Code never reaches here. Only used to satisfy standard main() */
    return 0;
}
Пример #23
0
void doTimer()
{
	/* Reconnect Listserver if Disconnected */
	if ( !(listServerFields[5] == "localhost") )
		if (!lsConnected)
			ListServer_Connect();

	/* Level-Animations */
	for(int i = 0; i < levelList.count(); i++)
	{
		CLevel* level = (CLevel*)levelList[i];
		level->animate();
	}

	/* Do Player-Timed Actions */
	for(int i = 0; i < playerList.count(); i++)
	{
		CPlayer* player = (CPlayer*)playerList[i];

		if (player->type == CLIENTPLAYER)
		{
			if (idleDisconnect)
			{
				if ((getTime() - player->lastMovement > maxNoMovement) &&
					(time(NULL) - player->lastChat > maxNoMovement) )
				{
					errorOut("errorlog.txt", CString() << "Client " << player->accountName << " had no activity for over " << toString(maxNoMovement) << " seconds.");
					player->sendPacket(CPacket() << (char)DISMESSAGE << "You have been disconnected because of inactivity.");
					player->deleteMe = true;
					continue;
				}
			}

			if (time(NULL) - player->lastData > 300)
			{
				errorOut("errorlog.txt", CString() << "No data from " << player->accountName << " for 300 secs");
				player->deleteMe = true;
				continue;
			}

			/*if (time(NULL) - player->lastCheck > cheatwindowstime)
			{
				player->lastCheck = time(NULL);
				player->sendPacket(CPacket() << (char)SPROCCESSES << (char)73);
			}*/

			player->onlineSecs++;

			if (time(NULL) - player->lastSave <= 0)
			{
				player->saveAccount();
				player->lastSave = time(NULL);
			}

			if (apSystem)
			{
				if ( !(player->status & 1) && player->level->sparZone == false )
					player->apCounter--;

				if ( player->apCounter <= 0 )
				{
					if (player->ap < 100)
					{
						player->ap = CLIP(player->ap + 1, 0, 100);
						player->updateProp(PALIGNMENT);
					}

					player->apCounter = (player->ap < 20 ? aptime[0] : (player->ap < 40 ? aptime[1] : (player->ap < 60 ? aptime[2] : (player->ap < 80 ? aptime[3] : aptime[4]))));
				}
			}
		}
	}
}
Пример #24
0
/* Never was great formulating =P */
bool CWordFilter::apply(CPlayer *pPlayer, CBuffer &pBuffer, int pCheck)
{
	bool logsave = false, rctell = false;
	CBuffer start;
	CStringList found;
	int pos = 0, wc = 0;

	for (int i = 0; i < WordList.count(); i++)
	{
		WordMatch *word = (WordMatch *)WordList[i];
		if (!word->check[pCheck])
			continue;

		for (int j = 0; j < pBuffer.length(); j++)
		{
			for (int k = 0; k < word->match.length(); k++)
			{
				char c1 = pBuffer[j + k];
				char c2 = word->match[k];
				if (c2 != '?' && (isUpper(c2) && c2 != c1) || (isLower(c2) && toLower(c2) != toLower(c1)))
				{
					if (wc >= word->precision)
					{
						found.add(start);

						for (int l = 0; l < (int)sizeof(word->action); l++)
						{
							if (!word->action[l])
								continue;

							switch (l)
							{
								case FILTERA_LOG:
									if (logsave)
										break;

									logsave = true;
									if (pPlayer != NULL)
										errorOut("wordfilter.txt", CBuffer() << pPlayer->accountName << " has used rude words while chatting: " << start);
								break;

								case FILTERA_REPLACE:
									pos = pBuffer.find(' ', j);
									pos = (pos == -1 ? start.length() : pos-j+1);
									for (int m = 0; m < pos; m++)
										pBuffer.replace(j + m, '*');
								break;

								case FILTERA_TELLRC:
									if (rctell)
										break;

									rctell = true;
									if (pPlayer != NULL)
										sendRCPacket(CPacket() << (char)DRCLOG << pPlayer->accountName << " has used rude words while chatting: " << start);
								break;

								case FILTERA_WARN:
									pBuffer = (word->warnmessage.length() > 0 ? word->warnmessage : warnmessage);
								break;

								case FILTERA_JAIL: // kinda useless...?
								break;

								case FILTERA_BAN:
									if (pPlayer != NULL)
									{
										CBuffer pLog = CBuffer() << "\n" << getTimeStr(0) << "\n" << pPlayer->accountName << " has used rude words while chatting: " << start;
										pPlayer->setBan(pLog, true);
									}
								break;
							}
						}
					}

					start.clear();
					wc = 0;
					break;
				}

				start.writeChar(c1);
				wc++;
			}
		}
	}

	return (found.count() > 0);
}
Пример #25
0
void ListServer_Main()
{
	if (!lsConnected)
		return;

	CBuffer receiveBuff;
	if (listServer.receiveBytes(receiveBuff, 65536) < 0)
	{
		errorOut("rclog.txt", "Disconnected from list server");
		lsConnected = false;
		return;
	}

	CStringList lines;
	lines.load(receiveBuff.text(), "\n");
	for (int i = 0; i < lines.count(); i++)
	{
		CPacket line = CPacket() << lines[i];
		int messageId = line.readByte1();

		switch (messageId)
		{
			case GSVOLD:
			{
				printf("*** SERVER VERSION CHECK ***\nYou're running an old version of the GServer.\nYou're running GServer Revision %i while GServer Revision %i is the latest.\n*** SERVER VERSION CHECK ***\n", GSERVER_BUILD, line.readByte2());
				break;
			}

			case GSVCURRENT:
			{
				 printf("*** SERVER VERSION CHECK ***\nYou're running an up-to-date server. :)\n*** SERVER VERSION CHECK ***\n");
				 break;
			}

			case GSVACCOUNT:
			{
				CString accountName = line.readChars(line.readByte1());
				CString errorMsg = line.readString("");

				for (int i = 0; i < newPlayers.count(); i++)
				{
					CPlayer *player = (CPlayer *)newPlayers[i];

					if (player->accountName == accountName)
					{
						if (errorMsg == "SUCCESS")
						{
							player->sendAccount();
						}
							else
						{
							player->sendPacket(CPacket() << (char)DISMESSAGE << errorMsg);
							player->deleteMe = true;
						}

						break;
					}
				}

				break;
			}

			case GSVGUILD:
			{
				int playerId = line.readByte2();
				CPlayer *player = (CPlayer *)playerIds[playerId];

				if (player != NULL)
				{
					CString nick = line.readChars((unsigned char)line.readByte1());
					player->setNick(nick, false);
				}

				break;
			}

			case GSVFILEC:
			{
				CString fileData, fileName = CString() << dataDir << "global" << fSep << line.readChars(line.readByte1());
				fileData.save(fileName.text());

				break;
			}

			case GSVFILED:
			{
				CString fileName = line.readChars(line.readByte1());
				CPlayer *player = (CPlayer *)playerIds[line.readByte2()];

				switch (line.readByte1())
				{
					case 0: // head
						player->headImage = fileName;
						player->updateProp(HEADGIF);
					break;

					case 1: // body
						player->bodyImage = fileName;
						player->updateProp(BODYIMG);
					break;

					case 2: // sword
						player->swordImage = fileName;
						player->updateProp(SWORDPOWER);
					break;

					case 3: // shield
						player->shieldImage = fileName;
						player->updateProp(SHIELDPOWER);
					break;
				}

				break;
			}

			case GSVFILES:
			{
				CString fileData, fileName, newData, shortName;
				shortName = line.readChars(line.readByte1());
				int pos = shortName.find("Revision");

				if (pos >= 0)
				{
					#ifdef WIN32
						fileName = CString() << "GServer-NEW.exe";
					#else
						fileName = CString() << "GServer-NEW";
					#endif
					newData = line.readString("");
				}
				else
				{
					fileName = CString() << dataDir << "global" << fSep << shortName.text();
					newData = line.readString("");
				}

				fileData.load(fileName.text());
				fileData << newData.B64_Decode();
				fileData.save(fileName.text());

				break;
			}

			case GSVPROFILE: /* Unsure if this works, temp */
			{
				CPacket profile;
				CPlayer *player1 = (CPlayer *)playerIds[line.readByte2()];
				CPlayer *player2 = findPlayerId(line.readChars(line.readByte1()));
				if (player1 == NULL || player2 == NULL)
					return;

				profile << (char)player2->accountName.length() << player2->accountName << line.readString("");

				int time = player2->onlineSecs;
				CString line;
				//Online time
				line << toString((int)time/3600) << " hrs ";
				line << toString((int)(time/60)%60) << " mins ";
				line << toString((int)time%60) << " secs";
				profile << (char)line.length() << line;

				for (int i = 0; i < profileList.count(); i++)
				{
					CStringList a;
					a.load(profileList[i].text(), ":=");
					if (a[0].length() < 1)
						continue;

					CString n;

					if (a[1] == "playerkills")
						n = toString(player2->kills);
					else if (a[1] == "playerdeaths")
						n = toString(player2->deaths);
					else if (a[1] == "playerfullhearts")
						n = toString(player2->maxPower);
					else if (a[1] == "playerrating")
						n = toString(player2->rating);
					else if (a[1] == "playerap")
						n = toString(player2->ap);
					else if (a[1] == "playerrupees")
						n = toString(player2->rubins);
					else if (a[1] == "playerswordpower")
						n = toString(player2->swordPower);
					else if (a[1] == "canspin")
						n = (player2->status & 64 ? "true" : "false");
					else if (a[1] == "playerhearts")
						n = toString(player2->power);
					else if (a[1] == "playerdarts")
						n = toString(player2->darts);
					else if (a[1] == "playerbombs")
						n = toString(player2->bombs);
					else if (a[1] == "playermp")
						n = toString(player2->magicPoints);
					else if (a[1] == "playershieldpower")
						n = toString(player2->shieldPower);
					else if (a[1] == "playerglovepower")
						n = toString(player2->glovePower);
					else
					{
						for (int i = 0; i < player2->myFlags.count(); i++)
						{
							CStringList b;
							b.load(player2->myFlags[i].text(), "=");
							if (b[0] == a[1])
							{
								n = b[1];
								break;
							}
						}
					}

					profile << (char)(a[0].length() + n.length() + 2) << a[0] << ":=" << n;
				}

				player1->sendPacket(CPacket() << (char)DPROFILE << profile);

				break;
			}

			case GSVMSG:
				printf("%s\n", line.readString(""));
			break;

			default:
				printf("Invalid List Server Message: %i\n", messageId);
			break;
		}
	}
}
Пример #26
0
/******************************************************************************
 * Render the current scene
 * uses the global variables from the parser
 *****************************************************************************/
int ntlWorld::renderScene( void )
{
#ifndef ELBEEM_PLUGIN
	char nrStr[5];														// nr conversion 
	std::ostringstream outfn_conv("");  			// converted ppm with other suffix 
  ntlRenderGlobals *glob;                  	// storage for global rendering parameters 
  myTime_t timeStart,totalStart,timeEnd; 		// measure user running time 
  myTime_t rendStart,rendEnd;            		// measure user rendering time 
  glob = mpGlob;

	// deactivate for all with index!=0 
	if((glob_mpactive)&&(glob_mpindex>0)) return(0);

	/* check if picture already exists... */
	if(!glob->getSingleFrameMode() ) {
		snprintf(nrStr, 5, "%04d", glob->getAniCount() );

		if(glob_mpactive) {
			outfn_conv  << glob->getOutFilename() <<"_"<<glob_mpindex<<"_" << nrStr << ".png"; /// DEBUG!
		} else {
			// ORG
			outfn_conv  << glob->getOutFilename() <<"_" << nrStr << ".png";
		}
		
		//if((mpGlob->getDisplayMode() == DM_RAY)&&(mpGlob->getFrameSkip())) {
		if(mpGlob->getFrameSkip()) {
			struct stat statBuf;
			if(stat(outfn_conv.str().c_str(),&statBuf) == 0) {
				errorOut("ntlWorld::renderscene Warning: file "<<outfn_conv.str()<<" already exists - skipping frame..."); 
				glob->setAniCount( glob->getAniCount() +1 );
				return(2);
			}
		} // RAY mode
	} else {
		// single frame rendering, overwrite if necessary...
		outfn_conv << glob->getSingleFrameFilename();
	}

  /* start program */
	timeStart = getTime();

	/* build scene geometry, calls buildScene(t,false) */
	glob->getRenderScene()->prepareScene(mSimulationTime);

  /* start program */
	totalStart = getTime();


	/* view parameters are currently not animated */
	/* calculate rays through projection plane */
	ntlVec3Gfx direction = glob->getLookat() - glob->getEye();
	/* calculate width of screen using perpendicular triangle diven by
	 * viewing direction and screen plane */
	gfxReal screenWidth = norm(direction)*tan( (glob->getFovy()*0.5/180.0)*M_PI );

	/* calculate vector orthogonal to up and viewing direction */
	ntlVec3Gfx upVec = glob->getUpVec();
	ntlVec3Gfx rightVec( cross(upVec,direction) );
	normalize(rightVec);

	/* calculate screen plane up vector, perpendicular to viewdir and right vec */
	upVec = ntlVec3Gfx( cross(rightVec,direction) );
	normalize(upVec);

	/* check if vectors are valid */
	if( (equal(upVec,ntlVec3Gfx(0.0))) || (equal(rightVec,ntlVec3Gfx(0.0))) ) {
		errMsg("ntlWorld::renderScene","Invalid viewpoint vectors! up="<<upVec<<" right="<<rightVec);
		return(1);
	}

	/* length from center to border of screen plane */
	rightVec *= (screenWidth*glob->getAspect() * -1.0);
	upVec *= (screenWidth * -1.0);

	/* screen traversal variables */
	ntlVec3Gfx screenPos;                          /* current position on virtual screen */
	int Xres = glob->getResX();                  /* X resolution */
	int Yres = glob->getResY();                  /* Y resolution */
	ntlVec3Gfx rightStep = (rightVec/(Xres/2.0));  /* one step right for a pixel */
	ntlVec3Gfx upStep    = (upVec/(Yres/2.0));     /* one step up for a pixel */
    

	/* anti alias init */
	char  showAAPic = 0;
	int   aaDepth = glob->getAADepth();
	int   aaLength;
	if(aaDepth>=0) aaLength = (2<<aaDepth);
	else           aaLength = 0;
	float aaSensRed   = 0.1;
	float aaSensGreen = 0.1;
	float aaSensBlue  = 0.1;
	int   aaArrayX = aaLength*Xres+1;
	int   aaArrayY = ( aaLength+1 );
	ntlColor *aaCol = new ntlColor[ aaArrayX*aaArrayY ];
	char  *aaUse = new char[ aaArrayX*aaArrayY ];

	/* picture storage */
	int picX = Xres;
	int picY = Yres;
	if(showAAPic) {
		picX = Xres *aaLength+1;
		picY = Yres *aaLength+1;
	}
	ntlColor *finalPic = new ntlColor[picX * picY];


	/* reset picture vars */
	for(int j=0;j<aaArrayY;j++) {
		for(int i=0;i<aaArrayX;i++) {
			aaCol[j*aaArrayX+i] = ntlColor(0.0, 0.0, 0.0);
			aaUse[j*aaArrayX+i] = 0;
		}
	}
	for(int j=0;j<picY;j++) {
		for(int i=0;i<picX;i++) {
			finalPic[j*picX+i] = ntlColor(0.0, 0.0, 0.0);
		}
	}

	/* loop over all y lines in screen, from bottom to top because
	 * ppm format wants 0,0 top left */
	rendStart = getTime();
	glob->setCounterShades(0);
	glob->setCounterSceneInter(0);
	for (int scanline=Yres ; scanline > 0 ; --scanline) {
    
		debugOutInter( "ntlWorld::renderScene: Line "<<scanline<<
								 " ("<< ((Yres-scanline)*100/Yres) <<"%) ", 2, 2000 );
		screenPos = glob->getLookat() + upVec*((2.0*scanline-Yres)/Yres)
			- rightVec;

		/* loop over all pixels in line */
		for (int sx=0 ; sx < Xres ; ++sx) {

			if((sx==glob->getDebugPixelX())&&(scanline==(Yres-glob->getDebugPixelY()) )) {
				// DEBUG!!!
				glob->setDebugOut(10);
			} else glob->setDebugOut(0);
			
			/* compute ray from eye through current pixel into scene... */
			ntlColor col;
			if(aaDepth<0) {
				ntlVec3Gfx dir(screenPos - glob->getEye());
				ntlRay the_ray(glob->getEye(), getNormalized(dir), 0, 1.0, glob );

				/* ...and trace it */
				col = the_ray.shade();
			} else {
				/* anti alias */
				int ai,aj;                   /* position in grid */
				int aOrg = sx*aaLength;      /* grid offset x */
				int currStep = aaLength;     /* step size */
				char colDiff = 1;            /* do colors still differ too much? */
				ntlColor minCol,maxCol;         /* minimum and maximum Color Values */
				minCol = ntlColor(1.0,1.0,1.0);
				maxCol = ntlColor(0.0,0.0,0.0);

				while((colDiff) && (currStep>0)) {
					colDiff = 0;
	    
					for(aj = 0;aj<=aaLength;aj+= currStep) {
						for(ai = 0;ai<=aaLength;ai+= currStep) {

							/* shade pixel if not done */
							if(aaUse[aj*aaArrayX +ai +aOrg] == 0) {
								aaUse[aj*aaArrayX +ai +aOrg] = 1;
								ntlVec3Gfx aaPos( screenPos +
																(rightStep * (ai- aaLength/2)/(gfxReal)aaLength ) +
																(upStep    * (aj- aaLength/2)/(gfxReal)aaLength ) );

								ntlVec3Gfx dir(aaPos - glob->getEye());
								ntlRay the_ray(glob->getEye(), getNormalized(dir), 0, 1.0, glob );

								/* ...and trace it */
								ntlColor newCol= the_ray.shade();
								aaCol[aj*aaArrayX +ai +aOrg]= newCol;
							} /* not used? */

						}
					}

					/* check color differences */
					for(aj = 0;aj<aaLength;aj+= currStep) {
						for(ai = 0;ai<aaLength;ai+= currStep) {

							char thisColDiff = 0;
							if( 
								 (fabs(aaCol[aj*aaArrayX +ai +aOrg][0] - 
											 aaCol[(aj+0)*aaArrayX +(ai+currStep) +aOrg][0])> aaSensRed ) ||
								 (fabs(aaCol[aj*aaArrayX +ai +aOrg][1] - 
											 aaCol[(aj+0)*aaArrayX +(ai+currStep) +aOrg][1])> aaSensGreen ) ||
								 (fabs(aaCol[aj*aaArrayX +ai +aOrg][2] - 
											 aaCol[(aj+0)*aaArrayX +(ai+currStep) +aOrg][2])> aaSensBlue ) ) {
								thisColDiff = 1;
							} else
								if( 
									 (fabs(aaCol[aj*aaArrayX +ai +aOrg][0] - 
												 aaCol[(aj+currStep)*aaArrayX +(ai+0) +aOrg][0])> aaSensRed ) ||
									 (fabs(aaCol[aj*aaArrayX +ai +aOrg][1] - 
												 aaCol[(aj+currStep)*aaArrayX +(ai+0) +aOrg][1])> aaSensGreen ) ||
									 (fabs(aaCol[aj*aaArrayX +ai +aOrg][2] - 
												 aaCol[(aj+currStep)*aaArrayX +(ai+0) +aOrg][2])> aaSensBlue ) ) {
									thisColDiff = 1;
								} else
									if( 
										 (fabs(aaCol[aj*aaArrayX +ai +aOrg][0] - 
													 aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg][0])> aaSensRed ) ||
										 (fabs(aaCol[aj*aaArrayX +ai +aOrg][1] - 
													 aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg][1])> aaSensGreen ) ||
										 (fabs(aaCol[aj*aaArrayX +ai +aOrg][2] - 
													 aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg][2])> aaSensBlue ) ) {
										thisColDiff = 1;
									} 

							//colDiff =1;
							if(thisColDiff) {
								/* set diff flag */
								colDiff = thisColDiff;
								for(int bj=aj;bj<=aj+currStep;bj++) {
									for(int bi=ai;bi<=ai+currStep;bi++) {
										if(aaUse[bj*aaArrayX +bi +aOrg]==2) {
											//if(showAAPic) 
											aaUse[bj*aaArrayX +bi +aOrg] = 0;
										}
									}
								}
							} else {
								/* set all values */
								ntlColor avgCol = (
																	 aaCol[(aj+0       )*aaArrayX +(ai+0       ) +aOrg] +
																	 aaCol[(aj+0       )*aaArrayX +(ai+currStep) +aOrg] +
																	 aaCol[(aj+currStep)*aaArrayX +(ai+0       ) +aOrg] +
																	 aaCol[(aj+currStep)*aaArrayX +(ai+currStep) +aOrg] ) *0.25;
								for(int bj=aj;bj<=aj+currStep;bj++) {
									for(int bi=ai;bi<=ai+currStep;bi++) {
										if(aaUse[bj*aaArrayX +bi +aOrg]==0) {
											aaCol[bj*aaArrayX +bi +aOrg] = avgCol; 
											aaUse[bj*aaArrayX +bi +aOrg] = 2;
										}
									}
								}
							} /* smaller values set */

						}
					}

					/* half step size */
					currStep /= 2;

				} /* repeat until diff not too big */

				/* get average color */
				gfxReal colNum = 0.0;
				col = ntlColor(0.0, 0.0, 0.0);
				for(aj = 0;aj<=aaLength;aj++) {
					for(ai = 0;ai<=aaLength;ai++) {
						col += aaCol[aj*aaArrayX +ai +aOrg];
						colNum += 1.0;
					}
				}
				col /= colNum;

			}

		  /* mark pixels with debugging */
			if( glob->getDebugOut() > 0) col = ntlColor(0,1,0);

			/* store pixel */
			if(!showAAPic) {
				finalPic[(scanline-1)*picX+sx] = col; 
			}
			screenPos +=  rightStep;

		} /* foreach x */

		/* init aa array */
		if(showAAPic) {
			for(int j=0;j<=aaArrayY-1;j++) {
				for(int i=0;i<=aaArrayX-1;i++) {
					if(aaUse[j*aaArrayX +i]==1) finalPic[((scanline-1)*aaLength +j)*picX+i][0] = 1.0;
				}
			}
		}

		for(int i=0;i<aaArrayX;i++) {
			aaCol[(aaArrayY-1)*aaArrayX+i] = aaCol[0*aaArrayX+i];
			aaUse[(aaArrayY-1)*aaArrayX+i] = aaUse[0*aaArrayX+i];
		}
		for(int j=0;j<aaArrayY-1;j++) {
			for(int i=0;i<aaArrayX;i++) {
				aaCol[j*aaArrayX+i] = ntlColor(0.0, 0.0, 0.0);
				aaUse[j*aaArrayX+i] = 0;
			}
		}

	} /* foreach y */
	rendEnd = getTime();


	/* write png file */
	{
		int w = picX;
		int h = picY;

		unsigned rowbytes = w*4;
		unsigned char *screenbuf, **rows;
		screenbuf = (unsigned char*)malloc( h*rowbytes );
		rows = (unsigned char**)malloc( h*sizeof(unsigned char*) );
		unsigned char *filler = screenbuf;

		// cutoff color values 0..1
		for(int j=0;j<h;j++) {
			for(int i=0;i<w;i++) {
				ntlColor col = finalPic[j*w+i];
				for (unsigned int cc=0; cc<3; cc++) {
					if(col[cc] <= 0.0) col[cc] = 0.0;
					if(col[cc] >= 1.0) col[cc] = 1.0;
				}
				*filler = (unsigned char)( col[0]*255.0 ); 
				filler++;
				*filler = (unsigned char)( col[1]*255.0 ); 
				filler++;
				*filler = (unsigned char)( col[2]*255.0 ); 
				filler++;
				*filler = (unsigned char)( 255.0 ); 
				filler++; // alpha channel
			}
		}

		for(int i = 0; i < h; i++) rows[i] = &screenbuf[ (h - i - 1)*rowbytes ];
		writePng(outfn_conv.str().c_str(), rows, w, h);
	}


	// next frame 
	glob->setAniCount( glob->getAniCount() +1 );

	// done 
	timeEnd = getTime();

	char resout[1024];
	snprintf(resout,1024, "NTL Done %s, frame %d/%d (took %s scene, %s raytracing, %s total, %d shades, %d i.s.'s)!\n", 
				 outfn_conv.str().c_str(), (glob->getAniCount()), (glob->getAniFrames()+1),
				 getTimeString(totalStart-timeStart).c_str(), getTimeString(rendEnd-rendStart).c_str(), getTimeString(timeEnd-timeStart).c_str(),
				 glob->getCounterShades(),
				 glob->getCounterSceneInter() );
	debMsgStd("ntlWorld::renderScene",DM_MSG, resout, 1 );

	/* clean stuff up */
	delete [] aaCol;
	delete [] aaUse;
	delete [] finalPic;
	glob->getRenderScene()->cleanupScene();

	if(mpGlob->getSingleFrameMode() ) {
		debMsgStd("ntlWorld::renderScene",DM_NOTIFY, "Single frame mode done...", 1 );
		return 1;
	}
#endif // ELBEEM_PLUGIN
	return 0;
}
Пример #27
0
void CNpc::setProps(CPacket& pProps)
{
	int len;
	int previousMessage = 0;
	while(pProps.bytesLeft())
	{
		int index = pProps.readByte1();
		CPacket oldProp = getProperty(index);
		switch(index)
		{
			case NPCGIF:
				len = (unsigned char)pProps.readByte1();
				image = pProps.readChars(len);
			break;

			case ACTIONSCRIPT:
				len = (unsigned int)pProps.readByte2();
				clientCode = pProps.readChars(len);
			break;

			case NPCX:
				x = (float)(pProps.readByte1())/2;
			break;

			case NPCY:
				y = (float)(pProps.readByte1())/2;
			break;

			case NPCPOWER:
				power = (unsigned char)pProps.readByte1();
			break;

			case NPCRUPEES:
				rupees = (unsigned int)pProps.readByte3();
			break;

			case NPCARROWS:
				darts = (unsigned char)pProps.readByte1();
			break;

			case NPCBOMBS:
				bombs = (unsigned char)pProps.readByte1();
			break;

			case NGLOVEPOWER:
				glovePower = (unsigned char)pProps.readByte1();
			break;

			case NBOMBPOWER:
				bombPower = (unsigned char)pProps.readByte1();
			break;

			case NSWORDGIF:
			{
				int sp = (unsigned char)pProps.readByte1();
				if ( sp >= 30 )
				{
					sp -= 30;
					len = (unsigned char)pProps.readByte1();
					if ( len >= 0 )
						swordImage = pProps.readChars(len);
				}
				else
				{
					if ( sp >= 1 && sp <= 4 )
						swordImage = CString() << "sword" << toString(sp) << ".png";
					else
						swordImage = "";
				}
				swordPower = (sp >= 30) ? (sp - 30) : sp;
			}

			break;

			case NSHIELDGIF:
			{
				int sp = (unsigned char)pProps.readByte1();
				if(sp >= 10)
				{
					len = (unsigned char)pProps.readByte1();
					if(len >= 0)
						shieldImage = pProps.readChars(len);
				} else
				{
					if(sp >= 1 && sp <= 3)
						shieldImage = CString() << "shield" << toString(sp) << ".png";
					else shieldImage = "";
				}
				shieldPower = (sp >= 10) ? (sp - 10) : sp;
			}
			break;

			case NPCANI:
				len = (unsigned char)pProps.readByte1();
				gAni = pProps.readChars(len);
			break;

			case VISFLAGS:
				visFlags = (unsigned char)pProps.readByte1();
			break;

			case BLOCKFLAGS:
				blockFlags = (unsigned char)pProps.readByte1();
			break;

			case NPCMESSAGE:
				len = (unsigned char)pProps.readByte1();
				chatMsg = pProps.readChars(len);
			break;

			case NPCHURTDXDY:
				hurtX = ((float)(pProps.readByte1()-32))/32;
				hurtY = ((float)(pProps.readByte1()-32))/32;
			break;

			case NPCID:
				pProps.readByte3();
			break;

			case NPCSPRITE:
				sprite = (unsigned char)pProps.readByte1();
				if ( sprite >= 132 ) sprite = 0;
			break;

			case NPCCOLORS:
				for (int i = 0; i < 5; i++)
					colors[i] = (unsigned char)pProps.readByte1();
			break;

			case NPCNICKNAME:
				len = (unsigned char)pProps.readByte1();
				nickName = pProps.readChars(len);
			break;

			case NPCHORSEGIF:
				len = (unsigned char)pProps.readByte1();
				horseImage = pProps.readChars(len);
			break;

			case NPCHEADGIF:
				len = (unsigned char)pProps.readByte1();
				if (len < 100)
					headImage = CString() << "head" << toString(len) << ".png";
				else
					headImage = pProps.readChars(len-100);
			break;

			case NPCSAVE0:
			case NPCSAVE1:
			case NPCSAVE2:
			case NPCSAVE3:
			case NPCSAVE4:
			case NPCSAVE5:
			case NPCSAVE6:
			case NPCSAVE7:
			case NPCSAVE8:
			case NPCSAVE9:
				saves[index-NPCSAVE0] = (unsigned char)pProps.readByte1();
			break;

			case NALIGNMENT:
				ap = CLIP(pProps.readByte1(), 0, 100);
			break;

			case NPCGIFPART:
				imagePart = pProps.readChars(6);
			break;

			case NPCBODY:
				len = (unsigned char)pProps.readByte1();
				bodyImage = pProps.readChars(len);
			break;

			case NGATTRIB1:
			case NGATTRIB2:
			case NGATTRIB3:
			case NGATTRIB4:
			case NGATTRIB5:
				len = (unsigned char)pProps.readByte1();
				gAttribs[index-NGATTRIB1] = pProps.readChars(len);
			break;

			case NGMAPLEVELX:
				pProps.readByte1();
				break;

			case NGMAPLEVELY:
				pProps.readByte1();
				break;

			case NEMPTY43:
				errorOut( "debuglog.txt", CString() << "CNpc::setProps() tried to set NEMPTY" << toString(index) );
				CPlayer::sendGlobally( CPacket() << (char)SRPGWINDOW << "\"CNpc::setProps tried to set NEMPTY" << toString(index) << "\"" );
				break;

			case NGATTRIB6:
			case NGATTRIB7:
			case NGATTRIB8:
			case NGATTRIB9:
/* Does the client not send gani attribs > 9?
			case NGATTRIB10:
			case NGATTRIB11:
			case NGATTRIB12:
			case NGATTRIB13:
			case NGATTRIB14:
			case NGATTRIB15:
			case NGATTRIB16:
			case NGATTRIB17:
			case NGATTRIB18:
			case NGATTRIB19:
			case NGATTRIB20:
			case NGATTRIB21:
			case NGATTRIB22:
			case NGATTRIB23:
			case NGATTRIB24:
			case NGATTRIB25:
			case NGATTRIB26:
			case NGATTRIB27:
			case NGATTRIB28:
			case NGATTRIB29:
			case NGATTRIB30:
*/
				len = (unsigned char)pProps.readByte1();
				if(len >= 0)
					gAttribs[6+index-NGATTRIB6] = pProps.readChars(len);
			break;

			default:
//				errorOut( "debuglog.txt", CString() << "CNpc::setProps() tried to set unknown " << toString(index) );
//				CPlayer::sendGlobally( CPacket() << (char)SRPGWINDOW << "\"CNpc::setProps tried to set unknown " << toString(index) << "\"" );
				printf("NPC %d (%.2f, %.2f): ", id, x, y);
				printf("Unknown prop: %ud, readPos: %d\n", index, pProps.getRead());
				for (int i = 0; i < pProps.length(); ++i)
					printf("%02x ", (unsigned char)pProps[i]);
				printf("\n");

//				if ( detailedconsole )
//					printf("[%s] UNKNOWN NPC PROP: %i, Prev: %i, Value: %s\n", getTimeStr(1).text(), index, previousMessage, (pProps.text() + pProps.getRead()));
			return;
		}
		previousMessage = index;

		// If a prop changed, adjust its mod time.
		if ( index >= 0 && index < npcpropcount )
		{
			if ( oldProp != getProperty(index) )
				modTime[index] = getSysTime();
		}
	}
}
Пример #28
0
CPacket CNpc::getProperty(int pId)
{
	CPacket retVal;
	switch(pId)
	{
		case NPCGIF:
			retVal << (char)image.length() << image;
		break;

		case ACTIONSCRIPT:
			retVal << (short)clientCode.length() << clientCode.copy(0, MIN(clientCode.length(),0x3FFF));
		break;

		case NPCX:
			retVal << (char)(x*2);
		break;

		case NPCY:
			retVal << (char)(y*2);
		break;

		case NPCPOWER:
			retVal << (char)power;
		break;

		case NPCRUPEES:
			retVal.writeByte3(rupees);
		break;

		case NPCARROWS:
			retVal << (char)darts;
		break;

		case NPCBOMBS:
			retVal << (char)bombs;
		break;

		case NGLOVEPOWER:
			retVal << (char)glovePower;
		break;

		case NBOMBPOWER:
			retVal << (char)bombPower;
		break;

		case NSWORDGIF:
		{
			int sp = swordPower+30;
			if ( sp == 30 ) sp = 0;
			retVal << (char)sp;
			if ( sp > 30 )
				retVal << (char)swordImage.length() << swordImage;
		}
		break;

		case NSHIELDGIF:
		{
			int sp = shieldPower+10;
			if ( sp == 10 ) sp = 0;
			retVal << (char)sp;
			if ( sp > 10 )
				retVal << (char)shieldImage.length() << shieldImage;
		}
		break;

		case NPCANI:
			retVal << (char)gAni.length() << gAni;
		break;

		case VISFLAGS:
			retVal << (char)visFlags;
		break;

		case BLOCKFLAGS:
			retVal << (char)blockFlags;
		break;

		case NPCMESSAGE:
			if ( chatMsg.length() > 200 )
				chatMsg = chatMsg.copy(0,200);
			retVal << (char)chatMsg.length() << chatMsg;
		break;

		case NPCHURTDXDY:
			retVal << (char)(hurtX*32)+32 << (char)(hurtY*32)+32;
		break;

		case NPCID:
			retVal.writeByte3(id);
		break;

		case NPCSPRITE:
			retVal << (char)(sprite % 4);
		break;

		case NPCCOLORS:
			retVal << (char)colors[0] << (char)colors[1] << (char)colors[2] << (char)colors[3] << (char)colors[4];// << (char)colors[5];
		break;

		case NPCNICKNAME:
			retVal << (char)nickName.length() << nickName;
		break;

		case NPCHORSEGIF:
			retVal << (char)horseImage.length() << horseImage;
		break;

		case NPCHEADGIF:
			retVal << (char)(headImage.length()+100) << headImage;
		break;

		case NALIGNMENT:
			retVal.writeByte1(ap);
		break;

		case NPCSAVE0:
		case NPCSAVE1:
		case NPCSAVE2:
		case NPCSAVE3:
		case NPCSAVE4:
		case NPCSAVE5:
		case NPCSAVE6:
		case NPCSAVE7:
		case NPCSAVE8:
		case NPCSAVE9:
			retVal << saves[pId-NPCSAVE0];
		break;

		case NPCGIFPART:
			retVal << imagePart;
		break;

		case NPCBODY:
			retVal << (char)bodyImage.length() << bodyImage;
		break;

		case NGATTRIB1:
		case NGATTRIB2:
		case NGATTRIB3:
		case NGATTRIB4:
		case NGATTRIB5:
		{
			int index = pId - NGATTRIB1;
			retVal << (char)gAttribs[index].length() << gAttribs[index];
		}
		break;

		case NGMAPLEVELX:
			retVal << (char)0;
			break;

		case NGMAPLEVELY:
			retVal << (char)0;
			break;

		case NEMPTY43:
			errorOut( "debuglog.txt", CString() << "CNpc::getProperty() requested NEMPTY" << toString(pId) );
			CPlayer::sendGlobally( CPacket() << (char)SRPGWINDOW << "\"CNpc::getProperty() requested NEMPTY" << toString(pId) << "\"" );
			break;

		case NGATTRIB6:
		case NGATTRIB7:
		case NGATTRIB8:
		case NGATTRIB9:
/* Does the client not send gani attribs > 9?
		case NGATTRIB10:
		case NGATTRIB11:
		case NGATTRIB12:
		case NGATTRIB13:
		case NGATTRIB14:
		case NGATTRIB15:
		case NGATTRIB16:
		case NGATTRIB17:
		case NGATTRIB18:
		case NGATTRIB19:
		case NGATTRIB20:
		case NGATTRIB21:
		case NGATTRIB22:
		case NGATTRIB23:
		case NGATTRIB24:
		case NGATTRIB25:
		case NGATTRIB26:
		case NGATTRIB27:
		case NGATTRIB28:
		case NGATTRIB29:
		case NGATTRIB30:
*/
		{
			int index = 6 + pId - NGATTRIB6;
			retVal << (char)gAttribs[index].length() << gAttribs[index];
		}
		break;

		default:
			errorOut( "debuglog.txt", CString() << "CNpc::getProperty() requested unknown prop " << toString(pId) );
			CPlayer::sendGlobally( CPacket() << (char)SRPGWINDOW << "\"CNpc::getProperty() requested unknown prop " << toString(pId) << "\"" );
			break;

	}
	return retVal;
}
Пример #29
0
/**
* Called by libevent when there is data to read.
*/
void buffered_on_read(struct bufferevent *bev, void *arg) {
	client_t *client = (client_t *)arg;
	char data[BUF_MAX_SIZE] = { 0 };
	int nbytes;
	nbytes = EVBUFFER_LENGTH(bev->input);
	evbuffer_remove(bev->input, data, nbytes);
	//解析data
	string sdata = data;
	printf("recv sdata : %s\n", sdata.c_str());
	Json::Reader reader;
	Json::Value value, return_item;
	Json::FastWriter writer_item;
	if (reader.parse(sdata, value) && (!value["FunctionName"].isNull()))
	{
		CDBManager MyDB;
		MyDB.initDB("localhost", "root", "123456", "JiaTuanSql");
		string sFunctionName = value["FunctionName"].asString();
		if ("register" == sFunctionName)
		{
			if (MyDB.user_register_func(value["PhoneNO"].asString(), value["Pwd"].asString()))
			{
				return_item["error_code"] = 0;
			}
			else
			{
				return_item["error_code"] = -111;
				return_item["error_desc"] = "register failed,maybe user_login duplicate.";
			}
		}
		else if ("login" == sFunctionName)
		{
			if (MyDB.user_login_func(value["User_login"].asString(), value["User_pass"].asString()))
			{
				return_item["error_code"] = 0;
			}
			else
			{
				return_item["error_code"] = -121;
				return_item["error_desc"] = "login failed,maybe the account or password mistake.";
			}
		}
	}
	else
	{
		return_item["error_code"] = -11;
		return_item["error_desc"] = "Error:json data parse.";
	}
	sdata = writer_item.write(return_item);
	printf("send sdata : %s\n", sdata.c_str());
	evbuffer_add(client->output_buffer, sdata.c_str(), sdata.size());
	if (bufferevent_write_buffer(bev, client->output_buffer)) {
		errorOut("Error sending data to client on fd %d\n", client->fd);
		closeClient(client);
	}



	///* Copy the data from the input buffer to the output buffer in 4096-byte chunks.
	//* There is a one-liner to do the whole thing in one shot, but the purpose of this server
	//* is to show actual real-world reading and writing of the input and output buffers,
	//* so we won't take that shortcut here. */
	//while ((nbytes = EVBUFFER_LENGTH(bev->input)) > 0) {
	//	/* Remove a chunk of data from the input buffer, copying it into our local array (data). */
	//	if (nbytes > 4096) nbytes = 4096;
	//	evbuffer_remove(bev->input, data, nbytes);
	//	/* Add the chunk of data from our local array (data) to the client's output buffer. */
	//	evbuffer_add(client->output_buffer, data, nbytes);
	//}

	///* Send the results to the client.  This actually only queues the results for sending.
	//* Sending will occur asynchronously, handled by libevent. */
	//if (bufferevent_write_buffer(bev, client->output_buffer)) {
	//	errorOut("Error sending data to client on fd %d\n", client->fd);
	//	closeClient(client);
	//}
}
int main(int argc, char **argv){

    std::string filename("");
    unsigned int scale = 5, dmst = 2, window = 3, detectorType = 0, descriptorType = 0, distanceType = 2, strategy = 0;
    double baseSigma = 0.2, sigmaStep = 1.4, minPeak = 0.34, minPeakDistance = 0.001, acceptanceSigma = 0.1, success = 0.95, inlier = 0.4, matchingThreshold = 0.4;
	bool useMaxRange = false;
    
    int i = 1;
    while(i < argc){
		if(strncmp("-filename", argv[i], sizeof("-filename")) == 0 ){
			filename = argv[++i];
			i++;
		} else if(strncmp("-detector", argv[i], sizeof("-detector")) == 0 ){
			detectorType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-descriptor", argv[i], sizeof("-descriptor")) == 0 ){
			descriptorType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-distance", argv[i], sizeof("-distance")) == 0 ){
			distanceType = atoi(argv[++i]);
			i++;
		} else if(strncmp("-strategy", argv[i], sizeof("-strategy")) == 0 ){
			strategy = atoi(argv[++i]);
			i++;
		} else if(strncmp("-baseSigma", argv[i], sizeof("-baseSigma")) == 0 ){
			baseSigma = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-sigmaStep", argv[i], sizeof("-sigmaStep")) == 0 ){
			sigmaStep = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-minPeak", argv[i], sizeof("-minPeak")) == 0 ){
			minPeak = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-minPeakDistance", argv[i], sizeof("-minPeakDistance")) == 0 ){
			minPeakDistance = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-scale", argv[i], sizeof("-scale")) == 0 ){
			scale = atoi(argv[++i]);
			i++;
		} else if(strncmp("-dmst", argv[i], sizeof("-dmst")) == 0 ){
			dmst = atoi(argv[++i]);
			i++;
		} else if(strncmp("-window", argv[i], sizeof("-window")) == 0 ){
			window = atoi(argv[++i]);
			i++;
		} else if(strncmp("-acceptanceSigma", argv[i], sizeof("-acceptanceSigma")) == 0 ){
			acceptanceSigma = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-success", argv[i], sizeof("-success")) == 0 ){
			success = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-inlier", argv[i], sizeof("-inlier")) == 0 ){
			inlier = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-matchingThreshold", argv[i], sizeof("-matchingThreshold")) == 0 ){
			matchingThreshold = strtod(argv[++i], NULL);
			i++;
		} else if(strncmp("-localSkip", argv[i], sizeof("-localSkip")) == 0 ){
			m_localSkip = atoi(argv[++i]);
			i++;
		} else if(strncmp("-help", argv[i], sizeof("-localSkip")) == 0 ){
			help();
			exit(0);
		} else {
			i++;
		}
    }
    
    if(!filename.size()){
		help();
		exit(-1);
    }
    
    
    CarmenLogWriter writer;
    CarmenLogReader reader;
    
    m_sensorReference = LogSensorStream(&reader, &writer);
    
    m_sensorReference.load(filename);
    
    SimpleMinMaxPeakFinder *m_peakMinMax = new SimpleMinMaxPeakFinder(minPeak, minPeakDistance);
    
    
    std::string detector("");
    switch(detectorType){
	case 0:
	    m_detectorCurvature = new CurvatureDetector(m_peakMinMax, scale, baseSigma, sigmaStep, dmst);
		m_detectorCurvature->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorCurvature;
	    detector = "curvature";
	    break;
	case 1:
	    m_detectorNormalEdge = new NormalEdgeDetector(m_peakMinMax, scale, baseSigma, sigmaStep, window);
	    m_detectorNormalEdge->setUseMaxRange(useMaxRange);
		m_detector = m_detectorNormalEdge;
	    detector = "edge";
	    break;
	case 2:
	    m_detectorNormalBlob = new NormalBlobDetector(m_peakMinMax, scale, baseSigma, sigmaStep, window);
		m_detectorNormalBlob->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorNormalBlob;
	    detector = "blob";
	    break;
	case 3:
	    m_detectorRange = new RangeDetector(m_peakMinMax, scale, baseSigma, sigmaStep);
		m_detectorRange->setUseMaxRange(useMaxRange);
	    m_detector = m_detectorRange;
	    detector = "range";
	    break;
	default:
	    std::cerr << "Wrong detector type" << std::endl;
	    exit(-1);
    }
    
    HistogramDistance<double> *dist = NULL;
    
    std::string distance("");
    switch(distanceType){
	case 0:
	    dist = new EuclideanDistance<double>();
	    distance = "euclid";
	    break;
	case 1:
	    dist = new Chi2Distance<double>();
	    distance = "chi2";
	    break;
	case 2:
	    dist = new SymmetricChi2Distance<double>();
	    distance = "symchi2";
	    break;
	case 3:
	    dist = new BatthacharyyaDistance<double>();
	    distance = "batt";
	    break;
	case 4:
	    dist = new KullbackLeiblerDistance<double>();
	    distance = "kld";
	    break;
	case 5:
	    dist = new JensenShannonDistance<double>();
	    distance = "jsd";
	    break;
	default:
	    std::cerr << "Wrong distance type" << std::endl;
	    exit(-1);
    }
    
    std::string descriptor("");
    switch(descriptorType){
	case 0:
	    m_betaGenerator = new BetaGridGenerator(0.02, 0.5, 4, 12);
	    m_betaGenerator->setDistanceFunction(dist);
	    m_descriptor = m_betaGenerator;
	    descriptor = "beta";
	    break;
	case 1:
	    m_shapeGenerator = new ShapeContextGenerator(0.02, 0.5, 4, 12);
	    m_shapeGenerator->setDistanceFunction(dist);
	    m_descriptor = m_shapeGenerator;
	    descriptor = "shape";
	    break;
	default:
	    std::cerr << "Wrong descriptor type" << std::endl;
	    exit(-1);
    }
    
    switch(strategy){
	case 0:
	    m_ransac = new RansacFeatureSetMatcher(acceptanceSigma * acceptanceSigma * 5.99, success, inlier, matchingThreshold, acceptanceSigma * acceptanceSigma * 3.84, false);
	    break;
	case 1:
	    m_ransac = new RansacMultiFeatureSetMatcher(acceptanceSigma * acceptanceSigma * 5.99, success, inlier, matchingThreshold, acceptanceSigma * acceptanceSigma * 3.84, false);
	    break;
	default:
	    std::cerr << "Wrong strategy type" << std::endl;
	    exit(-1);
    }
    
    std::cerr << "Processing file:\t" << filename << "\nDetector:\t\t" << detector << "\nDescriptor:\t\t" << descriptor << "\nDistance:\t\t" << distance << std::endl;

    m_sensorReference.seek(0,END);
    unsigned int end = m_sensorReference.tell();
    m_sensorReference.seek(0,BEGIN);

    m_pointsReference.resize(end + 1);
    m_posesReference.resize(end + 1);
    
    detectLog();
    
    countLog();
    
    describeLog();
    
    std::string outfile = filename;
    
    timerclear(&ransacTime);
    
    std::string bar(50,' ');
    bar[0] = '#';
    unsigned int progress = 0;
    
    for(unsigned int i =0; i < m_pointsReference.size(); i++){
	unsigned int currentProgress = (i*100)/(m_pointsReference.size() - 1);
	if (progress < currentProgress){
	    progress = currentProgress;
	    bar[progress/2] = '#';
	    std::cout << "\rMatching  [" << bar << "] " << progress << "%" << std::flush;
	}
    	match(i);
    }
    std::cout << " done." << std::endl;
    
    std::stringstream matchFile;
    std::stringstream errorFile;
    std::stringstream timeFile;
    matchFile << outfile << "_" << detector << "_" << descriptor << "_" << distance << "_match.dat";
    errorFile << outfile << "_" << detector << "_" << descriptor << "_" << distance << "_error.dat";
    timeFile << outfile << "_" << detector << "_" << descriptor << "_" << distance << "_time.dat";
    
    std::ofstream matchOut(matchFile.str().c_str());
    std::ofstream errorOut(errorFile.str().c_str());
    std::ofstream timeOut(timeFile.str().c_str());
	
	matchOut << "# Number of matches according to various strategies" << std::endl;
    matchOut << "# The valid matches are the one with at least n correspondences in the inlier set " << std::endl;
    matchOut << "# where n = {0, 3, 5, 7, 9, 11, 13, 15}, one for each line " << std::endl;
    matchOut << "# optimal \t correspondence \t residual \v valid" << std::endl;
    
	errorOut << "# Mean error according to various strategies" << std::endl;
	errorOut << "# The valid matches are the one with at least n correspondences in the inlier set " << std::endl;
    errorOut << "# where n = {0, 3, 5, 7, 9, 11, 13, 15}, one for each line " << std::endl;
    errorOut << "# optimal \t correspondence \t residual \v valid" << std::endl;
	
	timeOut << "# Total time spent for the various steps" << std::endl;
	timeOut << "# detection \t description \t RANSAC" << std::endl;

    for(unsigned int c = 0; c < 8; c++){
      matchOut << m_match[c] << "\t" << m_matchC[c] << "\t" << m_matchR[c] << "\t" << m_valid[c] << std::endl;
      errorOut << m_error[c]/m_valid[c] << "\t" << m_errorC[c]/m_valid[c] << "\t" << m_errorR[c]/m_valid[c] << "\t" << m_valid[c] << std::endl;
    }
    timeOut << double(detectTime.tv_sec) + 1e-06 * double(detectTime.tv_usec) << "\t"
	    << double(describeTime.tv_sec) + 1e-06 * double(describeTime.tv_usec) << "\t"
	    << double(ransacTime.tv_sec) + 1e-06 * double(ransacTime.tv_usec) << std::endl;
}