<commit_before>#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <cmath>
#include <unistd.h>		//for usleep
using namespace std;

// bool RequestToSend = false;
// bool ArrivalNotificationSenderSide = false;
// bool TimeOut = false;
// bool ArrivalNotificationReceiverSide = false;

// int Sw = pow(2, m-1);
// int Sf = 0;
// int Sn = 0;

// int Rn = 0;
// bool NakSent = false;
// AckNeeded = false;

//ssh test

int scount = 0;
int rcount = 0;

int m = 4;
int Sw = pow(2, m-1);
int Sf = 0;
int Sn = 0;

string messages[3] = {"I", "am", "Rohit"};
string message;
int messageNo = 0;
int i = 0;

void * upperLayer(void * arg){
	if(i == 0){
		usleep(3000);
		if(messageNo < 2){
			message = message[messageNo++];
			requestToSend = true;
		}else{
			requestToSend = false;
		}
	}
}

// class Frame{
// public:
// 	char seqNo;
// 	char value;
// 	char crcRemainder;
// };

char GetData(){
	char data;
	if(i < message.length()){
		data = message[i++];
	}else if(i == message.length()){
		requestToSend = false;
		data = message[i];
		i = 0;
	}
	return data;
}

int MakeFrame(char data, int Sn ){
	// Frame newFrame = new Frame();
	// newFrame.seqNo = (char)Sn;
	// newFrame.value = data;
	// newFrame.crcRemainder = (int)data/Sn;
	int frame = Sn << 8;
	frame = frame | data;
	frame = frame << 4;
	frame = frame | 11;
	frame = frame << 2;
	frame = frame | 0; //00 means send; 10 means send ack; 11 means nack
}

void * requestToSendHandler(void * arg){
	vector<Frame> frameBuffer;
	while(true){
		 if(RequestToSend == true){
			if(Sn -Sf >= Sw){
				usleep(2000);
			}
			if(Sn - Sf < Sw){
				char data = GetData();
				MakeFrame(data, Sn);
				StoreFrame(Sn);
				SendFrame(Sn);
				Sn = Sn + 1;
				StartTimer(Sn);
			}
		}
	}
}

void * sending(void* arg){
	//spawn three event threads
	pthread_t requestToSendThread;
	pthread_create(&requestToSendThread, NULL, requestToSendHandler,NULL);
	pthread_join(requestToSendThread, NULL);

	// while(true){
	// 	scount++;
	// 	printf("sending.....%d\n",scount);
		// if(RequestToSend == true){
		// 	if(Sn -Sf >= Sw){
		// 		Sleep();
		// 	}
		// 	if(Sn - Sf < Sw){
		// 		GetData();
		// 		MakeFrame(Sn);
		// 		StoreFrame(Sn);
		// 		SendFrame(Sn);
		// 		Sn = Sn + 1;
		// 		StartTimer(Sn);
		// 	}
		// }
		// if(ArrivalNotificationSenderSide == true){
		// 	Receive(frame);
		// 	if(corrupted(frame))
		// 		Sleep();
		// 	else{
		// 		if(FrameType == NAK){
		// 			if(nakNo >= Sf && nakNo <= Sn){
		// 				resend(nakNo);
		// 				StartTimer(nakNo);
		// 			}
		// 		}
		// 		if(FrameType == ACK){
		// 			if(ackNo >= Sf && ackNo <= Sn){
		// 				while(Sf < ackNo){
		// 					Purge(Sf);
		// 					StopTimer(Sf);
		// 					Sf = Sf + 1;
		// 				}
		// 			}
		// 		}
		// 	}
		// }
		// if(TimeOut == true){
		// 	StartTimer(t);
		// 	SendFrame(t)
		// }
	// }
}

void * receiving(void *arg){
	//spawn the single thread
	// while(true){
	// 	rcount++;
	// 	printf("receiving.....%d\n",rcount);
		// if(ArrivalNotificationReceiverSide == true){
		// 	Receive(Frame);
		// 	if(corrupted(Frame) && (! NakSent)){
		// 		SendNAK(Rn);
		// 		NakSent = true;
		// 		Sleep();
		// 	}
		// 	if((seqNo < Rn || seqNo > Rn) && (! NakSent){
		// 		SendNAK(Rn);
		// 		NakSent = true;
		// 		if((seqNo in  window) && (!Marked(seqNo))){
		// 			StoreFrame(seqNo);
		// 			Marked(seqNo) = true;
		// 			while(Marked(Rn)){
		// 				DeliverData(Rn);
		// 				Purge(Rn);
		// 				Rn = Rn + 1;
		// 				AckNeeded = true;
		// 			}
		// 			if(AckNeeded == ture){
		// 				sendAck(Rn);
		// 				AckNeeded = false;
		// 				NakSent = false;
		// 			}
		// 		}
		// 	}
		// }
	// }
}

int main(){
	//Spawn two threads which do the
	//sending and receiving
	pthread_t sendingThread, receivingThread;

	pthread_create(&sendingThread, NULL, sending, NULL);
	pthread_create(&receivingThread, NULL, receiving, NULL);

	pthread_join(sendingThread, NULL);
	pthread_join(receivingThread, NULL);

	pthread_exit(NULL);
	return 0;
}<commit_msg>Added makeframe with no ack<commit_after>#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <cmath>
#include <unistd.h>		//for usleep
using namespace std;

// bool RequestToSend = false;
// bool ArrivalNotificationSenderSide = false;
// bool TimeOut = false;
// bool ArrivalNotificationReceiverSide = false;

// int Sw = pow(2, m-1);
// int Sf = 0;
// int Sn = 0;

// int Rn = 0;
// bool NakSent = false;
// AckNeeded = false;

//ssh test

int scount = 0;
int rcount = 0;

int m = 4;
int Sw = pow(2, m-1);
int Sf = 0;
int Sn = 0;

string messages[3] = {"I", "am", "Rohit"};
string message;
int messageNo = 0;
int i = 0;

void * upperLayer(void * arg){
	if(i == 0){
		usleep(3000);
		if(messageNo < 2){
			message = message[messageNo++];
			requestToSend = true;
		}else{
			requestToSend = false;
		}
	}
}

// class Frame{
// public:
// 	char seqNo;
// 	char value;
// 	char crcRemainder;
// };

char GetData(){
	char data;
	if(i < message.length()){
		data = message[i++];
	}else if(i == message.length()){
		requestToSend = false;
		data = message[i];
		i = 0;
	}
	return data;
}

int MakeFrame(char data, int Sn ){
	// Frame newFrame = new Frame();
	// newFrame.seqNo = (char)Sn;
	// newFrame.value = data;
	// newFrame.crcRemainder = (int)data/Sn;
	int frame = Sn << 8;
	frame = frame | data;
	frame = frame << 4;
	frame = frame | 11;
	frame = frame << 2;
	frame = frame | 0; //00 means send; 01 means send ack; 11 means nack
}

void * requestToSendHandler(void * arg){
	vector<Frame> frameBuffer;
	while(true){
		 if(RequestToSend == true){
			if(Sn -Sf >= Sw){
				usleep(2000);
			}
			if(Sn - Sf < Sw){
				char data = GetData();
				MakeFrame(data, Sn);
				StoreFrame(Sn);
				SendFrame(Sn);
				Sn = Sn + 1;
				StartTimer(Sn);
			}
		}
	}
}

void * sending(void* arg){
	//spawn three event threads
	pthread_t requestToSendThread;
	pthread_create(&requestToSendThread, NULL, requestToSendHandler,NULL);
	pthread_join(requestToSendThread, NULL);

	// while(true){
	// 	scount++;
	// 	printf("sending.....%d\n",scount);
		// if(RequestToSend == true){
		// 	if(Sn -Sf >= Sw){
		// 		Sleep();
		// 	}
		// 	if(Sn - Sf < Sw){
		// 		GetData();
		// 		MakeFrame(Sn);
		// 		StoreFrame(Sn);
		// 		SendFrame(Sn);
		// 		Sn = Sn + 1;
		// 		StartTimer(Sn);
		// 	}
		// }
		// if(ArrivalNotificationSenderSide == true){
		// 	Receive(frame);
		// 	if(corrupted(frame))
		// 		Sleep();
		// 	else{
		// 		if(FrameType == NAK){
		// 			if(nakNo >= Sf && nakNo <= Sn){
		// 				resend(nakNo);
		// 				StartTimer(nakNo);
		// 			}
		// 		}
		// 		if(FrameType == ACK){
		// 			if(ackNo >= Sf && ackNo <= Sn){
		// 				while(Sf < ackNo){
		// 					Purge(Sf);
		// 					StopTimer(Sf);
		// 					Sf = Sf + 1;
		// 				}
		// 			}
		// 		}
		// 	}
		// }
		// if(TimeOut == true){
		// 	StartTimer(t);
		// 	SendFrame(t)
		// }
	// }
}

void * receiving(void *arg){
	//spawn the single thread
	// while(true){
	// 	rcount++;
	// 	printf("receiving.....%d\n",rcount);
		// if(ArrivalNotificationReceiverSide == true){
		// 	Receive(Frame);
		// 	if(corrupted(Frame) && (! NakSent)){
		// 		SendNAK(Rn);
		// 		NakSent = true;
		// 		Sleep();
		// 	}
		// 	if((seqNo < Rn || seqNo > Rn) && (! NakSent){
		// 		SendNAK(Rn);
		// 		NakSent = true;
		// 		if((seqNo in  window) && (!Marked(seqNo))){
		// 			StoreFrame(seqNo);
		// 			Marked(seqNo) = true;
		// 			while(Marked(Rn)){
		// 				DeliverData(Rn);
		// 				Purge(Rn);
		// 				Rn = Rn + 1;
		// 				AckNeeded = true;
		// 			}
		// 			if(AckNeeded == ture){
		// 				sendAck(Rn);
		// 				AckNeeded = false;
		// 				NakSent = false;
		// 			}
		// 		}
		// 	}
		// }
	// }
}

int main(){
	//Spawn two threads which do the
	//sending and receiving
	pthread_t sendingThread, receivingThread;

	pthread_create(&sendingThread, NULL, sending, NULL);
	pthread_create(&receivingThread, NULL, receiving, NULL);

	pthread_join(sendingThread, NULL);
	pthread_join(receivingThread, NULL);

	pthread_exit(NULL);
	return 0;
}<|endoftext|>


<commit_before>/**
 * @author : xiaozhuai
 * @date   : 17/3/18
 */

#include "ServEnv.h"

ServEnv ServEnv::instance;

string __dump_list__[] = {
        KEY_LISTEN,                     DEFAULT_LISTEN,
        KEY_PORT,                       DEFAULT_PORT,
        KEY_DIR_INDEXS,                 DEFAULT_DIR_INDEXS,
        KEY_DIR_INDEXS_TPL,             DEFAULT_DIR_INDEXS_TPL,
        KEY_ERR_TPL,                    DEFAULT_ERR_TPL,
        KEY_ACCESS_RULE,                DEFAULT_ACCESS_RULE
};

#define OVERRIDE_FLAG_STR(overridden)           ( overridden ? "\033[32m[ custom  ] \033[0m" : "\033[33m[ default ] \033[0m" )

ServEnv::ServEnv() : webRoot(DEFAULT_WEB_ROOT),
                     absoluteWebRoot(DEFAULT_WEB_ROOT),
                     customWebRoot(false),
                     ini(NULL) {

}

ServEnv::~ServEnv() {
    if (ini != NULL) delete ini;
}

void ServEnv::setWebRoot(string path) {
    webRoot = path;
    rtrim(webRoot, '/');
    FileHandler file(webRoot);
    absoluteWebRoot = file.getAbsolutePath();
    customWebRoot = true;
}

string ServEnv::getWebRoot() {
    return webRoot;
}

string ServEnv::getAbsoluteWebRoot() {
    return absoluteWebRoot;
}

void ServEnv::parseConfig(string path) {
    if (path == "") {
        path = webRoot + "/" + DEFAULT_INI_FILE;
        LOGI("No provided config file, try \"%s\"", path);
    }
    ini = Ini::parse(path);
    if (ini->perror == Ini::NO_ERROR) {
        LOGI("Parse config file \"%s\" %ssuc%s", path, ANSI_COLOR_GREEN, ANSI_COLOR_NORMAL);
    } else {
        ini = new Ini();
        LOGI(
                "Parse config file \"%s\" %sfailed%s, maybe file not exist, will use default values for all params",
                path, ANSI_COLOR_ORANGE, ANSI_COLOR_NORMAL
        );
    }
}

string ServEnv::getConfig(string key, string defaultValue) {
    return ini->get(key, defaultValue);
}

bool ServEnv::customConfig(string key) {
    return ini->exist(key);
}

void ServEnv::dumpWebRoot() {
    if (!customWebRoot) {
        LOGI("No provided web root, use %s/var/www%s", ANSI_COLOR_BLUE, ANSI_COLOR_NORMAL);
    } else {
        LOGI("Web root is %s%s%s, absolute path is %s%s%s",
             ANSI_COLOR_BLUE, webRoot, ANSI_COLOR_NORMAL,
             ANSI_COLOR_BLUE, absoluteWebRoot, ANSI_COLOR_NORMAL
        );
    }
}

void ServEnv::dumpConfigs() {
    for (int i = 0; i < sizeof(__dump_list__) / sizeof(string) / 2; ++i) {
        string key = __dump_list__[i * 2];
        string defaultValue = __dump_list__[i * 2 + 1];
        LOGI(
                "%s %s%s = %s%s",
                OVERRIDE_FLAG_STR(customConfig(key)),
                ANSI_COLOR_BLUE, key, getConfig(key, defaultValue), ANSI_COLOR_NORMAL
        );
    }
}<commit_msg>fix a memory leak<commit_after>/**
 * @author : xiaozhuai
 * @date   : 17/3/18
 */

#include "ServEnv.h"

ServEnv ServEnv::instance;

string __dump_list__[] = {
        KEY_LISTEN,                     DEFAULT_LISTEN,
        KEY_PORT,                       DEFAULT_PORT,
        KEY_DIR_INDEXS,                 DEFAULT_DIR_INDEXS,
        KEY_DIR_INDEXS_TPL,             DEFAULT_DIR_INDEXS_TPL,
        KEY_ERR_TPL,                    DEFAULT_ERR_TPL,
        KEY_ACCESS_RULE,                DEFAULT_ACCESS_RULE
};

#define OVERRIDE_FLAG_STR(overridden)           ( overridden ? "\033[32m[ custom  ] \033[0m" : "\033[33m[ default ] \033[0m" )

ServEnv::ServEnv() : webRoot(DEFAULT_WEB_ROOT),
                     absoluteWebRoot(DEFAULT_WEB_ROOT),
                     customWebRoot(false),
                     ini(NULL) {

}

ServEnv::~ServEnv() {
    if (ini != NULL) delete ini;
}

void ServEnv::setWebRoot(string path) {
    webRoot = path;
    rtrim(webRoot, '/');
    FileHandler file(webRoot);
    absoluteWebRoot = file.getAbsolutePath();
    customWebRoot = true;
}

string ServEnv::getWebRoot() {
    return webRoot;
}

string ServEnv::getAbsoluteWebRoot() {
    return absoluteWebRoot;
}

void ServEnv::parseConfig(string path) {
    if (path == "") {
        path = webRoot + "/" + DEFAULT_INI_FILE;
        LOGI("No provided config file, try \"%s\"", path);
    }
    ini = Ini::parse(path);
    if (ini->perror == Ini::NO_ERROR) {
        LOGI("Parse config file \"%s\" %ssuc%s", path, ANSI_COLOR_GREEN, ANSI_COLOR_NORMAL);
    } else {
        LOGI(
                "Parse config file \"%s\" %sfailed%s, maybe file not exist, will use default values for all params",
                path, ANSI_COLOR_ORANGE, ANSI_COLOR_NORMAL
        );
    }
}

string ServEnv::getConfig(string key, string defaultValue) {
    return ini->get(key, defaultValue);
}

bool ServEnv::customConfig(string key) {
    return ini->exist(key);
}

void ServEnv::dumpWebRoot() {
    if (!customWebRoot) {
        LOGI("No provided web root, use %s/var/www%s", ANSI_COLOR_BLUE, ANSI_COLOR_NORMAL);
    } else {
        LOGI("Web root is %s%s%s, absolute path is %s%s%s",
             ANSI_COLOR_BLUE, webRoot, ANSI_COLOR_NORMAL,
             ANSI_COLOR_BLUE, absoluteWebRoot, ANSI_COLOR_NORMAL
        );
    }
}

void ServEnv::dumpConfigs() {
    for (int i = 0; i < sizeof(__dump_list__) / sizeof(string) / 2; ++i) {
        string key = __dump_list__[i * 2];
        string defaultValue = __dump_list__[i * 2 + 1];
        LOGI(
                "%s %s%s = %s%s",
                OVERRIDE_FLAG_STR(customConfig(key)),
                ANSI_COLOR_BLUE, key, getConfig(key, defaultValue), ANSI_COLOR_NORMAL
        );
    }
}<|endoftext|>


<commit_before>#include "scanner.h"

/*void Scanner::setInput(string in) {buffer = in;}

int Scanner::nextToken() {
    if (skipLeadingWhiteSpace() >= buffer.length())
      return EOS;
    else if (isdigit(currentChar())) {
      _tokenValue = extractNumber();
      return NUMBER;
    }  else if (islower(currentChar())) {
      string s = extractAtom();
      processToken<ATOM>(s);
      return ATOM;
    } else if (isSpecialCh(currentChar())) {
      string s = extractAtomSC();
      processToken<ATOMSC>(s);
      return ATOMSC;
    } else if (isupper(currentChar()) || currentChar() == '_') {
      string s = extractVar();
      processToken<VAR>(s);
      return VAR;
    } else {
      _tokenValue = NONE;
      return extractChar();
    }
}

int Scanner::tokenValue() const {return _tokenValue;}

int Scanner::skipLeadingWhiteSpace() {
  for (; (buffer[pos] == ' ' || buffer[pos] == '\t') && pos<buffer.length(); ++pos);
  return position();
}

int Scanner::position() const {return pos;}

char Scanner::currentChar() {
  return buffer[pos];
}

// extractX: extract X and set position right after X
int Scanner::extractNumber() {
  int posBegin = position();
  for (;isdigit(buffer[pos]); ++pos);
  //std::cout << pos << std::endl;
  return stoi(buffer.substr(posBegin, pos-posBegin));
}

string Scanner::extractAtom() {
  int posBegin = position();
  for (;isalnum(buffer[pos]); ++pos);
  return buffer.substr(posBegin, pos-posBegin);
}

string Scanner::extractAtomSC() {
  int posBegin = position();
  for (;isSpecialCh(buffer[pos]); ++pos);
  return buffer.substr(posBegin, pos-posBegin);
}

string Scanner::extractVar() {
  int posBegin = position();
  for (;isalnum(buffer[pos]) || buffer[pos] == '_'; ++pos);
  return buffer.substr(posBegin, pos-posBegin);
}

char Scanner::extractChar() {
  return buffer[pos++];
}
<commit_msg>Delete Scanner.cpp<commit_after><|endoftext|>


<commit_before>#include "common.h"
#include "World.h"
#include "Species.h"
#include <algorithm>

static long idGen = 0;

Species::Species(Species* originalSpecies){
  id = idGen++;
  distanceToAncestor = 1;

  if (originalSpecies == NULL){
    // completely new species
    ancestor = NULL;
    while (!generateDna()) ;
  }else{
    // evolution of an existing species
    ancestor = originalSpecies;

    vector<DNA*>::iterator itDNA;
    for (itDNA = originalSpecies->dna.begin(); itDNA != originalSpecies->dna.end(); ++itDNA) {
      DNA* from = (*itDNA);
      this->dna.push_back(new DNA(from));
    }
    // mutation:
    int randIdx = randInt(dna.size());
    delete this->dna[randIdx];
    this->dna[randIdx] = new DNA(NULL);
  }

  HSVtoRGB( &(this->r), &(this->g), &(this->b), randDouble(), 1, .65 );
}

// Don't allow species with impossible shape (z<1 or collision with self)
bool Species::generateDna(){
//cout<<"generate"<<endl;
  clearDna();

  DNA* d = new DNA(NULL);
  d->growthDirection = 4; // first cell has to go up
  this->dna.push_back(d);

  int pos[MAX_CELLS][3];
  pos[0][0] = pos[0][1] = pos[0][2] = 0;
  pos[1][0] = pos[1][1] = 0;
  pos[1][2] = 1;

  for (int i=2; i<world.maxCells; ++i){ // (i-1) -> i
    int x = pos[i-1][0], y = pos[i-1][1], z = pos[i-1][2];

    vector<int> takenDirs;
    bool canGoDown = true;

    for (int j=0; j<i-1; ++j){
      int prevX = pos[j][0], prevY = pos[j][1], prevZ = pos[j][2];
      if (prevX == x+1 && prevY == y   && prevZ == z)   takenDirs.push_back(0);
      if (prevX == x-1 && prevY == y   && prevZ == z)   takenDirs.push_back(1);
      if (prevX == x   && prevY == y+1 && prevZ == z)   takenDirs.push_back(2);
      if (prevX == x   && prevY == y-1 && prevZ == z)   takenDirs.push_back(3);
      if (prevX == x   && prevY == y   && prevZ == z+1) takenDirs.push_back(4);
      if (prevX == x   && prevY == y   && prevZ == z-1) {
        takenDirs.push_back(5);
        canGoDown = false;
      }
    }

    // the only position available is downwards but Z=0 is disallowed:
    if (canGoDown && takenDirs.size() == 5 && z<=1) return false;

    // all positions around are already taken:
    if (takenDirs.size() == 6) return false;

    // don't allow Z=0
    if (canGoDown && z == 1) takenDirs.push_back(5);

    if (takenDirs.size() >6) {
      cout << "ERROR: more than 6 taken dirs!" <<endl;
      for (unsigned int p=0;p<takenDirs.size();p++) cout<<takenDirs[p]<<" "<<endl;
      cout<<"relative creature position so far:"<<endl;
      for (int e=0; e<i; ++e){
        cout<<"\t" << pos[e][0] << ", " << pos[e][1] << ", " << pos[e][2] <<endl;
      }
    }

    int direction = randInt(6 - takenDirs.size());
    for (unsigned int k=0; k<takenDirs.size(); ++k){
      if (takenDirs[k] <= direction){
        ++direction;
      }
    }

//cout << "new direction="<< direction << endl;

    DNA* d = new DNA(NULL);
    d->growthDirection = direction;
    this->dna.push_back(d);

    pos[i][0] = x;
    pos[i][1] = y;
    pos[i][2] = z;

    if      (direction == 0) pos[i][0] = x+1;
    else if (direction == 1) pos[i][0] = x-1;
    else if (direction == 2) pos[i][1] = y+1;
    else if (direction == 3) pos[i][1] = y-1;
    else if (direction == 4) pos[i][2] = z+1;
    else if (direction == 5) pos[i][2] = z-1;
//    cout<<"pos="<<pos[i][0]<<", "<<pos[i][1]<<", "<<pos[i][2]<<endl;
  }

  return true;
}

void Species::setColor(float r, float g, float b){
  this->r=r; this->g=g; this->b=b;
}

void Species::kill(Creature* c){
  list<Creature*>::iterator it = find(creatures.begin(), creatures.end(), c);
  if (it == creatures.end()){
    cout<<"Cannot kill creature: not found!"<<endl;
    exit(5);
  }else{
    delete *it;
    creatures.erase(it);
  }
}

int Species::killOldAndWeakCreatures(){
  std::list<Creature*>::iterator itCreature = creatures.begin();

  int deathCount = 0;
  while (itCreature != creatures.end()){
    Creature* c = (*itCreature);
    if (c->cells.size() >= (unsigned int)world.maxCells
        || world.cycle - c->creationCycle >= world.maxCells
        || !c->hasEnoughEnergy()){
      if (DEBUG) cout << "Creature dies." <<endl;
      delete c;
      itCreature = creatures.erase(itCreature);
      ++deathCount;
    }else{
      ++itCreature;
    }
  }

  return deathCount;
}

Creature* Species::reproduce(int x, int y){
  Creature* c = new Creature( (*this), x, y );
  creatures.push_back(c);
  return c;
}

void Species::clearDna(){
  vector<DNA*>::iterator itDNA;
  for (itDNA = dna.begin(); itDNA != dna.end(); ++itDNA) {
    delete (*itDNA);
  }
  this->dna.clear();
}

Species::~Species(){
  list<Creature*>::iterator itCreature;
  for (itCreature = creatures.begin(); itCreature != creatures.end(); ++itCreature) {
    delete (*itCreature);
  }

  clearDna();
}

DNA::DNA(DNA* from){
  for (int i=0;i<6;i++) {
    this->probas[i] = (from!=NULL) ? from->probas[i] : randDouble();
  }
  growthDirection = from!=NULL ? from->growthDirection:randInt(6);
}
<commit_msg>Fixed Species shape inconsistency<commit_after>#include "common.h"
#include "World.h"
#include "Species.h"
#include <algorithm>

static long idGen = 0;

Species::Species(Species* originalSpecies){
  id = idGen++;
  distanceToAncestor = 1;

  if (originalSpecies == NULL){
    // completely new species
    ancestor = NULL;
    while (!generateDna()) ;
  }else{
    // evolution of an existing species
    ancestor = originalSpecies;

    vector<DNA*>::iterator itDNA;
    for (itDNA = originalSpecies->dna.begin(); itDNA != originalSpecies->dna.end(); ++itDNA) {
      DNA* from = (*itDNA);
      this->dna.push_back(new DNA(from));
    }
    // mutation:
    int randIdx = randInt(dna.size());
    delete this->dna[randIdx];
    this->dna[randIdx] = new DNA(NULL);
  }

  HSVtoRGB( &(this->r), &(this->g), &(this->b), randDouble(), 1, .65 );
}

// Don't allow species with impossible shape (z<1 or collision with self)
bool Species::generateDna(){
  clearDna();

  DNA* d = new DNA(NULL);
  d->growthDirection = 4; // first cell has to go up
  this->dna.push_back(d);

  int pos[MAX_CELLS][3];
  pos[0][0] = pos[0][1] = pos[0][2] = 0;
  pos[1][0] = pos[1][1] = 0;
  pos[1][2] = 1;

  for (int i=2; i<world.maxCells; ++i){ // (i-1) -> i
    int x = pos[i-1][0], y = pos[i-1][1], z = pos[i-1][2];

    vector<int> takenDirs;
    bool canGoDown = true;

    for (int j=0; j<i-1; ++j){
      int prevX = pos[j][0], prevY = pos[j][1], prevZ = pos[j][2];

      if      (prevX == x+1 && prevY == y   && prevZ == z)   takenDirs.push_back(0);
      else if (prevX == x-1 && prevY == y   && prevZ == z)   takenDirs.push_back(1);
      else if (prevX == x   && prevY == y+1 && prevZ == z)   takenDirs.push_back(2);
      else if (prevX == x   && prevY == y-1 && prevZ == z)   takenDirs.push_back(3);
      else if (prevX == x   && prevY == y   && prevZ == z+1) takenDirs.push_back(4);
      else if (prevX == x   && prevY == y   && prevZ == z-1) {
        takenDirs.push_back(5);
        canGoDown = false;
      }
    }

    // the only position available is downwards but Z=0 is disallowed:
    if (canGoDown && takenDirs.size() == 5 && z<=1) return false;

    // all positions around are already taken:
    if (takenDirs.size() == 6) return false;

    // don't allow Z=0
    if (canGoDown && z == 1) takenDirs.push_back(5);

    if (takenDirs.size() >6) {
      cout << "ERROR: more than 6 taken dirs!" <<endl;
      exit(8);
    }

    int direction = randInt(6 - takenDirs.size());
    sort(takenDirs.begin(), takenDirs.end(), std::less<int>());
    for (unsigned int k=0; k<takenDirs.size(); ++k){
      if (takenDirs[k] <= direction){
        ++direction;
      }
    }

    DNA* d = new DNA(NULL);
    d->growthDirection = direction;
    this->dna.push_back(d);

    pos[i][0] = x;
    pos[i][1] = y;
    pos[i][2] = z;

    if      (direction == 0) pos[i][0] = x+1;
    else if (direction == 1) pos[i][0] = x-1;
    else if (direction == 2) pos[i][1] = y+1;
    else if (direction == 3) pos[i][1] = y-1;
    else if (direction == 4) pos[i][2] = z+1;
    else if (direction == 5) pos[i][2] = z-1;
  }

  return true;
}

void Species::setColor(float r, float g, float b){
  this->r=r; this->g=g; this->b=b;
}

void Species::kill(Creature* c){
  list<Creature*>::iterator it = find(creatures.begin(), creatures.end(), c);
  if (it == creatures.end()){
    cout<<"Cannot kill creature: not found!"<<endl;
    exit(5);
  }else{
    delete *it;
    creatures.erase(it);
  }
}

int Species::killOldAndWeakCreatures(){
  std::list<Creature*>::iterator itCreature = creatures.begin();

  int deathCount = 0;
  while (itCreature != creatures.end()){
    Creature* c = (*itCreature);
    if (c->cells.size() >= (unsigned int)world.maxCells
        || world.cycle - c->creationCycle >= world.maxCells
        || !c->hasEnoughEnergy()){
      if (DEBUG) cout << "Creature dies." <<endl;
      delete c;
      itCreature = creatures.erase(itCreature);
      ++deathCount;
    }else{
      ++itCreature;
    }
  }

  return deathCount;
}

Creature* Species::reproduce(int x, int y){
  Creature* c = new Creature( (*this), x, y );
  creatures.push_back(c);
  return c;
}

void Species::clearDna(){
  vector<DNA*>::iterator itDNA;
  for (itDNA = dna.begin(); itDNA != dna.end(); ++itDNA) {
    delete (*itDNA);
  }
  this->dna.clear();
}

Species::~Species(){
  list<Creature*>::iterator itCreature;
  for (itCreature = creatures.begin(); itCreature != creatures.end(); ++itCreature) {
    delete (*itCreature);
  }

  clearDna();
}

DNA::DNA(DNA* from){
  for (int i=0;i<6;i++) {
    this->probas[i] = (from!=NULL) ? from->probas[i] : randDouble();
  }
  growthDirection = from!=NULL ? from->growthDirection:randInt(6);
}
<|endoftext|>


<commit_before>#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDirIterator>
#include <QDebug>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_OFPath("")
    , m_OFAddonsPath("")
    , m_OFAppTemplatePath("")
    , m_AppPath("")
    , m_AddonsPath("")
    , m_IsAppNameValid(false)
{
    ui->setupUi(this);
    connect(ui->lineEditOfPath, SIGNAL(textChanged(QString)), this, SLOT(getAddonNames()));
    connect(ui->lineEditAppName, SIGNAL(textChanged(QString)), this, SLOT(checkAppNameValidity(QString)));
    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(getSelectedAddons(QListWidgetItem *)));
    connect(ui->buttonOfPath, SIGNAL(pressed()), this, SLOT(browseOFPath()));
    connect(ui->buttonAppPath, SIGNAL(pressed()), this, SLOT(browseAppPath()));
    connect(ui->buttonGenerate, SIGNAL(pressed()), this, SLOT(generateProject()));
}

MainWindow::~MainWindow()
{
    for (int i = 0; i < m_AddonItems.size(); i++) {
        delete m_AddonItems[i];
    }
    m_AddonItems.clear();
    delete ui;
}

void MainWindow::getAddonNames()
{
    ui->listWidget->clear();
    m_OFPath = ui->lineEditOfPath->text() + "/";
    m_OFAddonsPath = m_OFPath + "addons/";
    m_OFAppTemplatePath = m_OFPath + "apps/myApps/emptyExample/src/";

    QDirIterator dirIteratorTop(m_OFAddonsPath, QDirIterator::NoIteratorFlags);
    if (dirIteratorTop.hasNext() == false) {
        ui->lineEditOfPath->setStyleSheet("color: red");
    }
    else {
        ui->lineEditOfPath->setStyleSheet("");
    }
    while (dirIteratorTop.hasNext()) {
        dirIteratorTop.next();
        if (dirIteratorTop.fileName() == "." || dirIteratorTop.fileName() == "..") {
            continue;
        }
        QListWidgetItem *wid = new QListWidgetItem(ui->listWidget);
        wid->setText(dirIteratorTop.fileName());
        wid->setCheckState(Qt::CheckState::Unchecked);
        m_AddonItems.append(wid);
    }
}

void MainWindow::checkAppNameValidity(QString str)
{
    if (str.contains(" ")) {
        ui->lineEditAppName->setStyleSheet("color: red");
        m_IsAppNameValid = false;
    }
    else {
        ui->lineEditAppName->setStyleSheet("");
        m_IsAppNameValid = true;
    }
}

void MainWindow::browseOFPath()
{
    QFileDialog dialog(this, "Select OF Path");
    const QString selectedDir = dialog.getExistingDirectory();
    ui->lineEditOfPath->setText(selectedDir);
}

void MainWindow::browseAppPath()
{
    QFileDialog dialog(this, "Select App Path");
    const QString selectedDir = dialog.getExistingDirectory();
    ui->lineEditAppPath->setText(selectedDir);
}

void MainWindow::getSelectedAddons(QListWidgetItem *selectedItem)
{
    if (selectedItem == nullptr) {
        return;
    }

    if (selectedItem->checkState() == Qt::Checked && m_SelectedAddons.contains(selectedItem->text()) == false) {
        m_SelectedAddons.append(selectedItem->text());
    }
    else if (selectedItem->checkState() == Qt::Unchecked && m_SelectedAddons.contains(selectedItem->text())) {
        m_SelectedAddons.removeAt(m_SelectedAddons.indexOf(selectedItem->text()));
    }
}

void MainWindow::generateProject()
{
    QFile priFile("./data/openFrameworks-0.8.4.pri");
    QDir dir(ui->lineEditAppPath->text() + "/");
    //Create the project dir and copy the template
    if (dir.exists()) {
        dir.mkdir(ui->lineEditAppName->text());
        m_AppPath = ui->lineEditAppPath->text() + "/" + ui->lineEditAppName->text() + "/";
        QFile::copy(m_OFAppTemplatePath + "main.cpp", m_AppPath + "main.cpp");
        QFile::copy(m_OFAppTemplatePath + "ofApp.cpp", m_AppPath + "ofApp.cpp");
        QFile::copy(m_OFAppTemplatePath + "ofApp.h", m_AppPath + "ofApp.h");
        QFile::copy("./data/proFileTemplate.pro", m_AppPath + ui->lineEditAppName->text() + ".pro");
    }

    if (priFile.exists() && priFile.open(QIODevice::ReadOnly)) {
        QString contents = QString(priFile.readAll());
        //Insert OF path
        QString ofPathWithoutSuffix = m_OFPath;
        contents.replace("#OF_PATH#", ofPathWithoutSuffix.remove(ofPathWithoutSuffix.length() - 1, 1));
        insertAddons(contents);

        //Write the changed pri file to the new path
        QFile newProFile(m_AppPath + "openFrameworks-0.8.4.pri");
        if (newProFile.open(QIODevice::WriteOnly)) {
            newProFile.write(contents.toStdString().c_str());
            newProFile.close();
        }

    }
    priFile.close();
    ui->statusBar->showMessage("Project generated", 5000);
    ui->lineEditAppName->clear();
    for (int i = 0; i < m_AddonItems.size(); i++) {
        QListWidgetItem *item = m_AddonItems.at(i);
        item->setCheckState(Qt::Unchecked);
    }
}

void MainWindow::insertAddons(QString &priContent)
{
    if (m_SelectedAddons.size() == 0) {
        return;
    }

    bool isCopyEnabled = ui->checkBox->isChecked();
    QString addonRootPath = m_OFAddonsPath;
    if (isCopyEnabled) {
        QDir dir(m_AppPath);
        if (dir.exists()) {
            dir.mkdir("addons");
            m_AddonsPath = m_AppPath + "addons/";
        }
        addonRootPath = m_AddonsPath;
        for (int i = 0; i < m_SelectedAddons.size(); i++) {
            const QString srcAddonPath = m_OFAddonsPath + m_SelectedAddons.at(i);
            copyRecursively(srcAddonPath, m_AddonsPath);
        }
    }

    QStringList includePaths;
    for (int i = 0; i < m_SelectedAddons.size(); i++) {
        const QString addonName = m_SelectedAddons.at(i);
        priContent += "#" + addonName + "\n";
        const QString addonPath = addonRootPath + addonName;
        QDirIterator dirIt(addonPath, QDirIterator::Subdirectories);
        while (dirIt.hasNext()) {
            dirIt.next();
            if (dirIt.fileName() == "." || dirIt.fileName() == "..") {
                continue;
            }

            if (dirIt.fileInfo().isDir()) {
                if (includePaths.contains(dirIt.fileInfo().absoluteDir().absolutePath()) == false) {
                    priContent += "INCLUDEPATH += " + dirIt.filePath() + "\n";
                }
                continue;
            }

            if (dirIt.fileInfo().suffix() == "cpp") {
                priContent += "SOURCES += " + dirIt.filePath() + "\n";
            }
            else if (dirIt.fileInfo().suffix() == "h") {
                priContent += "HEADERS += " + dirIt.filePath() + "\n";
            }
            else if (dirIt.fileInfo().suffix() == "lib") {
                priContent += "LIBS += " + dirIt.filePath() + "\n";
            }
        }
    }
}

bool MainWindow::copyRecursively(const QString &srcFilePath, const QString &tgtFilePath)
{
    QFileInfo srcFileInfo(srcFilePath);
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        if (targetDir.exists() == false) {
            targetDir.cdUp();
        }
        if (!targetDir.mkdir(srcFileInfo.fileName())) {
            return false;
        }

        targetDir.cd(srcFileInfo.fileName());
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        foreach (const QString &fileName, fileNames) {
            const QString newSrcFilePath = srcFilePath + QLatin1Char('/') + fileName;
            const QString newTgtFilePath = targetDir.absolutePath() + QLatin1Char('/') + fileName;
            if (!copyRecursively(newSrcFilePath, newTgtFilePath)) {
                return false;
            }
        }
    }
    else {
        if (!QFile::copy(srcFilePath, tgtFilePath)) {
            return false;
        }
    }
    return true;
}
<commit_msg>Add quotation marks to include and lib path in case the directory have spaces<commit_after>#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDirIterator>
#include <QDebug>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_OFPath("")
    , m_OFAddonsPath("")
    , m_OFAppTemplatePath("")
    , m_AppPath("")
    , m_AddonsPath("")
    , m_IsAppNameValid(false)
{
    ui->setupUi(this);
    connect(ui->lineEditOfPath, SIGNAL(textChanged(QString)), this, SLOT(getAddonNames()));
    connect(ui->lineEditAppName, SIGNAL(textChanged(QString)), this, SLOT(checkAppNameValidity(QString)));
    connect(ui->listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(getSelectedAddons(QListWidgetItem *)));
    connect(ui->buttonOfPath, SIGNAL(pressed()), this, SLOT(browseOFPath()));
    connect(ui->buttonAppPath, SIGNAL(pressed()), this, SLOT(browseAppPath()));
    connect(ui->buttonGenerate, SIGNAL(pressed()), this, SLOT(generateProject()));
}

MainWindow::~MainWindow()
{
    for (int i = 0; i < m_AddonItems.size(); i++) {
        delete m_AddonItems[i];
    }
    m_AddonItems.clear();
    delete ui;
}

void MainWindow::getAddonNames()
{
    ui->listWidget->clear();
    m_OFPath = ui->lineEditOfPath->text() + "/";
    m_OFAddonsPath = m_OFPath + "addons/";
    m_OFAppTemplatePath = m_OFPath + "apps/myApps/emptyExample/src/";

    QDirIterator dirIteratorTop(m_OFAddonsPath, QDirIterator::NoIteratorFlags);
    if (dirIteratorTop.hasNext() == false) {
        ui->lineEditOfPath->setStyleSheet("color: red");
    }
    else {
        ui->lineEditOfPath->setStyleSheet("");
    }
    while (dirIteratorTop.hasNext()) {
        dirIteratorTop.next();
        if (dirIteratorTop.fileName() == "." || dirIteratorTop.fileName() == "..") {
            continue;
        }
        QListWidgetItem *wid = new QListWidgetItem(ui->listWidget);
        wid->setText(dirIteratorTop.fileName());
        wid->setCheckState(Qt::CheckState::Unchecked);
        m_AddonItems.append(wid);
    }
}

void MainWindow::checkAppNameValidity(QString str)
{
    if (str.contains(" ")) {
        ui->lineEditAppName->setStyleSheet("color: red");
        m_IsAppNameValid = false;
    }
    else {
        ui->lineEditAppName->setStyleSheet("");
        m_IsAppNameValid = true;
    }
}

void MainWindow::browseOFPath()
{
    QFileDialog dialog(this, "Select OF Path");
    const QString selectedDir = dialog.getExistingDirectory();
    ui->lineEditOfPath->setText(selectedDir);
}

void MainWindow::browseAppPath()
{
    QFileDialog dialog(this, "Select App Path");
    const QString selectedDir = dialog.getExistingDirectory();
    ui->lineEditAppPath->setText(selectedDir);
}

void MainWindow::getSelectedAddons(QListWidgetItem *selectedItem)
{
    if (selectedItem == nullptr) {
        return;
    }

    if (selectedItem->checkState() == Qt::Checked && m_SelectedAddons.contains(selectedItem->text()) == false) {
        m_SelectedAddons.append(selectedItem->text());
    }
    else if (selectedItem->checkState() == Qt::Unchecked && m_SelectedAddons.contains(selectedItem->text())) {
        m_SelectedAddons.removeAt(m_SelectedAddons.indexOf(selectedItem->text()));
    }
}

void MainWindow::generateProject()
{
    QFile priFile("./data/openFrameworks-0.8.4.pri");
    QDir dir(ui->lineEditAppPath->text() + "/");
    //Create the project dir and copy the template
    if (dir.exists()) {
        dir.mkdir(ui->lineEditAppName->text());
        m_AppPath = ui->lineEditAppPath->text() + "/" + ui->lineEditAppName->text() + "/";
        QFile::copy(m_OFAppTemplatePath + "main.cpp", m_AppPath + "main.cpp");
        QFile::copy(m_OFAppTemplatePath + "ofApp.cpp", m_AppPath + "ofApp.cpp");
        QFile::copy(m_OFAppTemplatePath + "ofApp.h", m_AppPath + "ofApp.h");
        QFile::copy("./data/proFileTemplate.pro", m_AppPath + ui->lineEditAppName->text() + ".pro");
    }

    if (priFile.exists() && priFile.open(QIODevice::ReadOnly)) {
        QString contents = QString(priFile.readAll());
        //Insert OF path
        QString ofPathWithoutSuffix = m_OFPath;
        contents.replace("#OF_PATH#", "\"" + ofPathWithoutSuffix.remove(ofPathWithoutSuffix.length() - 1, 1) + "\"");
        insertAddons(contents);

        //Write the changed pri file to the new path
        QFile newProFile(m_AppPath + "openFrameworks-0.8.4.pri");
        if (newProFile.open(QIODevice::WriteOnly)) {
            newProFile.write(contents.toStdString().c_str());
            newProFile.close();
        }

    }
    priFile.close();
    ui->statusBar->showMessage("Project generated", 5000);
    ui->lineEditAppName->clear();
    for (int i = 0; i < m_AddonItems.size(); i++) {
        QListWidgetItem *item = m_AddonItems.at(i);
        item->setCheckState(Qt::Unchecked);
    }
}

void MainWindow::insertAddons(QString &priContent)
{
    if (m_SelectedAddons.size() == 0) {
        return;
    }

    bool isCopyEnabled = ui->checkBox->isChecked();
    QString addonRootPath = m_OFAddonsPath;
    if (isCopyEnabled) {
        QDir dir(m_AppPath);
        if (dir.exists()) {
            dir.mkdir("addons");
            m_AddonsPath = m_AppPath + "addons/";
        }
        addonRootPath = m_AddonsPath;
        for (int i = 0; i < m_SelectedAddons.size(); i++) {
            const QString srcAddonPath = m_OFAddonsPath + m_SelectedAddons.at(i);
            copyRecursively(srcAddonPath, m_AddonsPath);
        }
    }

    QStringList includePaths;
    for (int i = 0; i < m_SelectedAddons.size(); i++) {
        const QString addonName = m_SelectedAddons.at(i);
        priContent += "#" + addonName + "\n";
        const QString addonPath = addonRootPath + addonName;
        QDirIterator dirIt(addonPath, QDirIterator::Subdirectories);
        while (dirIt.hasNext()) {
            dirIt.next();
            if (dirIt.fileName() == "." || dirIt.fileName() == "..") {
                continue;
            }

            if (dirIt.fileInfo().isDir()) {
                if (includePaths.contains(dirIt.fileInfo().absoluteDir().absolutePath()) == false) {
                    priContent += "INCLUDEPATH += \"" + dirIt.filePath() + "\"\n";
                }
                continue;
            }

            if (dirIt.fileInfo().suffix() == "cpp") {
                priContent += "SOURCES += \"" + dirIt.filePath() + "\"\n";
            }
            else if (dirIt.fileInfo().suffix() == "h") {
                priContent += "HEADERS += \"" + dirIt.filePath() + "\"\n";
            }
            else if (dirIt.fileInfo().suffix() == "lib") {
                priContent += "LIBS += \"" + dirIt.filePath() + "\"\n";
            }
        }
    }
}

bool MainWindow::copyRecursively(const QString &srcFilePath, const QString &tgtFilePath)
{
    QFileInfo srcFileInfo(srcFilePath);
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        if (targetDir.exists() == false) {
            targetDir.cdUp();
        }
        if (!targetDir.mkdir(srcFileInfo.fileName())) {
            return false;
        }

        targetDir.cd(srcFileInfo.fileName());
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        foreach (const QString &fileName, fileNames) {
            const QString newSrcFilePath = srcFilePath + QLatin1Char('/') + fileName;
            const QString newTgtFilePath = targetDir.absolutePath() + QLatin1Char('/') + fileName;
            if (!copyRecursively(newSrcFilePath, newTgtFilePath)) {
                return false;
            }
        }
    }
    else {
        if (!QFile::copy(srcFilePath, tgtFilePath)) {
            return false;
        }
    }
    return true;
}
<|endoftext|>


<commit_before>#include <math.h>

#include "str.hh"
#include "MllrTrainer.hh"

MllrTrainer::MllrTrainer(HmmSet &model, FeatureGenerator &feagen) :
  m_model(model),
  m_feagen(feagen)
{
  m_dim = m_model.dim();

  // create vector and matrix arrays
  k_array = new d_vector*[m_dim];
  G_array = new d_matrix*[m_dim];
  for (int i = 0; i < m_dim; i++)
  {
    k_array[i] = new d_vector(m_dim+1);
    G_array[i] = new d_matrix(m_dim+1, m_dim+1);
  }

  // set statistics to zero
  clear_stats();
}

MllrTrainer::~MllrTrainer()
{
  // Free allocated memory
  for (int i = 0; i < m_dim; i++)
  {
    delete k_array[i];
    delete G_array[i];
  }

  delete [] k_array;
  delete [] G_array;
}

void MllrTrainer::find_probs(HmmState *state, FeatureVec &feature)
{
  int k_index; // kernel index
  int kernelcount = (state->weights).size();
  float probs[kernelcount];
  float prob_sum = 0;

  // check dim

  if (m_dim != m_feagen.dim())
  {
    throw std::string("MllrTrainer: Model and feature dimensions disagree");
  }

  // get probabilities

  for (int k = 0; k < kernelcount; k++)
  {
    k_index = (state->weights[k]).kernel;

    if (((m_model.kernel(k_index)).cov).type() != HmmCovariance::DIAGONAL)
    {
      throw std::string("MllrTrainer: Expected diagonal covariance matrix");
    }

    probs[k] = m_model.compute_kernel_likelihood(k_index, feature);
    prob_sum = prob_sum + probs[k];

  }

  if (prob_sum != 0)
  {
    for (int k = 0; k < kernelcount; k++)
      probs[k] = probs[k]/prob_sum;
  }
  else
  {
    m_zero_prob_count++;
  }

  update_stats(state, probs, feature);
}

void MllrTrainer::calculate_transform(LinTransformModule *mllr_mod)
{
  int i, j; // rows, columns
  d_matrix A(m_dim, m_dim);
  float detA = 1;
  dense1D<int> pivots(m_dim);
  dense1D<int> pivots2(m_dim+1);
  d_matrix cofactors(m_dim, m_dim);
  d_matrix G(m_dim+1, m_dim+1);
  d_matrix G_inv(m_dim+1, m_dim+1);
  d_vector p(m_dim+1);
  d_vector w(m_dim+1);
  d_matrix trans(m_dim, m_dim+1);
  double alpha;

  // check that we have probabilities
  if (m_beta == 0)
  {
    throw std::string("ERROR: No probabilities. See if .seg-file empty.");
  }

  if (m_zero_prob_count > 0)
  {
    printf("Warning: There were %i zero probability sample(s)\n",
           m_zero_prob_count);
  }

  // Initialize the transform with identity matrix
  mtl::set(trans, 0);
  for (i = 0; i < m_dim; i++)
    trans(i,i+1) = 1;

  // calculate inverse of G
  for (i = 0; i < m_dim; i++)
  {
    copy(*(G_array[i]), G);
    lu_factor(G, pivots2);
    lu_inverse(G, pivots2, G_inv);
    copy(G_inv, *(G_array[i]));
  }

  // calculate transformation
  int row = 0;
  for (int round = 0; round < 20 * m_dim; round++)
  {
    if (row == m_dim)
      row = 0; // next iteration

    // matrix A
    detA = 1;
    for (i = 0; i < m_dim; i++)
    {
      for (j = 0; j < m_dim; j++)
	A(i, j) = trans(i, j+1);
    }

    // calculate cofactors
    transpose(A);
    lu_factor(A, pivots);
    lu_inverse(A, pivots, cofactors);

    for (i = 0; i < m_dim; i++)
      detA *= A(i, i);

    scale(cofactors, detA);

    // cofactor vector
    p[0] = 0;
    for (j = 0; j < m_dim; j++)
      p[j+1] = cofactors[row][j];

    // alpha parameter
    alpha = calculate_alpha(*(G_array[row]), p, *(k_array[row]), m_beta);

    // calculate ith row of transformation matrix
    scale(p, alpha);
    add(*(k_array[row]), p);
    transpose(*(G_array[row]));
    mult(*(G_array[row]), p, w);
    for(j = 0; j < m_dim+1; j++)
      trans(row, j) = w[j];

    transpose(*(G_array[row]));

    row++; // next row
  }

  // Accumulate the new matrix with the previous one
  d_matrix A1(m_dim, m_dim);
  d_vector b1(m_dim);
  d_matrix A2(m_dim, m_dim);
  d_vector b2(m_dim);
  const std::vector<float> *bias = mllr_mod->get_transformation_bias();
  const std::vector<float> *matrix = mllr_mod->get_transformation_matrix();

  for (i = 0; i < m_dim; i++)
  {
    b1[i] = (*bias)[i];
    b2[i] = trans(i, 0);
    for (j = 0; j < m_dim; j++)
    {
      A1(i, j) = (*matrix)[i*m_dim + j];
      A2(i, j) = trans(i, j + 1);
    }
  }

  // calculate A x + b =  A2 (A1 x + b1) + b2
  d_vector b(m_dim);
  mult(A2, A1, A);
  mult(A2, b1, b);
  add(b2, b);

  // Set the transformation
  std::vector<float> new_bias;
  std::vector<float> new_matrix;
  new_bias.resize(m_dim, 0);
  new_matrix.resize(m_dim*m_dim, 0);
  for (i = 0; i < m_dim; i++)
  {
    new_bias[i] = b[i];
    for (j = 0; j < m_dim; j++)
    {
      new_matrix[i*m_dim+j] = A(i, j);
    }
  }

  mllr_mod->set_transformation_matrix(new_matrix);
  mllr_mod->set_transformation_bias(new_bias);

  clear_stats();
}

void MllrTrainer::clear_stats()
{
  for(int i = 0; i < m_dim; i++)
  {
    mtl::set(*(k_array[i]), 0);
    mtl::set(*(G_array[i]), 0);
  }
  m_beta = 0;
  m_zero_prob_count = 0;
}

void MllrTrainer::update_stats(HmmState *state, float *probs,
                              FeatureVec &feature)
{
  typedef double d;
  int i, j; // rows, columns
  int k_index, kernelcount;
  float k_mean, k_var;

  d_matrix matrix(m_dim+1, m_dim+1);

  // extended feature vector

  d_vector fea_vector(m_dim+1); fea_vector[0] = 1;

  for(i = 1; i < m_dim+1; i++) fea_vector[i] = (double)feature[i-1];

  // k array

  kernelcount = (state->weights).size();

  for (int k = 0; k < kernelcount; k++)
  {
    k_index = (state->weights[k]).kernel;

    for (int i = 0; i < m_dim; i++)
    {
      // get kernel statistics
      k_mean = (m_model.kernel(k_index)).center[i];
      k_var = ((m_model.kernel(k_index)).cov).diag(i);

      // update k(i)
      add( scaled(fea_vector, (d)(k_mean/k_var * probs[k])), *(k_array[i]));
    }
  }

  // G array

  for (i = 0; i < m_dim+1; i++){
    for (j = 0; j < m_dim+1; j++)
      matrix[i][j] = fea_vector[i]*fea_vector[j];
  }

  for (int k = 0; k < kernelcount; k++)
  {
    k_index = (state->weights[k]).kernel;

    for(int i = 0; i < m_dim; i++)
    {
      // get kernel statistics
      k_var = ((m_model.kernel(k_index)).cov).diag(i);

      // update G(i)
      add( scaled(matrix, (d)(1/k_var * probs[k])), *(G_array[i]));
    }
  }

  for (int k = 0; k < kernelcount; k++)
    m_beta += (d)probs[k];
}

double MllrTrainer::calculate_alpha(d_matrix &Gi, d_vector &p,
				 d_vector &k, double beta)
{

  double c2 = quadratic(p, Gi, p);
  double c1 = quadratic(p, Gi, k);

  // solve quadratic equation c2 x^2 + c1 x - beta

  double a1 = (-c1 + sqrt(c1*c1 + 4*c2*beta))/(2*c2);
  double a2 = (-c1 - sqrt(c1*c1 + 4*c2*beta))/(2*c2);

  double m1 = beta*log10(fabs(a1*c2 + c1))-(c2/2)*a1*a1;
  double m2 = beta*log10(fabs(a2*c2 + c1))-(c2/2)*a2*a2;

  // select the maximizing value

  if (m1 > m2)
    return a1;

  return a2;

}

double MllrTrainer::quadratic(d_vector &x, d_matrix &A, d_vector &y)
{

  double sum = 0;

  for (int i = 0; i < (int)A.nrows(); i++)
  {
    for (int j = 0; j < (int)A.ncols(); j++)
    {
      sum += A[i][j] * x[i] * y[j];
    }
  }
  return sum;
}
<commit_msg>*** empty log message ***<commit_after>#include <math.h>

#include "str.hh"
#include "MllrTrainer.hh"

MllrTrainer::MllrTrainer(HmmSet &model, FeatureGenerator &feagen) :
  m_model(model),
  m_feagen(feagen)
{
  m_dim = m_model.dim();

  // create vector and matrix arrays
  k_array = new d_vector*[m_dim];
  G_array = new d_matrix*[m_dim];
  for (int i = 0; i < m_dim; i++)
  {
    k_array[i] = new d_vector(m_dim+1);
    G_array[i] = new d_matrix(m_dim+1, m_dim+1);
  }

  // set statistics to zero
  clear_stats();
}

MllrTrainer::~MllrTrainer()
{
  // Free allocated memory
  for (int i = 0; i < m_dim; i++)
  {
    delete k_array[i];
    delete G_array[i];
  }

  delete [] k_array;
  delete [] G_array;
}

void MllrTrainer::find_probs(HmmState *state, FeatureVec &feature)
{
  int k_index; // kernel index
  int kernelcount = (state->weights).size();
  float probs[kernelcount];
  float prob_sum = 0;

  // check dim

  if (m_dim != m_feagen.dim())
  {
    throw std::string("MllrTrainer: Model and feature dimensions disagree");
  }

  // get probabilities

  for (int k = 0; k < kernelcount; k++)
  {
    k_index = (state->weights[k]).kernel;

    if (((m_model.kernel(k_index)).cov).type() != HmmCovariance::DIAGONAL)
    {
      throw std::string("MllrTrainer: Expected diagonal covariance matrix");
    }

    probs[k] = m_model.compute_kernel_likelihood(k_index, feature);
    prob_sum = prob_sum + probs[k];

  }

  if (prob_sum != 0)
  {
    for (int k = 0; k < kernelcount; k++)
      probs[k] = probs[k]/prob_sum;
  }
  else
  {
    m_zero_prob_count++;
  }

  update_stats(state, probs, feature);
}

void MllrTrainer::calculate_transform(LinTransformModule *mllr_mod)
{
  int i, j; // rows, columns
  d_matrix A(m_dim, m_dim);
  float detA = 1;
  dense1D<int> pivots(m_dim);
  dense1D<int> pivots2(m_dim+1);
  d_matrix cofactors(m_dim, m_dim);
  d_matrix G(m_dim+1, m_dim+1);
  d_matrix G_inv(m_dim+1, m_dim+1);
  d_vector p(m_dim+1);
  d_vector w(m_dim+1);
  d_matrix trans(m_dim, m_dim+1);
  double alpha;

  // check that we have probabilities
  if (m_beta == 0)
  {
    throw std::string("ERROR: No probabilities. See if .seg-file empty.");
  }

  if (m_zero_prob_count > 0)
  {
    printf("Warning: There were %i zero probability sample(s)\n",
           m_zero_prob_count);
  }

  // Initialize the transform with identity matrix
  mtl::set(trans, 0);
  for (i = 0; i < m_dim; i++)
    trans(i,i+1) = 1;

  // calculate inverse of G
  for (i = 0; i < m_dim; i++)
  {
    copy(*(G_array[i]), G);
    lu_factor(G, pivots2);
    lu_inverse(G, pivots2, G_inv);
    copy(G_inv, *(G_array[i]));
  }

  // calculate transformation
  int row = 0;
  for (int round = 0; round < 20 * m_dim; round++)
  {
    if (row == m_dim)
      row = 0; // next iteration

    // matrix A
    detA = 1;
    for (i = 0; i < m_dim; i++)
    {
      for (j = 0; j < m_dim; j++)
	A(i, j) = trans(i, j+1);
    }

    // calculate cofactors
    transpose(A);
    lu_factor(A, pivots);
    lu_inverse(A, pivots, cofactors);

    for (i = 0; i < m_dim; i++)
      detA *= A(i, i);

    fprintf(stderr, "calculate_transform: Adet = %.4f\n", detA);

    scale(cofactors, detA);

    // cofactor vector
    p[0] = 0;
    for (j = 0; j < m_dim; j++)
      p[j+1] = cofactors[row][j];

    // alpha parameter
    alpha = calculate_alpha(*(G_array[row]), p, *(k_array[row]), m_beta);

    // calculate ith row of transformation matrix
    scale(p, alpha);
    add(*(k_array[row]), p);
    transpose(*(G_array[row]));
    mult(*(G_array[row]), p, w);
    for(j = 0; j < m_dim+1; j++)
      trans(row, j) = w[j];

    transpose(*(G_array[row]));

    row++; // next row
  }

  // Accumulate the new matrix with the previous one
  d_matrix A1(m_dim, m_dim);
  d_vector b1(m_dim);
  d_matrix A2(m_dim, m_dim);
  d_vector b2(m_dim);
  const std::vector<float> *bias = mllr_mod->get_transformation_bias();
  const std::vector<float> *matrix = mllr_mod->get_transformation_matrix();

  for (i = 0; i < m_dim; i++)
  {
    b1[i] = (*bias)[i];
    b2[i] = trans(i, 0);
    fprintf(stderr, "%.2f\n", b1[i]);
    for (j = 0; j < m_dim; j++)
    {
      A1(i, j) = (*matrix)[i*m_dim + j];
      A2(i, j) = trans(i, j + 1);
    }
  }

//   // calculate A x + b =  A2 (A1 x + b1) + b2
//   d_vector b(m_dim);
//   mult(A2, A1, A);
//   mult(A2, b1, b);
//   add(b2, b);

  // Set the transformation
  std::vector<float> new_bias;
  std::vector<float> new_matrix;
  new_bias.resize(m_dim, 0);
  new_matrix.resize(m_dim*m_dim, 0);
  for (i = 0; i < m_dim; i++)
  {
    new_bias[i] = b2[i];
    for (j = 0; j < m_dim; j++)
    {
      new_matrix[i*m_dim+j] = A2(i, j);
    }
  }

  mllr_mod->set_transformation_matrix(new_matrix);
  mllr_mod->set_transformation_bias(new_bias);

  clear_stats();
}

void MllrTrainer::clear_stats()
{
  for(int i = 0; i < m_dim; i++)
  {
    mtl::set(*(k_array[i]), 0);
    mtl::set(*(G_array[i]), 0);
  }
  m_beta = 0;
  m_zero_prob_count = 0;
}

void MllrTrainer::update_stats(HmmState *state, float *probs,
                              FeatureVec &feature)
{
  typedef double d;
  int i, j; // rows, columns
  int k_index, kernelcount;
  float k_mean, k_var;

  d_matrix matrix(m_dim+1, m_dim+1);

  // extended feature vector

  d_vector fea_vector(m_dim+1); fea_vector[0] = 1;

  for(i = 1; i < m_dim+1; i++) fea_vector[i] = (double)feature[i-1];

  // k array

  kernelcount = (state->weights).size();

  for (int k = 0; k < kernelcount; k++)
  {
    k_index = (state->weights[k]).kernel;

    for (int i = 0; i < m_dim; i++)
    {
      // get kernel statistics
      k_mean = (m_model.kernel(k_index)).center[i];
      k_var = ((m_model.kernel(k_index)).cov).diag(i);

      // update k(i)
      add( scaled(fea_vector, (d)(k_mean/k_var * probs[k])), *(k_array[i]));
    }
  }

  // G array

  for (i = 0; i < m_dim+1; i++){
    for (j = 0; j < m_dim+1; j++)
      matrix[i][j] = fea_vector[i]*fea_vector[j];
  }

  for (int k = 0; k < kernelcount; k++)
  {
    k_index = (state->weights[k]).kernel;

    for(int i = 0; i < m_dim; i++)
    {
      // get kernel statistics
      k_var = ((m_model.kernel(k_index)).cov).diag(i);

      // update G(i)
      add( scaled(matrix, (d)(1/k_var * probs[k])), *(G_array[i]));
    }
  }

  for (int k = 0; k < kernelcount; k++)
    m_beta += (d)probs[k];
}

double MllrTrainer::calculate_alpha(d_matrix &Gi, d_vector &p,
				 d_vector &k, double beta)
{

  double c2 = quadratic(p, Gi, p);
  double c1 = quadratic(p, Gi, k);

  // solve quadratic equation c2 x^2 + c1 x - beta

  double a1 = (-c1 + sqrt(c1*c1 + 4*c2*beta))/(2*c2);
  double a2 = (-c1 - sqrt(c1*c1 + 4*c2*beta))/(2*c2);

  double m1 = beta*log10(fabs(a1*c2 + c1))-(c2/2)*a1*a1;
  double m2 = beta*log10(fabs(a2*c2 + c1))-(c2/2)*a2*a2;

  // select the maximizing value

  if (m1 > m2)
    return a1;

  return a2;

}

double MllrTrainer::quadratic(d_vector &x, d_matrix &A, d_vector &y)
{

  double sum = 0;

  for (int i = 0; i < (int)A.nrows(); i++)
  {
    for (int j = 0; j < (int)A.ncols(); j++)
    {
      sum += A[i][j] * x[i] * y[j];
    }
  }
  return sum;
}
<|endoftext|>


<commit_before>#include "src/graphics.h"

#include <conio.h>
#include <math.h>
#include <memory.h>
#include <stdlib.h>

// pointer to VGA memory
static unsigned char *VGA = (unsigned char *)0xA0000;

/* ***** */
void gfx_setMode(const unsigned char mode)
{
    _asm {
        mov ah, 0x00
        mov al, mode
        int 10h
    }
}

/* ***** */
void gfx_drawPixel(int x, int y, const unsigned char color, gfx_drawBuffer *buffer)
{
    // naive "clipping"
    if(x >= buffer->width || x < 0 || y >= buffer->height || y < 0) return;

    if(!buffer)
        VGA[(y << 8) + (y << 6) + x] = color;
    else
        buffer->colorBuffer[x + y * buffer->width] = color;
}

/* ***** */
void gfx_drawPixelDepth(int x, int y, float invZ, const unsigned char color, gfx_drawBuffer *buffer)
{
    // naive "clipping"
    if(x >= buffer->width || x < 0 || y >= buffer->height || y < 0) return;

    // no depth info for VGA array, so ignore invZ
    if(!buffer)
        VGA[(y << 8) + (y << 6) + x] = color;
    else
    {
        size_t idx = x + y * buffer->width;

        // write to buffers if 1/z of the drawn pixel is larger (ie. pixel is closer to viewer)
        if(buffer->depthBuffer[idx] <= invZ)
        {
            buffer->colorBuffer[idx] = color;
            buffer->depthBuffer[idx] = invZ;
        }
    }
}

/* ***** */
void gfx_drawLine(int x0, int y0, int x1, int y1, const unsigned char color, gfx_drawBuffer *buffer)
{
    // Bresenham line drawing
    int x = x1 - x0;
    int y = y1 - y0;
    int ax = abs(x), ay = abs(y);
    int dx1 = x < 0 ? -1 : x > 0 ? 1 : 0;
    int dy1 = y < 0 ? -1 : y > 0 ? 1 : 0;
    int dx2 = dx1, dy2 = 0;
    int n, i = 0;

    if(ax <= ay)
    {
        // swap ax <=> ay
        ax ^= ay; ay ^= ax; ax ^= ay;
        dx2 = 0; dy2 = dy1;
    }

    n = ax >> 1;

    while(i++ <= ax)
    {
        gfx_drawPixel(x0, y0, color, buffer);
        n  += ay;
        x0 += n >= ax ? dx1 : dx2;
        y0 += n >= ax ? dy1 : dy2;
        n  -= n >= ax ? ax  : 0;
    }
}

/* ***** */
void gfx_drawLineVec(const mth_Vector4 *from, const mth_Vector4 *to, const unsigned char color, gfx_drawBuffer *buffer)
{
    gfx_drawLine(from->x, from->y, to->x, to->y, color, buffer);
}

/* ***** */
void gfx_clrBuffer(gfx_drawBuffer *buffer, const enum BufferType bType)
{
    if(bType & DB_COLOR)
        gfx_clrBufferColor(buffer, 0);

    // CAUTION: C-standard does not guarantee that memsetting() float array to 0 will produce desired results,
    // this is platform dependent and may not work on architecture where 0.f is not represented by all 0 bits!
    if(bType & DB_DEPTH && buffer->depthBuffer)
        memset(buffer->depthBuffer, 0, sizeof(float) * buffer->width * buffer->height);
}

/* ***** */
void gfx_clrBufferColor(gfx_drawBuffer *buffer, const unsigned char color)
{
    if(!buffer)
        memset(VGA, color, SCREEN_WIDTH * SCREEN_HEIGHT);
    else
        memset(buffer->colorBuffer, color, buffer->width * buffer->height);
}

/* ***** */
void gfx_blitBuffer(int x, int y, const gfx_drawBuffer *src, gfx_drawBuffer *target)
{
    int i;

    if(target)
    {
        for(i = 0; i < src->height; ++i)
            memcpy(&target[x + (i + y) * target->width], &src->colorBuffer[i * src->width], src->width);
    }
    else
    {
        for(i = 0; i < src->height; ++i)
            memcpy(&VGA[(y << 8) + (y << 6) + x + i * SCREEN_WIDTH], &src->colorBuffer[i * src->width], src->width);
    }
}

/* ***** */
void gfx_updateScreen(gfx_drawBuffer *buffer)
{
    memcpy(VGA, buffer->colorBuffer, SCREEN_WIDTH * SCREEN_HEIGHT);
}

/* ***** */
void gfx_setPalette(const unsigned char *palette)
{
    int i;
    outp(0x03c8, 0);

    for(i = 0; i < 256*3; ++i)
    {
        outp(0x03c9, palette[i]);
    }
}

/* ***** */
void gfx_vSync()
{
    while((inp(0x03da) & 8));
    while(!(inp(0x03da) & 8));
}
<commit_msg>fetch correct buffer width when buffer is NULL<commit_after>#include "src/graphics.h"

#include <conio.h>
#include <math.h>
#include <memory.h>
#include <stdlib.h>

// pointer to VGA memory
static unsigned char *VGA = (unsigned char *)0xA0000;

/* ***** */
void gfx_setMode(const unsigned char mode)
{
    _asm {
        mov ah, 0x00
        mov al, mode
        int 10h
    }
}

/* ***** */
void gfx_drawPixel(int x, int y, const unsigned char color, gfx_drawBuffer *buffer)
{
    int bufferW = buffer ? buffer->width : SCREEN_WIDTH;
    int bufferH = buffer ? buffer->height : SCREEN_HEIGHT;

    // naive "clipping"
    if(x >= bufferW || x < 0 || y >= bufferH || y < 0) return;

    if(!buffer)
        VGA[(y << 8) + (y << 6) + x] = color;
    else
        buffer->colorBuffer[x + y * buffer->width] = color;
}

/* ***** */
void gfx_drawPixelDepth(int x, int y, float invZ, const unsigned char color, gfx_drawBuffer *buffer)
{
    int bufferW = buffer ? buffer->width : SCREEN_WIDTH;
    int bufferH = buffer ? buffer->height : SCREEN_HEIGHT;

    // naive "clipping"
    if(x >= bufferW || x < 0 || y >= bufferH || y < 0) return;

    // no depth info for VGA array, so ignore invZ
    if(!buffer)
        VGA[(y << 8) + (y << 6) + x] = color;
    else
    {
        size_t idx = x + y * buffer->width;

        // write to buffers if 1/z of the drawn pixel is larger (ie. pixel is closer to viewer)
        if(buffer->depthBuffer[idx] <= invZ)
        {
            buffer->colorBuffer[idx] = color;
            buffer->depthBuffer[idx] = invZ;
        }
    }
}

/* ***** */
void gfx_drawLine(int x0, int y0, int x1, int y1, const unsigned char color, gfx_drawBuffer *buffer)
{
    // Bresenham line drawing
    int x = x1 - x0;
    int y = y1 - y0;
    int ax = abs(x), ay = abs(y);
    int dx1 = x < 0 ? -1 : x > 0 ? 1 : 0;
    int dy1 = y < 0 ? -1 : y > 0 ? 1 : 0;
    int dx2 = dx1, dy2 = 0;
    int n, i = 0;

    if(ax <= ay)
    {
        // swap ax <=> ay
        ax ^= ay; ay ^= ax; ax ^= ay;
        dx2 = 0; dy2 = dy1;
    }

    n = ax >> 1;

    while(i++ <= ax)
    {
        gfx_drawPixel(x0, y0, color, buffer);
        n  += ay;
        x0 += n >= ax ? dx1 : dx2;
        y0 += n >= ax ? dy1 : dy2;
        n  -= n >= ax ? ax  : 0;
    }
}

/* ***** */
void gfx_drawLineVec(const mth_Vector4 *from, const mth_Vector4 *to, const unsigned char color, gfx_drawBuffer *buffer)
{
    gfx_drawLine(from->x, from->y, to->x, to->y, color, buffer);
}

/* ***** */
void gfx_clrBuffer(gfx_drawBuffer *buffer, const enum BufferType bType)
{
    if(bType & DB_COLOR)
        gfx_clrBufferColor(buffer, 0);

    // CAUTION: C-standard does not guarantee that memsetting() float array to 0 will produce desired results,
    // this is platform dependent and may not work on architecture where 0.f is not represented by all 0 bits!
    if(bType & DB_DEPTH && buffer->depthBuffer)
        memset(buffer->depthBuffer, 0, sizeof(float) * buffer->width * buffer->height);
}

/* ***** */
void gfx_clrBufferColor(gfx_drawBuffer *buffer, const unsigned char color)
{
    if(!buffer)
        memset(VGA, color, SCREEN_WIDTH * SCREEN_HEIGHT);
    else
        memset(buffer->colorBuffer, color, buffer->width * buffer->height);
}

/* ***** */
void gfx_blitBuffer(int x, int y, const gfx_drawBuffer *src, gfx_drawBuffer *target)
{
    int i;

    if(target)
    {
        for(i = 0; i < src->height; ++i)
            memcpy(&target[x + (i + y) * target->width], &src->colorBuffer[i * src->width], src->width);
    }
    else
    {
        for(i = 0; i < src->height; ++i)
            memcpy(&VGA[(y << 8) + (y << 6) + x + i * SCREEN_WIDTH], &src->colorBuffer[i * src->width], src->width);
    }
}

/* ***** */
void gfx_updateScreen(gfx_drawBuffer *buffer)
{
    memcpy(VGA, buffer->colorBuffer, SCREEN_WIDTH * SCREEN_HEIGHT);
}

/* ***** */
void gfx_setPalette(const unsigned char *palette)
{
    int i;
    outp(0x03c8, 0);

    for(i = 0; i < 256*3; ++i)
    {
        outp(0x03c9, palette[i]);
    }
}

/* ***** */
void gfx_vSync()
{
    while((inp(0x03da) & 8));
    while(!(inp(0x03da) & 8));
}
<|endoftext|>


<commit_before>#include "SyntaxTree.h"

#include <list>
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <assert.h>

#include <boost/format.hpp>

#include "parser.tab.hh"

#include "template.common.h"
#include "template.cs.h"

using namespace std;
using namespace boost;
using namespace Krystal;

// class Node
// {
// public:
    Krystal::Node::Node(Context* _context)
    {
        context = _context;
    }

    Krystal::Node::~Node()
    {
    }

    int Krystal::Node::getType() { return 0; } //TODO: remove getType() if unnecessary
    size_t Krystal::Node::getHash(vector<Node*>* referencingStack) { return 0; }
    string* Krystal::Node::getParsed(int as) { return 0; }

// };

// class NodeKst : public Node
// {
    // list<Node*>* commands;
    // string* fileName;
    // public:
    Krystal::NodeKst::NodeKst(Context* _context, list<Node*>* _commands, string* _fileName) : Node(_context)
    {
        commands = _commands;
        fileName = _fileName;
    }

    int Krystal::NodeKst::getType()
    {
       return CsNodeType::kst;
    }

    size_t Krystal::NodeKst::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* Krystal::NodeKst::getParsed(int as)
    {
        stringstream parsed;

        parsed << format(TCS_HEADER) % *fileName;
        parsed << TCS_USINGS;

        string namespaceByFileName = fileName->substr(0, fileName->find("."));

        parsed << format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;

        list<Node*>::iterator i = commands->begin();
        list<Node*>::iterator end = commands->end();

        string* temp;

        for (; i != end; i++)
        {
            temp = (*i)->getParsed(CsParseAs::Default);
            temp = indent(temp);
            parsed << *temp;
            parsed << "\n";
        }

        parsed << TCS_NAMESPACE_END;

        parsed << "\n\n";

        return new string(parsed.str());
    }
// };

// class NodeInclude : public Node
// {
//     string* value;
//     public:
    Krystal::NodeInclude::NodeInclude(Context* _context, string* _value) : Node(_context)
    {
        value = _value;
    }

    int Krystal::NodeInclude::getType()
    {
       return CsNodeType::include;
    }

    size_t Krystal::NodeInclude::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* Krystal::NodeInclude::getParsed(int as)
    {
        stringstream parsed;

        parsed << "#include \"";
        parsed << *(value);
        parsed << "\"";

        return new string(parsed.str());
    }
// };

// class NodePacket : public Node
// {
//     string* packetName;
//     list<Node*>* packetMembers;
//     public:
    Krystal::NodePacket::NodePacket(Context* _context, string* _packetName, list<Node*>* _packetMembers) : Node(_context)
    {
        packetName = _packetName;
        packetMembers = _packetMembers;
    }

    int Krystal::NodePacket::getType()
    {
       return CsNodeType::packet;
    }

    size_t Krystal::NodePacket::getHash(vector<Node*>* referencingStack)
    {
        if (referencingStack == NULL)
        {
            referencingStack = new vector<Node*>();
        }
        else // check circular reference
        {
            vector<Node*>::iterator end = referencingStack->end();
            for (vector<Node*>::iterator i = referencingStack->begin(); i != end; i++)
            {
                if (*i == this)
                {
                    throw(runtime_error("Circular reference between packets"));
                }
            }
        }

        referencingStack->push_back(this);

        size_t packetHash = getHashCode(packetName);

        list<Node*>::iterator i = packetMembers->begin();
        list<Node*>::iterator end = packetMembers->end();
        for (; i != end; i++)
        {
            combineHashCode(packetHash, (*i)->getHash(referencingStack));
        }

        referencingStack->pop_back();

        return packetHash;
    }

    string* Krystal::NodePacket::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << format(TCS_PACKET_BEGIN) % *packetName;

                {
                    stringstream body;

                    body << format(TCS_PACKET_ID_FIELD) % ((TCS_PACKET_ID_TYPE)getHash(NULL));

                    body << TCS_PACKET_COOKIE_FIELD;

                    // Member Variables
                    list<Node*>::iterator i = packetMembers->begin();
                    list<Node*>::iterator end = packetMembers->end();
                    for (; i != end; i++)
                    {
                        body << *((*i)->getParsed(CsParseAs::Default));
                    }

                    body << format(TCS_PACKET_CONSTRUCTOR) % *packetName;

                    body << TCS_PACKET_GET_ID;

                    body << TCS_PACKET_SET_COOKIE;
                    body << TCS_PACKET_GET_COOKIE;

                    body << TCS_PACKET_GET_LENGTH_BEGIN;
                    {
                        stringstream bodyGetLengthBlock;
                        for (i = packetMembers->begin(); i != end; i++)
                        {
                            bodyGetLengthBlock << *((*i)->getParsed(CsParseAs::GetLength));
                        }

                        body << *(indent(new string(bodyGetLengthBlock.str())));
                    }
                    body << TCS_PACKET_GET_LENGTH_END;

                    parsed << *(indent(new string(body.str())));
                }

                parsed << TCS_PACKET_END;
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMember : public Node
// {
//     Node* memberType;
//     Node* memberName;
//     public:
    Krystal::NodePacketMember::NodePacketMember(Context* _context, Node* _memberType, Node* _memberName) : Node(_context)
    {
        memberType = _memberType;
        memberName = _memberName;
    }

    int Krystal::NodePacketMember::getType()
    {
       return CsNodeType::packetMember;
    }

    size_t Krystal::NodePacketMember::getHash(vector<Node*>* referencingStack)
    {
        assert(referencingStack != NULL);

        size_t packetMemberHash = memberType->getHash(referencingStack);
        combineHashCode(packetMemberHash, memberName->getHash(referencingStack));

        return packetMemberHash;
    }

    string* Krystal::NodePacketMember::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << format(TCS_PACKET_MEMBER_AS_DEFAULT)
                    % *(memberType->getParsed(CsParseAs::Default))
                    % *(memberName->getParsed(CsParseAs::Default))
                    % *(memberType->getParsed(CsParseAs::Initialization));
            }
            break;
            case CsParseAs::GetLength:
            {
                int typeType = memberType->getType();
                switch (typeType)
                {
                    case CsNodeType::packetMemberTypePrimitive:
                    {
                        string* serializerName = lookupSerializerName(memberType->getParsed(CsParseAs::Default));
                        parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_PRIMITIVE)
                            % *serializerName
                            % *(memberName->getParsed(CsParseAs::Default));
                    }
                    break;

                    case CsNodeType::packetMemberTypeReference:
                    {
                        parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_REFERENCE)
                            % *(memberName->getParsed(CsParseAs::Default));
                    }
                    break;

                    case CsNodeType::packetMemberTypeMap:
                    {
                        parsed << "<temp> length += 4;\nforeach(...map...)\n{\n}\n";
                    }
                    break;

                    case CsNodeType::packetMemberTypeList:
                    {
                        parsed << "<temp> length += 4;\nforeach(...list...)\n{\n}\n";
                    }
                    break;
                }
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberType : public Node
// {
//     int typeType; // one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST
//     string* value; // "int", "bool", ..., "MyPacket", "Skill" or NULL when type is MAP or LIST
//     Node* generic1; // LIST<generic1>
//     Node* generic2; // MAP <generic1, generic2>
//     Node* generic3; // reserved
//     public:
    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, string* _value) : Node(_context)
    {
        typeType = _type;
        value = _value;
        generic1 = NULL;
        generic2 = NULL;
        generic3 = NULL;
    }

    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1) : Node(_context)
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = NULL;
        generic3 = NULL;
    }

    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context)
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = NULL;
    }

    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context)
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = _generic3;
    }

    int Krystal::NodePacketMemberType::getType()
    {
        switch (typeType)
        {
            case Parser::token::PRIMITIVE_DATA_TYPE:
            {
                return CsNodeType::packetMemberTypePrimitive;
            }
            break;

            case Parser::token::REFERENCE_DATA_TYPE:
            {
                return CsNodeType::packetMemberTypeReference;
            }
            break;

            case Parser::token::MAP:
            {
                return CsNodeType::packetMemberTypeMap;
            }
            break;

            case Parser::token::LIST:
            {
                return CsNodeType::packetMemberTypeList;
            }
            break;
        }
        return CsNodeType::packetMemberType;
    }

    size_t Krystal::NodePacketMemberType::getHash(vector<Node*>* referencingStack)
    {
        assert(referencingStack != NULL);

        size_t packetMemberTypeHash = 0;
        switch(typeType)
        {
            case Parser::token::PRIMITIVE_DATA_TYPE:
            {
                packetMemberTypeHash = getHashCode(value);
            }
            break;

            case Parser::token::REFERENCE_DATA_TYPE:
            {
                // lookup Context::declarations table
                Node* typePacketNode = context->getDeclarationNode(value);
                if (typePacketNode == NULL)
                {
                    throw(runtime_error("No such packet type."));
                }
                packetMemberTypeHash = typePacketNode->getHash(referencingStack);
            }
            break;

            case Parser::token::MAP:
            {
                // must be specified this is map type
                // in case of other generic<t1, t2> added.
                packetMemberTypeHash = getHashCode((int)Parser::token::MAP);
                combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));
                combineHashCode(packetMemberTypeHash, generic2->getHash(referencingStack));
            }
            break;

            case Parser::token::LIST:
            {
                // must be specified this is list type
                // in case of other generic<t> added.
                packetMemberTypeHash = getHashCode((int)Parser::token::LIST);
                combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));
            }
            break;
        }

        return packetMemberTypeHash;
    }

    string* Krystal::NodePacketMemberType::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                switch (typeType)
                {
                    case Parser::token::PRIMITIVE_DATA_TYPE:
                    case Parser::token::REFERENCE_DATA_TYPE:
                    {
                        parsed << *value;
                    }
                    break;

                    case Parser::token::MAP:
                    {
                        parsed << format(TCS_PACKET_MEMBER_TYPE_MAP_AS_DEFAULT)
                            % *(generic1->getParsed(CsParseAs::Default))
                            % *(generic2->getParsed(CsParseAs::Default));
                    }
                    break;

                    case Parser::token::LIST:
                    {
                        parsed << format(TCS_PACKET_MEMBER_TYPE_LIST_AS_DEFAULT)
                            % *(generic1->getParsed(CsParseAs::Default));
                    }
                    break;

                    default:
                    {
                        throw(runtime_error("Unknown NodePacketMemberType type."));
                    }
                    break;
                }
            }
            break;

            case CsParseAs::Initialization:
            {
                switch (typeType)
                {
                    case Parser::token::PRIMITIVE_DATA_TYPE:
                    {
                        parsed << "";
                    }
                    break;

                    case Parser::token::REFERENCE_DATA_TYPE:
                    case Parser::token::MAP:
                    case Parser::token::LIST:
                    {
                        parsed << format(TCS_PACKET_MEMBER_TYPE_NEW_AS_INITIALIZATION)
                            % *(getParsed(CsParseAs::Default));
                    }
                    break;

                    default:
                    {
                        throw(runtime_error("Unknown NodePacketMemberType type."));
                    }
                    break;
                }
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberName : public Node
// {
//     string* value;
//     public:
    Krystal::NodePacketMemberName::NodePacketMemberName(Context* _context, string* _value) : Node(_context)
    {
        value = _value;
    }

    int Krystal::NodePacketMemberName::getType()
    {
       return CsNodeType::packetMemberName;
    }

    size_t Krystal::NodePacketMemberName::getHash(vector<Node*>* referencingStack)
    {
        size_t packetMemberNameHash = getHashCode(value);
        return packetMemberNameHash;
    }

    string* Krystal::NodePacketMemberName::getParsed(int as)
    {
       return value;
    }
// };

<commit_msg>add routine for NodePacketMemberType::getParsed() to print itself as Generics or SerializerName<commit_after>#include "SyntaxTree.h"

#include <list>
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <assert.h>

#include <boost/format.hpp>

#include "parser.tab.hh"

#include "template.common.h"
#include "template.cs.h"

using namespace std;
using namespace boost;
using namespace Krystal;

// class Node
// {
// public:
    Krystal::Node::Node(Context* _context)
    {
        context = _context;
    }

    Krystal::Node::~Node()
    {
    }

    int Krystal::Node::getType() { return 0; } //TODO: remove getType() if unnecessary
    size_t Krystal::Node::getHash(vector<Node*>* referencingStack) { return 0; }
    string* Krystal::Node::getParsed(int as) { return 0; }

// };

// class NodeKst : public Node
// {
    // list<Node*>* commands;
    // string* fileName;
    // public:
    Krystal::NodeKst::NodeKst(Context* _context, list<Node*>* _commands, string* _fileName) : Node(_context)
    {
        commands = _commands;
        fileName = _fileName;
    }

    int Krystal::NodeKst::getType()
    {
       return CsNodeType::kst;
    }

    size_t Krystal::NodeKst::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* Krystal::NodeKst::getParsed(int as)
    {
        stringstream parsed;

        parsed << format(TCS_HEADER) % *fileName;
        parsed << TCS_USINGS;

        string namespaceByFileName = fileName->substr(0, fileName->find("."));

        parsed << format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;

        list<Node*>::iterator i = commands->begin();
        list<Node*>::iterator end = commands->end();

        string* temp;

        for (; i != end; i++)
        {
            temp = (*i)->getParsed(CsParseAs::Default);
            temp = indent(temp);
            parsed << *temp;
            parsed << "\n";
        }

        parsed << TCS_NAMESPACE_END;

        parsed << "\n\n";

        return new string(parsed.str());
    }
// };

// class NodeInclude : public Node
// {
//     string* value;
//     public:
    Krystal::NodeInclude::NodeInclude(Context* _context, string* _value) : Node(_context)
    {
        value = _value;
    }

    int Krystal::NodeInclude::getType()
    {
       return CsNodeType::include;
    }

    size_t Krystal::NodeInclude::getHash(vector<Node*>* referencingStack)
    {
        return 0;
    }

    string* Krystal::NodeInclude::getParsed(int as)
    {
        stringstream parsed;

        parsed << "#include \"";
        parsed << *(value);
        parsed << "\"";

        return new string(parsed.str());
    }
// };

// class NodePacket : public Node
// {
//     string* packetName;
//     list<Node*>* packetMembers;
//     public:
    Krystal::NodePacket::NodePacket(Context* _context, string* _packetName, list<Node*>* _packetMembers) : Node(_context)
    {
        packetName = _packetName;
        packetMembers = _packetMembers;
    }

    int Krystal::NodePacket::getType()
    {
       return CsNodeType::packet;
    }

    size_t Krystal::NodePacket::getHash(vector<Node*>* referencingStack)
    {
        if (referencingStack == NULL)
        {
            referencingStack = new vector<Node*>();
        }
        else // check circular reference
        {
            vector<Node*>::iterator end = referencingStack->end();
            for (vector<Node*>::iterator i = referencingStack->begin(); i != end; i++)
            {
                if (*i == this)
                {
                    throw(runtime_error("Circular reference between packets"));
                }
            }
        }

        referencingStack->push_back(this);

        size_t packetHash = getHashCode(packetName);

        list<Node*>::iterator i = packetMembers->begin();
        list<Node*>::iterator end = packetMembers->end();
        for (; i != end; i++)
        {
            combineHashCode(packetHash, (*i)->getHash(referencingStack));
        }

        referencingStack->pop_back();

        return packetHash;
    }

    string* Krystal::NodePacket::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << format(TCS_PACKET_BEGIN) % *packetName;

                {
                    stringstream body;

                    body << format(TCS_PACKET_ID_FIELD) % ((TCS_PACKET_ID_TYPE)getHash(NULL));

                    body << TCS_PACKET_COOKIE_FIELD;

                    // Member Variables
                    list<Node*>::iterator i = packetMembers->begin();
                    list<Node*>::iterator end = packetMembers->end();
                    for (; i != end; i++)
                    {
                        body << *((*i)->getParsed(CsParseAs::Default));
                    }

                    body << format(TCS_PACKET_CONSTRUCTOR) % *packetName;

                    body << TCS_PACKET_GET_ID;

                    body << TCS_PACKET_SET_COOKIE;
                    body << TCS_PACKET_GET_COOKIE;

                    body << TCS_PACKET_GET_LENGTH_BEGIN;
                    {
                        stringstream bodyGetLengthBlock;
                        for (i = packetMembers->begin(); i != end; i++)
                        {
                            bodyGetLengthBlock << *((*i)->getParsed(CsParseAs::GetLength));
                        }

                        body << *(indent(new string(bodyGetLengthBlock.str())));
                    }
                    body << TCS_PACKET_GET_LENGTH_END;

                    parsed << *(indent(new string(body.str())));
                }

                parsed << TCS_PACKET_END;
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMember : public Node
// {
//     Node* memberType;
//     Node* memberName;
//     public:
    Krystal::NodePacketMember::NodePacketMember(Context* _context, Node* _memberType, Node* _memberName) : Node(_context)
    {
        memberType = _memberType;
        memberName = _memberName;
    }

    int Krystal::NodePacketMember::getType()
    {
       return CsNodeType::packetMember;
    }

    size_t Krystal::NodePacketMember::getHash(vector<Node*>* referencingStack)
    {
        assert(referencingStack != NULL);

        size_t packetMemberHash = memberType->getHash(referencingStack);
        combineHashCode(packetMemberHash, memberName->getHash(referencingStack));

        return packetMemberHash;
    }

    string* Krystal::NodePacketMember::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                parsed << format(TCS_PACKET_MEMBER_AS_DEFAULT)
                    % *(memberType->getParsed(CsParseAs::Default))
                    % *(memberName->getParsed(CsParseAs::Default))
                    % *(memberType->getParsed(CsParseAs::Initialization));
            }
            break;
            case CsParseAs::GetLength:
            {
                int typeType = memberType->getType();
                switch (typeType)
                {
                    case CsNodeType::packetMemberTypePrimitive:
                    {
                        string* serializerName = lookupSerializerName(memberType->getParsed(CsParseAs::Default));
                        parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_PRIMITIVE)
                            % *serializerName
                            % *(memberName->getParsed(CsParseAs::Default));
                    }
                    break;

                    case CsNodeType::packetMemberTypeReference:
                    {
                        parsed << format(TCS_PACKET_MEMBER_AS_GET_LENGTH_REFERENCE)
                            % *(memberName->getParsed(CsParseAs::Default));
                    }
                    break;

                    case CsNodeType::packetMemberTypeMap:
                    {
                        parsed << "<temp> length += 4;\nforeach(...map...)\n{\n}\n";
                    }
                    break;

                    case CsNodeType::packetMemberTypeList:
                    {
                        parsed << "<temp> length += 4;\nforeach(...list...)\n{\n}\n";
                    }
                    break;
                }
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberType : public Node
// {
//     int typeType; // one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST
//     string* value; // "int", "bool", ..., "MyPacket", "Skill" or NULL when type is MAP or LIST
//     Node* generic1; // LIST<generic1>
//     Node* generic2; // MAP <generic1, generic2>
//     Node* generic3; // reserved
//     public:
    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, string* _value) : Node(_context)
    {
        typeType = _type;
        value = _value;
        generic1 = NULL;
        generic2 = NULL;
        generic3 = NULL;
    }

    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1) : Node(_context)
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = NULL;
        generic3 = NULL;
    }

    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context)
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = NULL;
    }

    Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context)
    {
        typeType = _type;
        value = NULL;
        generic1 = _generic1;
        generic2 = _generic2;
        generic3 = _generic3;
    }

    int Krystal::NodePacketMemberType::getType()
    {
        switch (typeType)
        {
            case Parser::token::PRIMITIVE_DATA_TYPE:
            {
                return CsNodeType::packetMemberTypePrimitive;
            }
            break;

            case Parser::token::REFERENCE_DATA_TYPE:
            {
                return CsNodeType::packetMemberTypeReference;
            }
            break;

            case Parser::token::MAP:
            {
                return CsNodeType::packetMemberTypeMap;
            }
            break;

            case Parser::token::LIST:
            {
                return CsNodeType::packetMemberTypeList;
            }
            break;
        }
        return CsNodeType::packetMemberType;
    }

    size_t Krystal::NodePacketMemberType::getHash(vector<Node*>* referencingStack)
    {
        assert(referencingStack != NULL);

        size_t packetMemberTypeHash = 0;
        switch(typeType)
        {
            case Parser::token::PRIMITIVE_DATA_TYPE:
            {
                packetMemberTypeHash = getHashCode(value);
            }
            break;

            case Parser::token::REFERENCE_DATA_TYPE:
            {
                // lookup Context::declarations table
                Node* typePacketNode = context->getDeclarationNode(value);
                if (typePacketNode == NULL)
                {
                    throw(runtime_error("No such packet type."));
                }
                packetMemberTypeHash = typePacketNode->getHash(referencingStack);
            }
            break;

            case Parser::token::MAP:
            {
                // must be specified this is map type
                // in case of other generic<t1, t2> added.
                packetMemberTypeHash = getHashCode((int)Parser::token::MAP);
                combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));
                combineHashCode(packetMemberTypeHash, generic2->getHash(referencingStack));
            }
            break;

            case Parser::token::LIST:
            {
                // must be specified this is list type
                // in case of other generic<t> added.
                packetMemberTypeHash = getHashCode((int)Parser::token::LIST);
                combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));
            }
            break;
        }

        return packetMemberTypeHash;
    }

    string* Krystal::NodePacketMemberType::getParsed(int as)
    {
        stringstream parsed;

        switch (as)
        {
            case CsParseAs::Default:
            {
                switch (typeType)
                {
                    case Parser::token::PRIMITIVE_DATA_TYPE:
                    case Parser::token::REFERENCE_DATA_TYPE:
                    {
                        parsed << *value;
                    }
                    break;

                    case Parser::token::MAP:
                    {
                        parsed << format(TCS_PACKET_MEMBER_TYPE_MAP_AS_DEFAULT)
                            % *(generic1->getParsed(CsParseAs::Default))
                            % *(generic2->getParsed(CsParseAs::Default));
                    }
                    break;

                    case Parser::token::LIST:
                    {
                        parsed << format(TCS_PACKET_MEMBER_TYPE_LIST_AS_DEFAULT)
                            % *(generic1->getParsed(CsParseAs::Default));
                    }
                    break;

                    default:
                    {
                        throw(runtime_error("Unknown NodePacketMemberType type."));
                    }
                    break;
                }
            }
            break;

            case CsParseAs::GenericType1:
            {
                parsed << *(generic1->getParsed(CsParseAs::Default));
            }
            break;

            case CsParseAs::GenericType2:
            {
                parsed << *(generic2->getParsed(CsParseAs::Default));
            }
            break;

            case CsParseAs::GenericType3:
            {
                parsed << *(generic3->getParsed(CsParseAs::Default));
            }
            break;

            case CsParseAs::GenericTypeSerializer1:
            {
                parsed << *(generic1->getParsed(CsParseAs::SerializerName));
            }
            break;

            case CsParseAs::GenericTypeSerializer2:
            {
                parsed << *(generic2->getParsed(CsParseAs::SerializerName));
            }
            break;

            case CsParseAs::GenericTypeSerializer3:
            {
                parsed << *(generic3->getParsed(CsParseAs::SerializerName));
            }
            break;

            case CsParseAs::SerializerName:
            {
                switch (typeType)
                {
                    case Parser::token::PRIMITIVE_DATA_TYPE:
                    {
                        string* serializerName = lookupSerializerName(value);
                        parsed << *serializerName;
                    }
                    break;

                    case Parser::token::REFERENCE_DATA_TYPE:
                    {
                        parsed << TCS_PACKET_CUSTOM_SERIALIZER_NAME;
                    }
                    break;

                    default:
                    {
                        throw(runtime_error("Serializer not supported for nested generic type"));
                    }
                    break;
                }
            }
            break;

            case CsParseAs::Initialization:
            {
                switch (typeType)
                {
                    case Parser::token::PRIMITIVE_DATA_TYPE:
                    {
                        parsed << "";
                    }
                    break;

                    case Parser::token::REFERENCE_DATA_TYPE:
                    case Parser::token::MAP:
                    case Parser::token::LIST:
                    {
                        parsed << format(TCS_PACKET_MEMBER_TYPE_NEW_AS_INITIALIZATION)
                            % *(getParsed(CsParseAs::Default));
                    }
                    break;

                    default:
                    {
                        throw(runtime_error("Unknown NodePacketMemberType type."));
                    }
                    break;
                }
            }
            break;
        }

        return new string(parsed.str());
    }
// };

// class NodePacketMemberName : public Node
// {
//     string* value;
//     public:
    Krystal::NodePacketMemberName::NodePacketMemberName(Context* _context, string* _value) : Node(_context)
    {
        value = _value;
    }

    int Krystal::NodePacketMemberName::getType()
    {
       return CsNodeType::packetMemberName;
    }

    size_t Krystal::NodePacketMemberName::getHash(vector<Node*>* referencingStack)
    {
        size_t packetMemberNameHash = getHashCode(value);
        return packetMemberNameHash;
    }

    string* Krystal::NodePacketMemberName::getParsed(int as)
    {
       return value;
    }
// };

<|endoftext|>