int main(int argc, char *argv[]){ if(argc!=3){ printf("Usage: ./project1 infile outfile\n"); return 0; } /* double vals[] = {10,8,3}; int dim = 3; DataPoint* dp = new DataPoint(true,dim,vals); dp->print(); DataPoint dp2 = *dp; DataPoint dp3; dp3 = *dp; dp->features[2] = 10; dp->print(); dp2.print(); dp3.print(); double newVals[] = {11,12,13}; //dp->addValue(3, newVals); dp->print(); cout << "**************************" << endl; */ DecisionTree* dt = new DecisionTree(); dt->importData(argv[1]); print(dt); dt->runDecisionTreeAlgorithm(argv[2]); return 0; }
DecisionTree* ETHNOPREDTree::CreateEPTree(string treeStructure){ //example of tree structure string //Yes or No branch Yes_rs7573555_rs7561423_Q_6 //Create branch reate_rs7570971_Q_1.5 string wordDelimiter(","); string lineDelimiter("\n"); string treeNodeBreak("_"); string treeWordInfo; vector<string> treeNodeInfo; DecisionTree* newTree = new DecisionTree(); auto treeWordPos = treeStructure.find(wordDelimiter); while(treeWordPos != std::string::npos){ auto treeWordInfo = treeStructure.substr(0, treeWordPos + wordDelimiter.length()); auto treeNodePos = treeWordInfo.find(treeNodeBreak); treeNodeInfo.push_back(treeWordInfo.substr(0, treeNodePos)); //Yes_rs7573555_rs7561423_Q_6 forward 4 times based on '-' //Create_rs7570971_Q_1.5 is still find, even if it is shorter for ( auto i = 0; i < 4 ; ++i){ treeWordInfo.erase(0, treeNodePos + treeNodeBreak.length()); treeNodePos = treeWordInfo.find(treeNodeBreak); treeNodeInfo.push_back(treeWordInfo.substr(0, treeNodePos)); } auto nodeType = treeNodeInfo[0]; if(nodeType == "Create"){ auto branchSNIP = treeNodeInfo[1]; auto weight = stof(treeNodeInfo[3]); newTree->CreateRootNode(branchSNIP, treeNodeInfo[2], weight); treeNodeInfo.clear(); } else { auto nodeLeftSNIP= treeNodeInfo[1]; auto nodeRightSNIP= treeNodeInfo[2]; auto weight = stof(treeNodeInfo[4]); if (nodeType == "Yes"){ newTree->AddYesNode(nodeLeftSNIP, nodeRightSNIP, treeNodeInfo[3], weight); treeNodeInfo.clear(); } if (nodeType == "No"){ double weight = stof(treeNodeInfo[4]); newTree->AddNoNode(nodeLeftSNIP, nodeRightSNIP, treeNodeInfo[3], weight); treeNodeInfo.clear(); } } treeStructure.erase(0, treeWordPos + wordDelimiter.length()); treeWordPos = treeStructure.find(wordDelimiter); } return newTree; }
void BoostedClassifier::train(const vector<TrainingExample*>& examples) { if(examples.size()==0) return; assert(m_trees.size()==0); size_t m = examples.size(); vector<double> distribs(m,1.0/m); m_sum_alphas = 0; for(size_t b=0; b<m_num_max_trees; b++) { DecisionTree* hb = new DecisionTree(m_label); hb->train(examples, distribs); double epsb = 0; size_t num_misclassified=0; for(size_t i=0; i<m; i++) { double predictprob= hb->predict(*examples[i]); bool prediction = (predictprob>0.5)?true:false; // cerr << "Actual label: " << egs_for_tree[i]->getLabel() << endl; // cerr << ", Predicted: " << m_label << " with prob " << predictprob << endl; bool actual = isLabelEqual(examples[i]->getLabel(), m_label); if(prediction!=actual) { epsb+=distribs[i]; num_misclassified++; } } // cerr << "Number misclassified: " << num_misclassified << " of " << m << ", my label: " << m_label << endl; // cerr << "\tEpsb: " << epsb << endl; double epsilon = 0.001; if(epsb==0) { epsb=epsilon; } else if(epsb==1.0) { epsb=1-epsilon; } double alphab = 0.5*log((1-epsb)/epsb)/log(2.0); double z = 0.0; for(size_t i=0; i<m; i++) { double predictprob= hb->predict(*examples[i]); // cerr << "My tree label: " << m_label << ", actual label: " << egs_for_tree[i]->getLabel()<< ", prediction probability: " << predictprob << endl; bool prediction = (predictprob>0.5)?true:false; bool actual = isLabelEqual(examples[i]->getLabel(),m_label); if(prediction!=actual) { // if incorrect drum up... distribs[i] = distribs[i]*exp(alphab); } else { // if correct drum down... distribs[i] = distribs[i]*exp(-alphab); } z +=distribs[i]; } // cerr << "z: " << z << endl; for(size_t i=0; i<m; i++) { distribs[i] = distribs[i]/z; } m_trees.push_back(hb); m_tree_alpha.push_back(alphab); m_sum_alphas += alphab; // cerr << "Trained tree with alphab: " << alphab <<endl; } // for each tree }
Move *Player::doMove(Move *opponentsMove) { board->doMove(opponentsMove, otherSide); if (!board->hasMoves(side)) { return NULL; } DecisionTree *tree = new DecisionTree(board, side); Move *moveToMake = tree->findBestMove(DEPTH); board->doMove(moveToMake, side); return moveToMake; }
int GradientBoostingForest::Fit(InstancePool * pInstancepool) { m_pInstancePool = pInstancepool; m_pInstancePool->MakeBucket(); if(NULL == m_pInstancePool) { Comm::LogErr("GradientBoostingForest::Fit pInstancepool is NULL"); return -1; } int ret = -1; for(int i=0;i<m_pconfig->TreeNum;i++) { DecisionTree * pTree = new DecisionTree(m_pconfig); ret = pTree->Fit(m_pInstancePool); // printf("i = %d Fited pTree->FitError = %f\n",i,pTree->FitError()); if(ret != 0) { Comm::LogErr("GradientBoostingForest::Fit fail! tree i = %d Fit fail!",i); return -1; } m_Forest.push_back(pTree); if(m_pconfig->LogLevel >= 2)printf("i = %d FitError = %f TestError = %f\n",i,FitError(),TestError()); ret = Residual(); printf("i = %d Residualed\n",i); if(ret != 0) { Comm::LogErr("GradientBoostingForest::Fit fail! Residual fail!"); return -1; } } if(m_pconfig->IsLearnNewInstances) { ret = LearnNewInstance(); if(ret != 0) { Comm::LogErr("GradientBoostingForest::Fit fail! LearnNewInstance fail!"); return -1; } } ret = SaveResult(); if(ret != 0) { Comm::LogErr("GradientBoostingForest::Fit fail ! SaveResult fail!"); return -1; } if(m_pconfig->LogLevel >= 2)FeatureStat(); return 0; }
void DecisionTree<T>::prune( const DataSet<T>& trainingData, const DataSet<T>& validationData, unsigned int target, unsigned int numTrees, unsigned int K ) { if ( m_root == NULL || isLeaf( m_root ) ) { return; } else { DecisionTree<T> bestTree; bestTree = *this; // Build different candidate trees. for ( unsigned int i = 1; i < numTrees; i++ ) { DecisionTree<T> candidateTree; candidateTree = *this; srand( time(NULL)); unsigned int M = rand() % K + 1; if ( M > candidateTree.m_size ) { M = candidateTree.m_size; } // Prune candidate tree M times. for ( unsigned int j = 1; j < M; j++ ) { chooseAndPrune( candidateTree, candidateTree.m_root, trainingData, target, 0 ); } // See if pruned tree is more accurate. float candidateAccuracy = candidateTree.test( validationData, target ); float bestAccuracy = bestTree.test( validationData, target ); if ( candidateAccuracy > bestAccuracy ) { bestTree = candidateTree; } } // This tree is the best tree found via pruning. *this = bestTree; } }
void BoostedDecisionTree::boostWeights(DataSet *ds) { DecisionTree *tree = trees[trees.size() - 1]; double boostFactor = exp(tree->alpha()); for (unsigned int i = 0; i < ds->size(); i++) { if (!tree->check((*ds)[i])){ (*ds)[i].weight *= boostFactor; } } }
int main(int argc, char* argv[]){ string filename = "source.txt"; DecisionTree dt ; int attr_node = 0; TreeNode* treeHead = nullptr; set<int> readLineNum; vector<int> readClumNum; int deep = 0; if (dt.pretreatment(filename, readLineNum, readClumNum) == 0) { dt.CreatTree(treeHead, dt.getStatTree(), dt.getInfos(), readLineNum, readClumNum, deep); } getchar(); return 0; }
void createPointCloud() { for(int i = -25; i <= 25; i++) { for(int j = -25; j <= 25; j++) { ColorPoint p(i/25.0,j/25.0); p.color = myTree.evaluatePoint(p); glBegin(GL_POINTS); switch(p.color) { case RED: glColor4f(1.0f,0.0f,0.0f,0.2f); break; case BLUE: glColor4f(0.0f,0.0f,1.0f,0.2f); break; case GREEN: glColor4f(0.0f,1.0f,0.0f,0.2f); break; default: glColor4f(0.0f,0.0f,0.0f,0.2f); break; } glVertex3f(p.x,p.y,0.0f); glEnd(); glFlush(); glutSwapBuffers(); } } }
void RetManager::retrieval(unsigned retNum) { retDocID = new unsigned[retNum]; retDocScore = new float[retNum]; topDocs = new MinHeap(retNum); DecisionTree *DT = new DecisionTree(r,num,retNum); while((curDoc = findNextDoc())!=MaxNum) { DT->putDoc(curDoc,r); //float score = grade(); //if(score > topDocs->smallest) topDocs->push(curDoc,score); } int i,l,n; const float okapiK1=1.2; const float okapiB=0.2; DecisionTreeNode **blockList = DT->getBlockList(); vector<pair<unsigned,unsigned*> >::iterator it; for(i=0;i<DT->getBlockNum();i++) { n=blockList[i]->termScores.size(); for(it=blockList[i]->content->record.begin();it!=blockList[i]->content->record.end();it++) { unsigned* theTF=it->second; float score=0; float docLength = theIndex -> getDocLength(it->first); for(l=0;l<n;l++) { float tf = theTF[l]; float weight = ((okapiK1+1.0)*tf) / (okapiK1*(1.0-okapiB+okapiB*docLength/theIndex->docLengthAvg)+tf); score+=weight*blockList[i]->termScores[l]; } if(score > topDocs->smallest) topDocs->push(it->first,score); evalCounter++; } } retN = topDocs->n; for(i=retN-1;i>=0;i--) { retDocID[i] = topDocs->pop(retDocScore[i]); } delete(topDocs); delete(DT); }
void RandForest::Train() { LOG(INFO) <<"Client " << client_id_<< " Thread " << thread_id_ << ": Random Forest begin training."; for (int i = 0; i < num_trees_; ++i) { // Build each tree. DecisionTree* tree = new DecisionTree(); tree->Init(tree_config_); trees_.push_back(tree); if (save_trees_) { serial_trees_.push_back(trees_[i]->GetSerializedTree()); } if ((client_id_ == 0) && (thread_id_ == 0)) { LOG(INFO) << "Each thread trained " << i + 1 << "/" << num_trees_ << " trees."; } } }
bool RandomForests::train(LabelledClassificationData trainingData){ //Clear any previous model clear(); const unsigned int M = trainingData.getNumSamples(); const unsigned int N = trainingData.getNumDimensions(); const unsigned int K = trainingData.getNumClasses(); if( M == 0 ){ errorLog << "train(LabelledClassificationData labelledTrainingData) - Training data has zero samples!" << endl; return false; } numInputDimensions = N; numClasses = K; classLabels = trainingData.getClassLabels(); ranges = trainingData.getRanges(); //Scale the training data if needed if( useScaling ){ //Scale the training data between 0 and 1 trainingData.scale(0, 1); } //Train the random forest forestSize = 10; Random random; DecisionTree tree; tree.enableScaling( false ); //We have already scaled the training data so we do not need to scale it again tree.setTrainingMode( DecisionTree::BEST_RANDOM_SPLIT ); tree.setNumSplittingSteps( numRandomSplits ); tree.setMinNumSamplesPerNode( minNumSamplesPerNode ); tree.setMaxDepth( maxDepth ); for(UINT i=0; i<forestSize; i++){ LabelledClassificationData data = trainingData.getBootstrappedDataset(); if( !tree.train( data ) ){ errorLog << "train(LabelledClassificationData labelledTrainingData) - Failed to train tree at forest index: " << i << endl; return false; } //Deep copy the tree into the forest forest.push_back( tree.deepCopyTree() ); } //Flag that the algorithm has been trained trained = true; return trained; }
int GradientBoostingForest::LoadModel() { FILE * fp; fp = fopen(m_pconfig->InputModelFilePath.c_str(),"r"); if(!fp) { Comm::LogErr("GradientBoostingForest::LoadModel fp is NULL"); return -1; } int ret; int treeNum; ret = fscanf(fp,"%d %d",&treeNum,&m_TotLeafCnt); if(ret < 0) { Comm::LogErr("GradientBoostingForest::LoadModel fail! fscanf treeNum fail!"); fclose(fp); return -1; } for(int i=0;i<m_Forest.size();i++) { m_Forest[i] = Comm::Delete(m_Forest[i]); } m_Forest.clear(); for(int i=0;i<treeNum;i++) { DecisionTree * pTree = new DecisionTree(m_pconfig); ret = pTree->LoadModel(fp); if(ret != 0) { Comm::LogErr("GradientBoostingForest::LoadModel fail! Tree %d LoadModel",i); fclose(fp); return -1; } m_Forest.push_back(pTree); } fclose(fp); printf("GradientBoostingForest::LoadModel treeNum = %d m_TotLeafCnt = %d\n",treeNum, m_TotLeafCnt); return 0; }
void mouseClick(int button, int state, int x, int y) { if(state == GLUT_UP) { ColorPoint point; point.x = map(x,0,winx,-1000,1000)/1000.0; point.y = map(y,0,winy,1000,-1000)/1000.0; cout << "x = " << point.x << endl; cout << "y = " << point.y << endl; glBegin(GL_POINTS); glColor3f(0.0f,0.0f,0.0f); glVertex3f(point.x,point.y,0.0f); glEnd(); glFlush(); glutSwapBuffers(); //usleep(500000); //cout << "Aqui 1" << endl; Color color = myTree.evaluatePoint(point); //cout << "Aqui SAIDA" << endl << endl; glBegin(GL_POINTS); switch(color) { case RED: glColor3f(1.0f,0.0f,0.0f); break; case BLUE: glColor3f(0.0f,0.0f,1.0f); break; case GREEN: glColor3f(0.0f,1.0f,0.0f); break; default: glColor3f(0.0f,0.0f,0.0f); break; } glVertex3f(point.x,point.y,0.0f); glEnd(); glFlush(); glutSwapBuffers(); } //display(); }
//===================================================================// //==================Main Method=====================================// //==================================================================// int main() { //===================================================================// //==================Things you need to start with====================// //==================================================================// glfwInit(); Window testWindow(500, 50, 800, 600, "testWindow"); glfwMakeContextCurrent(testWindow.getWindow()); cam.setCenter(glm::vec4(0.0, 10.0, 20.0, 1.0)); cam.setName("StrategyCam"); cam.setKeySpeed(2.0); cam.setNearFar(0.0001, 100); glfwSetKeyCallback(testWindow.getWindow(), key_callback); glfwSetScrollCallback(testWindow.getWindow(), mouseScroll_callback); glewInit(); OpenGL3Context context; Renderer renderer(context); //===================================================================// //==================Shaders for your program========================// //==================================================================// VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/TextureShader3D/TextureShader3D.vert"))); FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/TextureShader3D/TextureShader3D.frag"))); ShaderProgram shader(vs, fs); //===================================================================// //==================A Graph for the AI-Unit=========================// //==================================================================// glm::vec3 posFood(10.0, 0.0, -5.0); glm::vec3 posSpawn(10.0, 0.0, 60.0); Graph<AStarNode, AStarAlgorithm> testGraph; // testGraph.setExampleGraph2(posSpawn, posFood, geko.getPosition()); //===================================================================// //==================A Decision-Tree for the AI-Unit==================// //==================================================================// DecisionTree defaultTree; defaultTree.setAntTreeAggressiv(); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: AI==============================// Teapot teaAnt; Texture texPlayer((char*)RESOURCES_PATH "/Snake.jpg"); SoundFileHandler sfh = SoundFileHandler(1000); //AStarNode defaultASNode("Default"); //AI ant_Flick(&defaultTree, &defaultASNode, &aiNode); AI ant_Flick; //ant_Flick.setAntAfraid(); /*ant_Flick.setGraph(&testGraph); ant_Flick.setPosition(posSpawn); ant_Flick.setPosHome(testGraph.searchNode("Spawn"));*/ //ant_Flick.addFoodNodes(testGraph.searchNode("Food")); AntMesh ant; Node aiNode("Flick"); aiNode.addGeometry(&ant); aiNode.addTexture(&texPlayer); // aiNode.addScale(0.3, 0.3, 0.3); //aiNode.addTranslation(ant_Flick.getPosition().x, ant_Flick.getPosition().y, ant_Flick.getPosition().z); aiNode.setObject(&ant_Flick); //aiNode.setSoundHandler(&sfh); // aiNode.setSourceName("Ameise1", RESOURCES_PATH "/Sound/Footsteps.wav"); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Player===========================// Teapot teaPlayer; Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp"); GekoMesh gekoMesh; geko.setExp(0.0); geko.setLevelThreshold(100.0); geko.setLevel(0); Node playerNode("Player"); playerNode.addGeometry(&gekoMesh); playerNode.setObject(&geko); playerNode.addTexture(&texCV); // playerNode.addScale(0.5, 0.5, 0.5); // playerNode.addTranslation(20.0, 0.0, 20.0); geko.setSoundHandler(&sfh); geko.setSourceName(MOVESOUND, "SpielerFootsteps", RESOURCES_PATH "/Sound/rascheln.wav"); geko.setSourceName(BACKGROUNDMUSIC, "Hintergrund", RESOURCES_PATH "/Sound/jingle2.wav"); geko.setSourceName(FIGHTSOUND, "Kampfsound", RESOURCES_PATH "/Sound/Cookies kurz.wav"); geko.setSourceName(EATSOUND, "Essen", RESOURCES_PATH "/Sound/Munching.wav"); geko.setSourceName(QUESTSOUND, "Quest", RESOURCES_PATH "/Sound/jingle.wav"); geko.setSourceName(ITEMSOUND, "Item", RESOURCES_PATH "/Sound/itempickup.wav"); sfh.disableLooping("Essen"); sfh.disableLooping("Kampfsound"); sfh.disableLooping("Quest"); sfh.disableLooping("Item"); sfh.generateSource("Feuer",posFood, RESOURCES_PATH "/Sound/Feuer kurz.wav"); playerNode.setCamera(&cam); // ============================================================== // == Items ===================================================== // ============================================================== /*Item cookie(1); cookie.setName("Cookie"); cookie.setTypeId(ItemType::COOKIE); Item cookie2(2); cookie.setName("Cookie"); cookie.setTypeId(ItemType::COOKIE); Item branch(3); branch.setName("Branch"); branch.setTypeId(ItemType::BRANCH); */ //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Tree===========================// TreeMesh tree; glm::vec3 trees[5] = { glm::vec3(16.0, 0.0, 76.0), glm::vec3(23.0, 0.0, 74.0), glm::vec3(21.5, 0.0, 78.5), glm::vec3(15.0, 0.0, 81.5), glm::vec3(27.5, 0.0, 88.5), }; StaticObject treeStatic; treeStatic.setTree(); // treeStatic.setObjectType(ObjectType::TREE); Node treeNode("Tree"); treeNode.addGeometry(&tree); treeNode.setObject(&treeStatic); //treeNode.addScale(10.0, 10.0, 10.0); treeNode.addTranslation(trees[0]); treeNode.getBoundingSphere()->radius = 3.0; StaticObject treeStatic2; treeStatic2.setTree(); Node treeNode2("Tree2"); treeNode2.addGeometry(&tree); treeNode2.setObject(&treeStatic2); treeNode2.addTranslation(trees[1]); treeNode2.getBoundingSphere()->radius = 3.0; StaticObject treeStatic3; treeStatic3.setTree(); Node treeNode3("Tree3"); treeNode3.addGeometry(&tree); treeNode3.setObject(&treeStatic3); treeNode3.addTranslation(trees[2]); treeNode3.getBoundingSphere()->radius = 3.0; StaticObject treeStatic4; treeStatic4.setTree(); Node treeNode4("Tree4"); treeNode4.addGeometry(&tree); treeNode4.setObject(&treeStatic4); treeNode4.addTranslation(trees[3]); treeNode4.getBoundingSphere()->radius = 3.0; StaticObject treeStatic5; treeStatic5.setTree(); Node treeNode5("Tree5"); treeNode5.addGeometry(&tree); treeNode5.setObject(&treeStatic5); treeNode5.addTranslation(trees[4]); treeNode5.getBoundingSphere()->radius = 3.0; //treeStatic.getInventory()->addItem(&cookie, 25); //treeStatic.getInventory()->addItem(&branch, 10); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Plane===========================// Plane terrain; Texture terrainTex((char*)RESOURCES_PATH "/Grass.jpg"); Node terrainNode("Plane"); terrainNode.addGeometry(&terrain); terrainNode.addTexture(&terrainTex); terrainNode.addTranslation(0.0, -0.75, 0.0); terrainNode.addRotation(90.0f, glm::vec3(1.0, 0.0, 0.0)); terrainNode.addScale(100.0, 100.0, 100.0); //===================================================================// //==================Setting up the Level and Scene==================// //==================================================================// Level testLevel("testLevel"); Scene testScene("testScene"); testLevel.addScene(&testScene); testLevel.changeScene("testScene"); //==================Add Camera to Scene============================// testScene.getScenegraph()->addCamera(&cam); testScene.getScenegraph()->setActiveCamera("StrategyCam"); //==================Set Input-Maps and activate one================// iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera())); iH.changeActiveInputMap("Strategy"); //==================Add Objects to the Scene=======================// //==================Update the Bounding-Sphere 1st time============// testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&terrainNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode2); testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode3); testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode4); testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode5); // ============================================================== // == Questsystem ==================================================== // ============================================================== //QuestHandler questhandler; //testLevel.getQuestHandler()->getGraph()->setExampleGraph(); Quest questCollect(1); questCollect.setActive(true); Goal_Collect goalCollect(1); Goal_Collect goalCollect3(3); questCollect.addGoal(&goalCollect); questCollect.addGoal(&goalCollect3); ExpReward expReward(1); expReward.setExp(100); questCollect.addReward(&expReward); Quest questCollect2(2); questCollect2.setActive(true); Goal_Collect goalCollect2(2); questCollect2.addGoal(&goalCollect2); questCollect2.addReward(&expReward); goalCollect.setGoalCount(50); goalCollect2.setGoalCount(50); goalCollect3.setGoalCount(50); goalCollect.setItemType(ItemType::BRANCH); goalCollect2.setItemType(ItemType::BRANCH); goalCollect3.setItemType(ItemType::COOKIE); testLevel.getQuestHandler()->addQuest(&questCollect); testLevel.getQuestHandler()->addQuest(&questCollect2); //===================================================================// //==================Setting up the Collision=========================// //==================================================================// CollisionTest collision; collision.collectNodes(testScene.getScenegraph()->getRootNode()); //===================================================================// //==================Setting up the Observers========================// //==================================================================// ObjectObserver aiObserver(&testLevel); SoundObserver soundAIObserver(&testLevel); ant_Flick.addObserver(&aiObserver); ant_Flick.addObserver(&soundAIObserver); ObjectObserver playerObserver(&testLevel); SoundObserver soundPlayerObserver(&testLevel); geko.addObserver(&playerObserver); geko.addObserver(&soundPlayerObserver); CollisionObserver colObserver(&testLevel); collision.addObserver(&colObserver); collision.addObserver(&soundPlayerObserver); GravityObserver gravityObserver(&testLevel); collision.addObserver(&gravityObserver); QuestObserver questObserver(&testLevel); questCollect.addObserver(&questObserver); questCollect2.addObserver(&questObserver); questCollect.addObserver(&soundPlayerObserver); questCollect2.addObserver(&soundPlayerObserver); goalCollect.addObserver(&questObserver); goalCollect2.addObserver(&questObserver); goalCollect3.addObserver(&questObserver); testLevel.getFightSystem()->addObserver(&questObserver); //===================================================================// //==================Setting up the Gravity===========================// //==================================================================// Gravity gravity; playerNode.addGravity(&gravity); aiNode.addGravity(&gravity); //===================================================================// //==================The Render-Loop==================================// //==================================================================// float lastTime = glfwGetTime(); Node* tmp = testLevel.getActiveScene()->getScenegraph()->searchNode("Plane"); tmp->getNodeName(); sfh.updateListenerPosition(glm::vec3(10.0, 3.0, -5.0)); sfh.playSource("Feuer"); sfh.playSource("Hintergrund"); sfh.setGain("Hintergrund", 0.5f); while (!glfwWindowShouldClose(testWindow.getWindow())) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float currentTime = glfwGetTime(); float deltaTime = currentTime - lastTime; lastTime = currentTime; mouse_callback(testWindow.getWindow()); //===================================================================// //==================Update your Objects per Frame here =============// //==================================================================// collision.update(); //ant_Flick.updateState(); ant_Flick.update(); //===================================================================// //==================Input and update for the Player==================// //==================================================================// playKey_callback(testWindow.getWindow()); //geko.update(deltaTime); //===================================================================// //==================Render your Objects==============================// //==================================================================// glEnable(GL_DEPTH_TEST); shader.bind(); shader.sendMat4("viewMatrix", cam.getViewMatrix()); shader.sendMat4("projectionMatrix", cam.getProjectionMatrix()); testScene.render(shader); shader.unbind(); glfwSwapBuffers(testWindow.getWindow()); glfwPollEvents(); } glfwDestroyWindow(testWindow.getWindow()); glfwTerminate(); return 0; }
uint RetManager::retrieval(unsigned retNum, unsigned* pages, profilerC& p) { // p.start(CONSTS::ALLQS); cout << retNum << endl; retDocID = new unsigned[retNum]; retDocScore = new float[retNum]; // p.start(CONSTS::STEP1); DecisionTree *DT = new DecisionTree(r,num,retNum); theHead = DT->getHead(); // p.end(CONSTS::STEP1); // cout << "qp processing" << endl; int i,l,n; // p.start(CONSTS::STEP2); curDoc = findNextDoc(); uint Totaldocs_decompressed = 1; while(curDoc < CONSTS::MAXD) { for(i=0; i<num; i++) if(r[i].curDocID<curDoc) r[i].curDocID = r[i].PR->nextGEQ(curDoc); DT->putDoc(curDoc,r);;//DT->putDoc(curDoc,r); curDoc = findNextDoc(); Totaldocs_decompressed ++; } // cout <<"Totaldocs_decompressed: "<< Totaldocs_decompressed <<endl; // p.end(CONSTS::STEP2); // cout << "qp processing done" << endl; // cout << "look up" << endl; const float okapiK1=1.2; const float okapiB=0.2; DecisionTreeNode **blockList = DT->getBlockList(); vector<pair<unsigned,unsigned*> >::iterator it; // p.start(CONSTS::STEP3); cout << "Number of Blocks: " <<DT->getBlockNum()<<endl; for(i=0; i<DT->getBlockNum(); i++) { cout << "i: "<< i << endl; n=blockList[i]->termScores.size(); cout << "n: "<< n << endl; int theSize = blockList[i]->content->record.size(); cout<< "theSize of current lock: "<<theSize << endl; if(theSize+retN>retNum) theSize = retNum-retN; cout<< "TopK: "<< retNum <<" retN: "<<retN<<" theSize needed to reach topK: " <<theSize<<endl; if(theSize==0) continue; topDocs = new MinHeap(theSize); cout<< "start doing look up in block: "<<i<< endl; for(it=blockList[i]->content->record.begin(); it!=blockList[i]->content->record.end(); it++) { unsigned* theTF=it->second; float score=0; float docLength = pages[it->first];//float docLength = theIndex -> getDocLength(it->first); for(l=0; l<n; l++) { float tf = theTF[l]; float weight = ((okapiK1+1.0)*tf) / (okapiK1 * (1.0-okapiB+okapiB * docLength /CONSTS::AVGD)+tf);//float weight = ((okapiK1+1.0)*tf) / (okapiK1*(1.0-okapiB+okapiB*docLength/theIndex->docLengthAvg)+tf); score+=weight*blockList[i]->termScores[l]; } if(score > topDocs->smallest) topDocs->push(it->first,score); evalCounter++; } cout<< "Doc evaluated by far: "<<evalCounter<<endl; cout<< "doing look up in block: "<<i<<" done"<< endl; // p.end(CONSTS::STEP3); for(l=retN+theSize-1; l>=retN; l--) { // cout << l << endl; retDocID[l] = topDocs->pop(retDocScore[l]); } retN+=theSize; cout << "retN: "<<retN<<endl; delete(topDocs); } delete(DT); cout << "look up done" << endl; // p.end(CONSTS::ALLQS); cout << "docs decompressed: "<< Totaldocs_decompressed << endl; return Totaldocs_decompressed; }
bool RandomForests::train_(ClassificationData &trainingData){ //Clear any previous model clear(); const unsigned int M = trainingData.getNumSamples(); const unsigned int N = trainingData.getNumDimensions(); const unsigned int K = trainingData.getNumClasses(); if( M == 0 ){ errorLog << "train_(ClassificationData &trainingData) - Training data has zero samples!" << endl; return false; } if( bootstrappedDatasetWeight <= 0.0 || bootstrappedDatasetWeight > 1.0 ){ errorLog << "train_(ClassificationData &trainingData) - Bootstrapped Dataset Weight must be [> 0.0 and <= 1.0]" << endl; return false; } numInputDimensions = N; numClasses = K; classLabels = trainingData.getClassLabels(); ranges = trainingData.getRanges(); //Scale the training data if needed if( useScaling ){ //Scale the training data between 0 and 1 trainingData.scale(0, 1); } //Flag that the main algorithm has been trained encase we need to trigger any callbacks trained = true; //Train the random forest forest.reserve( forestSize ); for(UINT i=0; i<forestSize; i++){ //Get a balanced bootstrapped dataset UINT datasetSize = (UINT)(trainingData.getNumSamples() * bootstrappedDatasetWeight); ClassificationData data = trainingData.getBootstrappedDataset( datasetSize, true ); DecisionTree tree; tree.setDecisionTreeNode( *decisionTreeNode ); tree.enableScaling( false ); //We have already scaled the training data so we do not need to scale it again tree.setTrainingMode( trainingMode ); tree.setNumSplittingSteps( numRandomSplits ); tree.setMinNumSamplesPerNode( minNumSamplesPerNode ); tree.setMaxDepth( maxDepth ); tree.enableNullRejection( useNullRejection ); tree.setRemoveFeaturesAtEachSpilt( removeFeaturesAtEachSpilt ); trainingLog << "Training forest " << i+1 << "/" << forestSize << "..." << endl; //Train this tree if( !tree.train( data ) ){ errorLog << "train_(ClassificationData &labelledTrainingData) - Failed to train tree at forest index: " << i << endl; clear(); return false; } //Deep copy the tree into the forest forest.push_back( tree.deepCopyTree() ); } return true; }
int main(int argc, const char * argv[]) { //Parse the data filename from the argument list if( argc != 2 ){ cout << "Error: failed to parse data filename from command line. You should run this example with one argument pointing to the data filename!\n"; return EXIT_FAILURE; } const string filename = argv[1]; //Create a new DecisionTree instance DecisionTree dTree; //Set the node that the DecisionTree will use - different nodes may result in different decision boundaries //and some nodes may provide better accuracy than others on specific classification tasks //The current node options are: //- DecisionTreeClusterNode //- DecisionTreeThresholdNode dTree.setDecisionTreeNode( DecisionTreeClusterNode() ); //Set the number of steps that will be used to choose the best splitting values //More steps will give you a better model, but will take longer to train dTree.setNumSplittingSteps( 1000 ); //Set the maximum depth of the tree dTree.setMaxDepth( 10 ); //Set the minimum number of samples allowed per node dTree.setMinNumSamplesPerNode( 10 ); //Load some training data to train the classifier ClassificationData trainingData; if( !trainingData.load( filename ) ){ cout << "Failed to load training data: " << filename << endl; return EXIT_FAILURE; } //Use 20% of the training dataset to create a test dataset ClassificationData testData = trainingData.split( 80 ); //Train the classifier if( !dTree.train( trainingData ) ){ cout << "Failed to train classifier!\n"; return EXIT_FAILURE; } //Print the tree dTree.print(); //Save the model to a file if( !dTree.save("DecisionTreeModel.grt") ){ cout << "Failed to save the classifier model!\n"; return EXIT_FAILURE; } //Load the model from a file if( !dTree.load("DecisionTreeModel.grt") ){ cout << "Failed to load the classifier model!\n"; return EXIT_FAILURE; } //Test the accuracy of the model on the test data double accuracy = 0; for(UINT i=0; i<testData.getNumSamples(); i++){ //Get the i'th test sample UINT classLabel = testData[i].getClassLabel(); VectorDouble inputVector = testData[i].getSample(); //Perform a prediction using the classifier bool predictSuccess = dTree.predict( inputVector ); if( !predictSuccess ){ cout << "Failed to perform prediction for test sampel: " << i <<"\n"; return EXIT_FAILURE; } //Get the predicted class label UINT predictedClassLabel = dTree.getPredictedClassLabel(); VectorDouble classLikelihoods = dTree.getClassLikelihoods(); VectorDouble classDistances = dTree.getClassDistances(); //Update the accuracy if( classLabel == predictedClassLabel ) accuracy++; cout << "TestSample: " << i << " ClassLabel: " << classLabel << " PredictedClassLabel: " << predictedClassLabel << endl; } cout << "Test Accuracy: " << accuracy/double(testData.getNumSamples())*100.0 << "%" << endl; return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { // check parameters number if (argc != 6) { help(); return EXIT_FAILURE; } // choose mode int mode = UNKNOWN_MODE; if (!strcmp(argv[1], zpr)) { mode = ZPR_MODE; } else if (!strcmp(argv[1], um)) { mode = UM_MODE; } // quit app if mode is unknown if (UNKNOWN_MODE == mode) { help(); return EXIT_FAILURE; } // read category_index int readed_category_index = 0; if (ZPR_MODE == mode) { readed_category_index = atoi(argv[5]); } else if (UM_MODE == mode) { readed_category_index = atoi(argv[4]); } if (readed_category_index < 0) { cerr << "category_index must be > 0" << endl; return EXIT_FAILURE; } unsigned category_index = static_cast<unsigned>(readed_category_index); // read mep_parameter - only in UM mode unsigned mep_parameter = 0; if (UM_MODE == mode) { int readed_mep_parameter = atoi(argv[5]); if (readed_mep_parameter < 0) { cerr << "mep_parameter must be > 0" << endl; return EXIT_FAILURE; } mep_parameter = static_cast<unsigned>(readed_mep_parameter); } // this values could be app parameters char separator[] = " ,"; char missing_value_mark[] = "?"; try { /* Building tree */ vector<string> attr = vector<string>(); string line = ""; ifstream building_set_file(argv[2]); if (building_set_file.is_open()) { getline(building_set_file, line); } else throw string("Unable to open file: " + string(argv[2])); typedef tokenizer<char_separator<char> > tokenizer; char_separator<char> sep(separator); tokenizer tok(line, sep); for (tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) attr.push_back(string(*tok_iter)); cout << "Category name: " << attr[category_index] << endl; TrainingSet building_table = TrainingSet(attr, category_index, missing_value_mark); size_t examplesCount = building_table.readFromStream(building_set_file, separator); cout << "Number of readed examples to build: " << examplesCount << endl; building_set_file.close(); DecisionTree* dt = NULL; if (ZPR_MODE == mode) dt = new ZPRDecisionTree(); else if (UM_MODE == mode) dt = new UMDecisionTree(); dt->build(building_table); cout << "Built tree:" << endl; cout << *dt; /* Classifying */ attr = vector<string>(); char* p_to_classify_set_file = NULL; if (ZPR_MODE == mode) { p_to_classify_set_file = argv[4]; } else if (UM_MODE == mode) { p_to_classify_set_file = argv[3]; } line = ""; ifstream to_classify_set_file(argv[3]); if (to_classify_set_file.is_open()) { getline(to_classify_set_file, line); } else throw string("Unable to open file: " + string(argv[3])); tok = tokenizer(line, sep); for (tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) attr.push_back(string(*tok_iter)); TrainingSet to_classify_table = TrainingSet(attr, category_index, missing_value_mark); examplesCount = to_classify_table.readFromStream(to_classify_set_file, separator); cout << "Number of readed examples to classify:" << examplesCount << endl; to_classify_set_file.close(); shared_ptr<vector<string> > result(dt->classify(to_classify_table)); ErrorRate er = ErrorRate(); er.count(result, to_classify_table); cout << "Error rate before pruning: " << er.get() << endl; /* Pruning tree */ if (ZPR_MODE == mode) { attr = vector<string>(); line = ""; ifstream pruning_set_file(argv[3]); if (pruning_set_file.is_open()) { getline(pruning_set_file, line); } else throw string("Unable to open file: " + string(argv[3])); tok = tokenizer(line, sep); for (tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) attr.push_back(string(*tok_iter)); TrainingSet pruning_table = TrainingSet(attr, category_index, missing_value_mark); examplesCount = pruning_table.readFromStream(pruning_set_file, separator); cout << "Number of readed examples to prune:" << examplesCount << endl; pruning_set_file.close(); static_cast<ZPRDecisionTree*>(dt)->reducedErrorPruning(pruning_table); } else if (UM_MODE == mode) { cout << "MEP parameter = " << mep_parameter << endl; static_cast<UMDecisionTree*>(dt)->minimumErrorPruning(mep_parameter); } cout << "Pruned tree:" << endl; cout << *dt; shared_ptr<vector<string> > result2(dt->classify(to_classify_table)); ErrorRate er2 = ErrorRate(); er2.count(result2, to_classify_table); cout << "Error rate after pruning: " << er2.get() << endl; delete dt; } catch (std::string& err) { cerr << err << endl; return EXIT_FAILURE; } catch (std::exception& e) { cerr << e.what() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
int main() { Player geko("Geko", glm::vec3(10.0, 10.0, 10.0)); // Start Konifguration - Window, Context, Camera and Callbacks // glfwInit(); Window testWindow(500, 50, 800, 600, "testWindow"); glfwMakeContextCurrent(testWindow.getWindow()); cam.setKeySpeed(2.0); cam.setNearFar(0.01, 100); //Callback for Camera and Player glfwSetKeyCallback(testWindow.getWindow(), key_callback); glewInit(); // Shader and Renderer Initialization // //Shader for Objects VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert"))); FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag"))); ShaderProgram shader(vs, fs); //Shader for a Skybox VertexShader vsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.vert"))); FragmentShader fsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.frag"))); ShaderProgram shaderSkybox(vsSkybox, fsSkybox); //Renderer with context OpenGL3Context context; Renderer renderer(context); //Level and Scene Level testLevel("testLevel"); Scene testScene("testScene"); testLevel.addScene(&testScene); testLevel.changeScene("testScene"); //Add Camera to scenegraph testScene.getScenegraph()->addCamera(&cam); testScene.getScenegraph()->getCamera("PlayerViewCam"); testScene.getScenegraph()->setActiveCamera("PlayerViewCam"); //Set all InputMaps and set one InputMap active iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera())); iH.changeActiveInputMap("Object"); iH.getActiveInputMap()->update(geko); // ============================================================== // == Object (ant, afraid) ====================================== // ============================================================== Teapot teaAnt; Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp"); //AntMesh antMesh; //Node aiNodeFlick("Flick"); //aiNodeFlick.addGeometry(&teaAnt); //aiNodeFlick.addTexture(&texCV); //testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNodeFlick); //AI ant_Flick; //ant_Flick.setAntAfraid(); //aiNodeFlick.ssetObject(&ant_Flick); // ============================================================== // == Object (ant, aggressiv) =================================== // ============================================================== AntMesh antMesh; //Node aiNodeFlack("Flack"); //aiNodeFlack.addGeometry(&teaAnt); //aiNodeFlack.addGeometry(&antMesh); //aiNodeFlack.addTexture(&texCV); //testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNodeFlack); //AI ant_Flack; //ant_Flack.setAntAggressiv(); //aiNodeFlack.setObject(&ant_Flack); // ============================================================== // == Object (Tree) ============================================= // ============================================================== Texture texBrick((char*)RESOURCES_PATH "/brick.bmp"); //TreeMesh treeMesh; Teapot teaTree; TreeMesh treeMesh; Node treeNode("CookieTree"); StaticObject tree; tree.setTree(); treeNode.setObject(&tree); treeNode.addTexture(&texCV); treeNode.addGeometry(&treeMesh); glm::vec3 posFood(10.0, 0.0, -5.0); treeNode.addTranslation(posFood); treeNode.getBoundingSphere()->radius = 2.0; testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode); // ============================================================== // == Player ==================================================== // ============================================================== Teapot teaPlayer; GekoMesh gekomesh; // Texture texBrick((char*)RESOURCES_PATH "/brick.bmp"); Node playerNode("Player"); playerNode.addTexture(&texBrick); playerNode.setObject(&geko); //playerNode.addGeometry(&teaPlayer); playerNode.addGeometry(&gekomesh); playerNode.setCamera(&cam); geko.setPosition(glm::vec3(10.0, 0.0, 10.0)); //Add the node to the Scene testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode); // ============================================================== // == Questsystem ==================================================== // ============================================================== //QuestHandler questhandler; Quest questCollect(1); questCollect.setActive(true); Goal_Collect goalCollect(1); Goal_Collect goalCollect3(3); questCollect.addGoal(&goalCollect); questCollect.addGoal(&goalCollect3); Quest questCollect2(2); questCollect2.setActive(true); Goal_Collect goalCollect2(2); questCollect2.addGoal(&goalCollect2); goalCollect.setGoalCount(50); goalCollect2.setGoalCount(50); goalCollect3.setGoalCount(50); goalCollect.setItemType(ItemType::BRANCH); goalCollect2.setItemType(ItemType::BRANCH); goalCollect3.setItemType(ItemType::COOKIE); testLevel.getQuestHandler()->addQuest(&questCollect); testLevel.getQuestHandler()->addQuest(&questCollect2); /*questhandler.addQuest(&questCollect); questhandler.addQuest(&questCollect2);*/ //std::cout << "GRÖßE DES QUESTHANDLERS : " << questhandler.getQuests().size() << std::endl; // ============================================================== // == Collision, FightSystem===================================== // ============================================================== // Bounding Box creation for the objects and collision test // CollisionTest collision; FightSystem fight; //===================================================================// //==================Setting up the Observers========================// //==================================================================// ObjectObserver aiObserver(&testLevel); //ant_Flick.addObserver(&aiObserver); //ant_Flack.addObserver(&aiObserver); ObjectObserver playerObserver(&testLevel); geko.addObserver(&playerObserver); CollisionObserver colObserver(&testLevel); collision.addObserver(&colObserver); GravityObserver gravityObserver(&testLevel); collision.addObserver(&gravityObserver); SoundObserver soundObserver(&testLevel); // ============================================================== // == Object (Anthome) ========================================== // ============================================================== //TreeMesh treeMesh; AntHomeMesh homeMesh; Node homeNode("AntHome"); StaticObject home; //home.setTree(); homeNode.setObject(&home); homeNode.addTexture(&texBrick); homeNode.addGeometry(&homeMesh); glm::vec3 posHome(1.0, 0.0, 1.0); homeNode.addTranslation(posHome); homeNode.getBoundingSphere()->radius = 0.5; testScene.getScenegraph()->getRootNode()->addChildrenNode(&homeNode); glm::vec3 posFood2(10.0, 0.0, -5.0); glm::vec3 posSpawn(3.0, 0.0, 3.0); glm::vec3 posDefaultPlayer(0.0, 0.0, 0.0); DecisionTree *aggressivedecisionTree = new DecisionTree(); aggressivedecisionTree->setAntTreeAggressiv(); DecisionTree *afraidDecisionTree = new DecisionTree(); afraidDecisionTree->setAntTreeAfraid(); Graph<AStarNode, AStarAlgorithm>* antAggressiveGraph = new Graph<AStarNode, AStarAlgorithm>(); antAggressiveGraph->setExampleAntAfraid(posSpawn, posFood2, posDefaultPlayer); Graph<AStarNode, AStarAlgorithm>* antAfraidGraph = new Graph<AStarNode, AStarAlgorithm>(); antAfraidGraph->setExampleAntAfraid(posSpawn, posFood, posDefaultPlayer); //AntHome antHome(posSpawn, antMesh, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph); ////antHome.generateGuards(5, &aiObserver); //antHome.generateWorkers(1, &aiObserver); SoundFileHandler sfh(1000); AntHome antHome(posSpawn, &sfh, antMesh, &soundObserver, &playerObserver, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph); antHome.generateWorkers(5, testScene.getScenegraph()->getRootNode()); antHome.addAntsToSceneGraph(testScene.getScenegraph()->getRootNode()); collision.collectNodes(testScene.getScenegraph()->getRootNode()); float lastTime = glfwGetTime(); int i = 0; while (!glfwWindowShouldClose(testWindow.getWindow())) { i++; if (i == 30){ i++; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float currentTime = glfwGetTime(); float deltaTime = currentTime - lastTime; lastTime = currentTime; collision.update(); antHome.updateAnts(); antHome.printPosWorkers(); /* ant_Flick.update(); ant_Flack.update();*/ geko.update(); geko.setDeltaTime(currentTime); renderer.renderScene(testScene, testWindow); } glfwDestroyWindow(testWindow.getWindow()); glfwTerminate(); return 0; }
//===================================================================// //==================Main Method=====================================// //==================================================================// int main() { //===================================================================// //==================Things you need to start with====================// //==================================================================// glfwInit(); Window testWindow(500, 50, 800, 600, "Demo"); glfwMakeContextCurrent(testWindow.getWindow()); // Callback glfwSetKeyCallback(testWindow.getWindow(), key_callback); cam.setKeySpeed(2.0); cam.setNearFar(0.01, 100); glewInit(); OpenGL3Context context; //renderer = new Renderer(context); Renderer renderer(context); //===================================================================// //==================Shaders for your program========================// //==================================================================// VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert"))); FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag"))); ShaderProgram shader(vs, fs); VertexShader vsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.vert"))); FragmentShader fsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.frag"))); ShaderProgram shaderGBuffer(vsGBuffer, fsGBuffer); VertexShader vsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.vert"))); FragmentShader fsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.frag"))); ShaderProgram shaderSFQ(vsSfq, fsSfq); VertexShader vsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.vert"))); FragmentShader fsSkybox(loadShaderSource(SHADERS_PATH + std::string("/SkyboxShader/SkyboxShader.frag"))); ShaderProgram shaderSkybox(vsSkybox, fsSkybox); FBO fboGBuffer(WINDOW_WIDTH, WINDOW_HEIGHT, 3, true, false); SoundFileHandler sfh = SoundFileHandler(1000); Rect screenFillingQuad; screenFillingQuad.loadBufferData(); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Terrain===========================// StaticObject terrainObject; terrainObject.setClassType(ClassType::TERRAIN); Texture terrainTex((char*)RESOURCES_PATH "/Grass2.jpg"); Terrain terrain2((char*)RESOURCES_PATH "/heightmap.jpg", 0.0f, 0.0f); Node terrainNode2("Terrain"); terrainNode2.addGeometry(&terrain2); terrainNode2.addTexture(&terrainTex); terrainNode2.setObject(&terrainObject); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Player===========================// Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp"); GekoMesh gekoMesh; geko.setExp(0.0); geko.setLevelThreshold(100.0); geko.setLevel(0); Node playerNode("Player"); playerNode.addGeometry(&gekoMesh); playerNode.setObject(&geko); playerNode.addTexture(&texCV); sfh.generateSource(glm::vec3(geko.getPosition()), RESOURCES_PATH "/Sound/Rascheln.wav"); geko.setSoundHandler(&sfh); geko.setSourceName(MOVESOUND, "SpielerFootsteps", RESOURCES_PATH "/Sound/Rascheln.wav"); //geko.setSourceName(BACKGROUNDMUSIC, "Hintergrund", RESOURCES_PATH "/Sound/jingle2.wav"); geko.setSourceName(FIGHTSOUND, "Kampfsound", RESOURCES_PATH "/Sound/punch.wav"); geko.setSourceName(EATSOUND, "Essen", RESOURCES_PATH "/Sound/Munching.wav"); geko.setSourceName(QUESTSOUND, "Quest", RESOURCES_PATH "/Sound/jingle.wav"); geko.setSourceName(ITEMSOUND, "Item", RESOURCES_PATH "/Sound/itempickup.wav"); geko.setSourceName(FIRESOUND, "Fire", RESOURCES_PATH "/Sound/Feuer_kurz.wav"); sfh.disableLooping("Essen"); sfh.disableLooping("Quest"); sfh.disableLooping("Item"); geko.setPosition(glm::vec4(terrain2.getResolutionX() / 2.0f, 10.0f, terrain2.getResolutionY() / 2.0f, 1.0)); //sfh.generateSource("Feuer",posFood, RESOURCES_PATH "/Sound/Feuer kurz.wav"); playerNode.setCamera(&cam); //===================================================================// //==================Setting up the Level and Scene==================// //==================================================================// Level testLevel("testLevel"); Scene testScene("testScene"); testLevel.addScene(&testScene); testLevel.changeScene("testScene"); testLevel.setTerrain(&terrain2); //==================Add Camera to Scene============================// testScene.getScenegraph()->addCamera(&cam); testScene.getScenegraph()->setActiveCamera("PlayerViewCam"); //==================Set Input-Maps and activate one================// iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera())); iH.changeActiveInputMap(MapType::OBJECT); iH.getActiveInputMap()->update(geko); //==================Add Objects to the Scene=======================// //==================Update the Bounding-Sphere 1st time============// /*Node translateNode("Translate"); translateNode.addTranslation(glm::vec3(terrain2.getResolutionX() / 2.0f, 0.0, terrain2.getResolutionY() / 2.0f));*/ testScene.getScenegraph()->getRootNode()->addChildrenNode(&terrainNode2); testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode); //testScene.getScenegraph()->getRootNode()->addChildrenNode(&translateNode); //testScene.getScenegraph()->getRootNode()->getChildrenNode("Translate")->addChildrenNode(&playerNode); //===================================================================// //==================Setting up the Observers========================// //==================================================================// ObjectObserver playerObserver(&testLevel); SoundObserver soundPlayerObserver(&testLevel); geko.addObserver(&playerObserver); geko.addObserver(&soundPlayerObserver); // ============================================================== // == Object (Forest) ========================================== // ============================================================== TreeMesh tree; glm::vec3 tmp; std::stringstream name; for (int i = 0; i<TreeData::forest1.size(); i++) { name << "Forest1Tree" << i; std::string stringname = name.str(); StaticObject *treeStatic = new StaticObject(); treeStatic->setTree(50 / TreeData::forest1.size()); Node *treeNode = new Node(stringname); treeNode->addGeometry(&tree); treeNode->setObject(treeStatic); tmp.x = TreeData::forest1[i].x; tmp.z = TreeData::forest1[i].z; tmp.y = terrain2.getHeight(glm::vec2(tmp.x, tmp.z)); treeNode->addTranslation(tmp); treeNode->getBoundingSphere()->radius = 2.5; testScene.getScenegraph()->getRootNode()->addChildrenNode(treeNode); name.str(""); } for (int i = 0; i<TreeData::forest2.size(); i++) { name << "Forest2Tree" << i; std::string stringname = name.str(); StaticObject *treeStatic = new StaticObject(); treeStatic->setTree(50 / TreeData::forest2.size()); Node *treeNode = new Node(stringname); treeNode->addGeometry(&tree); treeNode->setObject(treeStatic); tmp.x = TreeData::forest2[i].x; tmp.z = TreeData::forest2[i].z; tmp.y = terrain2.getHeight(glm::vec2(tmp.x, tmp.z)); treeNode->addTranslation(tmp); treeNode->getBoundingSphere()->radius = 2.5; testScene.getScenegraph()->getRootNode()->addChildrenNode(treeNode); name.str(""); } // ============================================================== // == Object (Anthome) ========================================== // ============================================================== glm::vec3 posFood(10.0, 0.0, -5.0); glm::vec3 posFood2((terrain2.getResolutionX() / 2.0f) + 10.0, 0.0, (terrain2.getResolutionY() / 2.0f) - 5.0); glm::vec3 posSpawn(terrain2.getResolutionX() / 2.0f, 10.0, terrain2.getResolutionY() / 2.0f); glm::vec3 posDefaultPlayer(0.0, 0.0, 0.0); AntMesh antMesh; DecisionTree *aggressivedecisionTree = new DecisionTree(); aggressivedecisionTree->setAntTreeAggressiv(); DecisionTree *afraidDecisionTree = new DecisionTree(); afraidDecisionTree->setAntTreeAfraid(); Graph<AStarNode, AStarAlgorithm>* antAggressiveGraph = new Graph<AStarNode, AStarAlgorithm>(); antAggressiveGraph->setExampleAntAggressiv(posSpawn, posFood2, posDefaultPlayer); Graph<AStarNode, AStarAlgorithm>* antAfraidGraph = new Graph<AStarNode, AStarAlgorithm>(); antAfraidGraph->setExampleAntAfraid2(posSpawn, posDefaultPlayer); AntHome antHome(posSpawn, antMesh, &playerObserver, &texCV, &texCV, aggressivedecisionTree, antAggressiveGraph, afraidDecisionTree, antAfraidGraph); //antHome.generateGuards(5, &aiObserver, testScene.getScenegraph()->getRootNode()); antHome.generateWorkers(5, testScene.getScenegraph()->getRootNode()); /*antHome.addAntsToSceneGraph(testScene.getScenegraph()->getRootNode());*/ //===================================================================// //==================Setting up the Collision=========================// //==================================================================// CollisionTest collision; collision.collectNodes(testScene.getScenegraph()->getRootNode()); CollisionObserver colObserver(&testLevel); collision.addObserver(&colObserver); collision.addObserver(&soundPlayerObserver); GravityObserver gravityObserver(&testLevel); collision.addObserver(&gravityObserver); //===================================================================// //==================Setting up the Gravity===========================// //==================================================================// Gravity gravity; playerNode.addGravity(&gravity); //===================================================================// //==================Setting up the Gravity===========================// //==================================================================// PlayerGUI playerGUI(HUD_WIDTH, HUD_HEIGHT, WINDOW_HEIGHT, WINDOW_WIDTH, QUEST_HEIGHT, QUEST_WIDTH, playerNode.getPlayer()); //===================================================================// //==================The Render-Loop==================================// //==================================================================// float lastTime = glfwGetTime(); sfh.playSource("Hintergrund"); sfh.setGain("Hintergrund", 0.5f); //TODO adjust the Rotation,to match the Terrain glm::vec4 tmpPos; glm::vec3 normalFromTerrain; glm::vec3 rotateAxis; glm::vec4 viewDirFromPlayer; glm::vec3 up(0.0, 1.0, 0.0); float lengthFromNormal; float lengthFromUp; float phi; while (!glfwWindowShouldClose(testWindow.getWindow())) { float currentTime = glfwGetTime(); float deltaTime = currentTime - lastTime; lastTime = currentTime; //===================================================================// //==================Update your Objects per Frame here =============// //==================================================================// collision.update(); //===================================================================// //==================Input and update for the Player==================// //==================================================================// geko.update(); geko.setDeltaTime(currentTime); tmpPos = testScene.getScenegraph()->searchNode("Player")->getPlayer()->getPosition(); viewDirFromPlayer = testScene.getScenegraph()->searchNode("Player")->getPlayer()->getViewDirection(); //ToDo calculate Normal funktioniert evtl falsch normalFromTerrain = terrain2.calculateNormal(tmpPos.x, tmpPos.z); rotateAxis = glm::cross(glm::vec3(viewDirFromPlayer), normalFromTerrain ); // lengthFromNormal = glm::length(normalFromTerrain); // lengthFromUp = glm::length(up); normalFromTerrain = glm::normalize(normalFromTerrain); up = glm::normalize(up); phi = glm::dot(up, normalFromTerrain); phi = glm::atan(phi) * (180 / glm::pi<float>()); // phi = glm::acos(glm::dot(normalFromTerrain, up) / (lengthFromNormal * lengthFromUp)); //ToDo Rotation überschreibt die frühere Rotation testScene.getScenegraph()->searchNode("Player")->addRotation(phi, rotateAxis); antHome.updateAnts(); //===================================================================// //==================Render your Objects==============================// //==================================================================// //renderer.renderScene(testScene, testWindow); fboGBuffer.bind(); glClearColor(0.5, 0.5, 0.5, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderGBuffer.bind(); shaderGBuffer.sendMat4("viewMatrix", cam.getViewMatrix()); shaderGBuffer.sendMat4("projectionMatrix", cam.getProjectionMatrix()); testScene.render(shaderGBuffer); shaderGBuffer.unbind(); fboGBuffer.unbind(); //ScreenFillingQuad Render Pass shaderSFQ.bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderSFQ.sendSampler2D("fboTexture", fboGBuffer.getColorTexture(2)); screenFillingQuad.renderGeometry(); shaderSFQ.unbind(); renderer.renderGUI(*playerGUI.getHUD(), testWindow); glfwSwapBuffers(testWindow.getWindow()); glfwPollEvents(); } glfwDestroyWindow(testWindow.getWindow()); glfwTerminate(); return 0; }
//===================================================================// //==================Main Method=====================================// //==================================================================// int main() { //===================================================================// //==================Things you need to start with====================// //==================================================================// glfwInit(); Window testWindow(500, 50, 800, 600, "testWindow"); glfwMakeContextCurrent(testWindow.getWindow()); // Callback glfwSetKeyCallback(testWindow.getWindow(), key_callback); cam.setKeySpeed(2.0); cam.setNearFar(0.01, 100); glewInit(); OpenGL3Context context; //renderer = new Renderer(context); Renderer renderer(context); //===================================================================// //==================Shaders for your program========================// //==================================================================// VertexShader vs(loadShaderSource(SHADERS_PATH + std::string("/Vertex-Shaders/TextureShader3D.vert"))); FragmentShader fs(loadShaderSource(SHADERS_PATH + std::string("/Fragment-Shaders/TextureShader3D.frag"))); ShaderProgram shader(vs, fs); VertexShader vsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.vert"))); FragmentShader fsGBuffer(loadShaderSource(SHADERS_PATH + std::string("/GBuffer/GBuffer.frag"))); ShaderProgram shaderGBuffer(vsGBuffer, fsGBuffer); VertexShader vsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.vert"))); FragmentShader fsSfq(loadShaderSource(SHADERS_PATH + std::string("/ScreenFillingQuad/ScreenFillingQuad.frag"))); ShaderProgram shaderSFQ(vsSfq, fsSfq); FBO fboGBuffer(WINDOW_WIDTH, WINDOW_HEIGHT, 3, true, false); ParticleSystem* particle = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/ComicCloudEffect.xml"); particle->m_type = ParticleType::FIGHT; ParticleSystem* particle2 = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/SwarmOfFliesEffect.xml"); particle2->m_type = ParticleType::SWARMOFFLIES; ParticleSystem* particleFire = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/Fire.xml"); particleFire->m_type = ParticleType::FIRE; Node particleNode("ParticleNode"); particleNode.addParticleSystem(particle2); particleNode.setCamera(&cam); particleNode.setParticleActive(true); Node particleNodeFire("ParticleNodeFire"); particleNodeFire.addParticleSystem(particleFire); particleNodeFire.setCamera(&cam); particleNodeFire.setParticleActive(true); //===================================================================// //==================A Graph for the AI-Unit=========================// //==================================================================// glm::vec3 posFood(10.0, 0.0, -5.0); glm::vec3 posSpawn(3.0, 0.0, 3.0); Graph<AStarNode, AStarAlgorithm> testGraph; //===================================================================// //==================A Decision-Tree for the AI-Unit==================// //==================================================================// DecisionTree defaultTree; defaultTree.setAntTreeAggressiv(); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: AI==============================// Teapot teaAnt; Texture texPlayer((char*)RESOURCES_PATH "/Mesh/Snake.jpg"); SoundFileHandler sfh = SoundFileHandler(1000); AStarNode defaultASNode(); Ant ant_Flick; ant_Flick.setAntAfraid(); AntMesh ant; Node aiNode("Flick"); aiNode.addGeometry(&ant); aiNode.addTexture(&texPlayer); aiNode.addTranslation(ant_Flick.getPosition().x, ant_Flick.getPosition().y, ant_Flick.getPosition().z); aiNode.setObject(&ant_Flick); ant_Flick.setSoundHandler(&sfh); ant_Flick.setSourceName(MOVESOUND_AI, "AIFootsteps", RESOURCES_PATH "/Sound/Footsteps.wav"); sfh.disableLooping("AIFootsteps"); ant_Flick.setSourceName(DEATHSOUND_AI, "AIDeath", RESOURCES_PATH "/Sound/death.wav"); sfh.disableLooping("AIDeath"); ant_Flick.setSourceName(EATSOUND_AI, "AIEssen", RESOURCES_PATH "/Sound/Munching.wav"); sfh.disableLooping("AIEssen"); ant_Flick.setSourceName(DEATHSOUND_FLIES_AI, "Flies", RESOURCES_PATH "/Sound/Fliege_kurz.wav"); sfh.setGain("Flies", 7.0); Rect screenFillingQuad; screenFillingQuad.loadBufferData(); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Player===========================// Teapot teaPlayer; Texture texCV((char*)RESOURCES_PATH "/cv_logo.bmp"); GekoMesh gekoMesh; geko.setExp(0.0); geko.setLevelThreshold(100.0); geko.setLevel(0); Node playerNode("Player"); playerNode.addGeometry(&gekoMesh); playerNode.setObject(&geko); playerNode.addTexture(&texCV); sfh.generateSource(posFood, RESOURCES_PATH "/Sound/Rascheln.wav"); geko.setSoundHandler(&sfh); geko.setSourceName(MOVESOUND, "SpielerFootsteps", RESOURCES_PATH "/Sound/Rascheln.wav"); //geko.setSourceName(BACKGROUNDMUSIC, "Hintergrund", RESOURCES_PATH "/Sound/jingle2.wav"); geko.setSourceName(FIGHTSOUND, "Kampfsound", RESOURCES_PATH "/Sound/punch.wav"); geko.setSourceName(EATSOUND, "Essen", RESOURCES_PATH "/Sound/Munching.wav"); geko.setSourceName(QUESTSOUND, "Quest", RESOURCES_PATH "/Sound/jingle.wav"); geko.setSourceName(ITEMSOUND, "Item", RESOURCES_PATH "/Sound/itempickup.wav"); geko.setSourceName(FIRESOUND, "Fire", RESOURCES_PATH "/Sound/Feuer_kurz.wav"); sfh.disableLooping("Essen"); sfh.disableLooping("Quest"); sfh.disableLooping("Item"); //sfh.generateSource("Feuer",posFood, RESOURCES_PATH "/Sound/Feuer kurz.wav"); playerNode.setCamera(&cam); //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Tree===========================// StaticObject treeStatic; treeStatic.setTree(); TreeMesh tree; Node treeNode("Tree"); treeNode.addGeometry(&tree); treeNode.setObject(&treeStatic); treeNode.addTranslation(posFood); treeNode.getBoundingSphere()->radius = 3.0; //===================================================================// //==================Object declarations - Geometry, Texture, Node=== // //==========================Object: Plane===========================// StaticObject terrainObject; terrainObject.setClassType(ClassType::TERRAIN); Plane terrain; Texture terrainTex((char*)RESOURCES_PATH "/Grass.jpg"); Node terrainNode("Plane"); terrainNode.addGeometry(&terrain); terrainNode.addTexture(&terrainTex); terrainNode.setObject(&terrainObject); terrainNode.addTranslation(0.0, -0.75, 0.0); terrainNode.addRotation(90.0f, glm::vec3(1.0, 0.0, 0.0)); terrainNode.addScale(20.0, 20.0, 20.0); //===================================================================// //==================Setting up the Level and Scene==================// //==================================================================// Level testLevel("testLevel"); Scene testScene("testScene"); testLevel.addScene(&testScene); testLevel.changeScene("testScene"); testLevel.getFightSystem()->setParticle(particle); //==================Add Camera to Scene============================// testScene.getScenegraph()->addCamera(&cam); testScene.getScenegraph()->setActiveCamera("PlayerViewCam"); //==================Set Input-Maps and activate one================// iH.setAllInputMaps(*(testScene.getScenegraph()->getActiveCamera())); iH.changeActiveInputMap(MapType::OBJECT); iH.getActiveInputMap()->update(geko); //==================Add Objects to the Scene=======================// //==================Update the Bounding-Sphere 1st time============// testScene.getScenegraph()->getRootNode()->addChildrenNode(&aiNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&playerNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&terrainNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&treeNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&particleNode); testScene.getScenegraph()->getRootNode()->addChildrenNode(&particleNodeFire); testScene.getScenegraph()->addParticleSystem(particle); testScene.getScenegraph()->addParticleSystem(particle2); testScene.getScenegraph()->addParticleSystem(particleFire); // ============================================================== // == Questsystem ==================================================== // ============================================================== //QuestHandler questhandler; /*Quest questCollect(1); questCollect.setActive(true); Goal_Collect goalCollect(1); Goal_Collect goalCollect3(3); questCollect.addGoal(&goalCollect); questCollect.addGoal(&goalCollect3); ExpReward expReward(1); expReward.setExp(100); questCollect.addReward(&expReward); Item cookie2(100); cookie2.setName("Cookie100"); cookie2.setTypeId(ItemType::COOKIE); ItemReward itemReward(2); itemReward.addItem(&cookie2); questCollect.addReward(&itemReward); Quest questCollect2(2); questCollect2.setActive(true); Goal_Collect goalCollect2(2); questCollect2.addGoal(&goalCollect2); questCollect2.addReward(&expReward); questCollect2.addReward(&itemReward); goalCollect.setGoalCount(50); goalCollect2.setGoalCount(50); goalCollect3.setGoalCount(50); goalCollect.setItemType(ItemType::BRANCH); goalCollect2.setItemType(ItemType::BRANCH); goalCollect3.setItemType(ItemType::COOKIE); testLevel.getQuestHandler()->addQuest(&questCollect); testLevel.getQuestHandler()->addQuest(&questCollect2);*/ Quest questKillAnt(1); Quest questEatAnt(2); Quest questCollectCookie(3); Quest questCollectBranch(4); Goal_Kill killAnt(1); Goal_Eaten eatAnt(2); Goal_Collect collectCookie(3); Goal_Collect collectBranch(4); questKillAnt.addGoal(&killAnt); questEatAnt.addGoal(&eatAnt); questCollectCookie.addGoal(&collectCookie); questCollectBranch.addGoal(&collectBranch); killAnt.setGoalCount(1); eatAnt.setGoalCount(1); collectCookie.setGoalCount(1); collectBranch.setGoalCount(1); collectBranch.setItemType(ItemType::BRANCH); collectCookie.setItemType(ItemType::COOKIE); ExpReward expReward(1); expReward.setExp(100); questKillAnt.addReward(&expReward); questEatAnt.addReward(&expReward); questCollectCookie.addReward(&expReward); questCollectBranch.addReward(&expReward); QuestGraph questGraph; QuestGraphNode nodeStart; nodeStart.setQuest(&questKillAnt); questGraph.addNode(&nodeStart); questKillAnt.setActive(true); QuestGraphNode nodeSecond; nodeSecond.setQuest(&questEatAnt); nodeSecond.setParent(&nodeStart); questGraph.addNode(&nodeSecond); QuestGraphNode nodeThird; nodeThird.setQuest(&questCollectCookie); nodeThird.setParent(&nodeSecond); questGraph.addNode(&nodeThird); QuestGraphNode nodeFourth; nodeFourth.setQuest(&questCollectBranch); nodeFourth.setParent(&nodeThird); questGraph.addNode(&nodeFourth); testLevel.getQuestHandler()->addQuest(&questKillAnt); testLevel.getQuestHandler()->addQuest(&questEatAnt); testLevel.getQuestHandler()->addQuest(&questCollectBranch); testLevel.getQuestHandler()->addQuest(&questCollectCookie); testLevel.getQuestHandler()->setGraph(&questGraph); //===================================================================// //==================Setting up the Collision=========================// //==================================================================// CollisionTest collision; collision.collectNodes(testScene.getScenegraph()->getRootNode()); //===================================================================// //==================Setting up the Observers========================// //==================================================================// ObjectObserver aiObserver(&testLevel); SoundObserver soundAIObserver(&testLevel); ant_Flick.addObserver(&aiObserver); ant_Flick.addObserver(&soundAIObserver); ObjectObserver playerObserver(&testLevel); SoundObserver soundPlayerObserver(&testLevel); geko.addObserver(&playerObserver); geko.addObserver(&soundPlayerObserver); CollisionObserver colObserver(&testLevel); collision.addObserver(&colObserver); collision.addObserver(&soundPlayerObserver); GravityObserver gravityObserver(&testLevel); collision.addObserver(&gravityObserver); QuestObserver questObserver(&testLevel); /*questCollect.addObserver(&questObserver); questCollect2.addObserver(&questObserver); questCollect.addObserver(&soundPlayerObserver); questCollect2.addObserver(&soundPlayerObserver); goalCollect.addObserver(&questObserver); goalCollect2.addObserver(&questObserver); goalCollect3.addObserver(&questObserver);*/ questKillAnt.addObserver(&questObserver); questEatAnt.addObserver(&questObserver); questCollectCookie.addObserver(&questObserver); questCollectBranch.addObserver(&questObserver); killAnt.addObserver(&questObserver); eatAnt.addObserver(&questObserver); collectCookie.addObserver(&questObserver); collectBranch.addObserver(&questObserver); testLevel.getFightSystem()->addObserver(&questObserver); //===================================================================// //==================Setting up the Gravity===========================// //==================================================================// Gravity gravity; playerNode.addGravity(&gravity); aiNode.addGravity(&gravity); //===================================================================// //==================The Render-Loop==================================// //==================================================================// float lastTime = glfwGetTime(); sfh.playSource("Feuer"); sfh.playSource("Hintergrund"); sfh.setGain("Hintergrund", 0.5f); //===================================================================// //==================The Particle-System==============================// //==================================================================// //Effect* smBla = new Effect(); //smBla->loadEffect((char*)RESOURCES_PATH "/XML/ComicCloudEffect.xml"); //ParticleSystem* particle = new ParticleSystem(glm::vec3(0, 0, -10), smBla); // ParticleSystem* particle = new ParticleSystem(glm::vec3(0, 0, 0), (char*)RESOURCES_PATH "/XML/ComicCloudEffect.xml"); //===================================================================// //==================The GUI=========================================// //==================================================================// //======================================================================================================== //SETUP GUI //Texture bricks((char*)RESOURCES_PATH "/bricks_diffuse.png"); //hud = new GUI("testGUI", HUD_WIDTH, HUD_HEIGHT); //hud->setPosition((WINDOW_WIDTH / 2) - (HUD_WIDTH / 2), WINDOW_HEIGHT - HUD_HEIGHT); //hud->setCollapsable(false); //hud->setTitleBarVisible(false); //hud->setBackgroundAlpha(0.5f); //hud->setResizable(false); //hud->setUseScrollbar(false); //hud->setMoveable(false); //int hp = playerNode.getPlayer()->getHealth(); //int hpMax = 10; //int exp = playerNode.getPlayer()->getExp(); //int expMax = playerNode.getPlayer()->getLevelThreshold(); //GuiElement::ProgressBar *hpBar = new GuiElement::ProgressBar(&hp, hpMax, 300, glm::fvec4(1.0f, 0.0f, 0.0f, 1.0f)); //hud->addElement(hpBar); //hud->addElement(new GuiElement::SameLine()); //hud->addElement(new GuiElement::Text("HP")); //GuiElement::ProgressBar *expBar = new GuiElement::ProgressBar(&exp, expMax, 300, glm::fvec4(1.0f, 0.9960784f, 0.9529411f, 1.0f)); //hud->addElement(expBar); //hud->addElement(new GuiElement::SameLine()); //hud->addElement(new GuiElement::Text("EXP")); //hud->addElement(new GuiElement::Spacing()); //hud->addElement(new GuiElement::Separator()); //hud->addElement(new GuiElement::Spacing()); //hud->addElement(new GuiElement::Text("LVL")); //int level = playerNode.getPlayer()->getLvl(); //hud->addElement(new GuiElement::SameLine()); //GuiElement::IntBox *lvlBox = new GuiElement::IntBox(&level, glm::fvec4(1.0f, 1.0f, 1.0f, 1.0f), glm::fvec4(0.7f, 0.7f, 0.7f, 1.0f)); //hud->addElement(lvlBox); //hud->addElement(new GuiElement::SameLine()); //GuiElement::PushButton *inventoryButton = new GuiElement::PushButton("Inventory"); //hud->addElement(inventoryButton); //hud->addElement(new GuiElement::SameLine()); //GuiElement::PushButton *questButton = new GuiElement::PushButton("Quests"); //hud->addElement(questButton); //questWindow = new GuiElement::NestedWindow(); //questWindow->hide(); //GuiElement::Header *quest1 = new GuiElement::Header("Test the Quest"); //quest1->addElement(new GuiElement::Text("Quest description here bla bla bla")); //GuiElement::Header *quest2 = new GuiElement::Header("Testwindow Questwindow"); //quest2->addElement(new GuiElement::Text("Quest description here too bla bla bla")); //questWindow->addElement(quest1); //questWindow->addElement(quest2); //questWindow->setName("Quests"); //questWindow->setCollapsable(false); //questWindow->setPosition(WINDOW_WIDTH - QUEST_WIDTH, (WINDOW_HEIGHT / 2) - (QUEST_HEIGHT / 2)); //questWindow->setSize(QUEST_WIDTH, QUEST_HEIGHT); //hud->addNestedWindow(questWindow); //inventoryWindow = new GuiElement::NestedWindow(); //inventoryWindow->hide(); //inventoryWindow->setName("Inventory"); //inventoryWindow->setCollapsable(false); //inventoryWindow->setResizable(false); //inventoryWindow->setPosition(WINDOW_WIDTH - QUEST_WIDTH, (WINDOW_HEIGHT / 2) - (QUEST_HEIGHT / 2)); //inventoryWindow->setSize(QUEST_WIDTH, QUEST_HEIGHT); //hud->addNestedWindow(inventoryWindow); //std::map<std::string, Texture*> *inventoryItems = new std::map<std::string, Texture*>(); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem1"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem2"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem3"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem4"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem5"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem6"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem7"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem8"), &bricks)); //inventoryItems->insert(std::pair<std::string, Texture*>(std::string("bricksItem9"), &bricks)); //GuiElement::Inventory *inventory = new GuiElement::Inventory(inventoryItems, 6); //inventoryWindow->addElement(inventory); // PlayerGUI playerGUI(HUD_WIDTH, HUD_HEIGHT, WINDOW_HEIGHT, WINDOW_WIDTH, QUEST_HEIGHT, QUEST_WIDTH, playerNode.getPlayer()); float testFloat = float(0.0f); float testFloat2 = float(0.0f); /*testLevel.addGUI(hud); testLevel.getGUI("testGUI")->m_windowName;*/ while (!glfwWindowShouldClose(testWindow.getWindow())) { //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); float currentTime = glfwGetTime(); float deltaTime = currentTime - lastTime; lastTime = currentTime; fboGBuffer.bind(); glClearColor(0.5, 0.5, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderGBuffer.bind(); shaderGBuffer.sendMat4("viewMatrix", cam.getViewMatrix()); shaderGBuffer.sendMat4("projectionMatrix", cam.getProjectionMatrix()); testScene.render(shaderGBuffer); ant_Flick.update(); geko.update(); geko.deleteKeyInput(); geko.setDeltaTime(currentTime); collision.update(); //TEST //particle->update(cam); //particle->render(cam); shaderGBuffer.unbind(); fboGBuffer.unbind(); //ScreenFillingQuad Render Pass shaderSFQ.bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shaderSFQ.sendSampler2D("fboTexture", fboGBuffer.getColorTexture(2)); screenFillingQuad.renderGeometry(); shaderSFQ.unbind(); glfwSwapBuffers(testWindow.getWindow()); glfwPollEvents(); } glfwDestroyWindow(testWindow.getWindow()); glfwTerminate(); return 0; }
int main(int arc, char *argv[]) { //make tree DecisionTree *gameTree = new DecisionTree(); //current node Node *curr; string user; string question; string animal; string userInput = ""; int menu = 0; bool correct = true; //flag to determine if the user put in correct input cout << "Welcome to Animal Guessing Game!" << endl; while (menu != 8) { //print menu cout << "===========Main Menu============" << endl; cout << "1. Play the Game" << endl; cout << "2. How to play" << endl; cout << "3. How many possible animals?" << endl; cout << "4. Display all the animals" << endl; cout << "5. How many possible questions?" << endl; cout << "6. Load" <<endl; cout << "7. Save" <<endl; cout << "8. Quit" << endl; cin >> userInput; //reset value of correct correct = true; // check if the user entered an integer try { //try to convert it to integer //menu = stoi(userInput); menu = atoi(userInput.c_str()); } catch(invalid_argument&) { //if stoi failed, user didn't input an integer cout << "Please enter an integer for the menu options." << endl; correct = false; } catch(out_of_range&) { //user entered a number that is too large for the memory cout << "Please enter an integer that is in-range." << endl; correct = false; } //check if the user entered acceptable input if (correct) { switch(menu) { case 1: //play the game { //get the root to the tree curr = gameTree->getRoot(); //traverse through the tree cout << "Let's play! Think of an animal." << endl; //while the current node is a question while (!curr->isAnimal) { curr = gameTree->askQuestion(curr); } //reached the end of the questions cout << "Is it a " << curr->info << "?\n> "; cin >> user; for (int i = 0; i < user.length(); i++) { //Convert to lower case so that user can input "Yes" or "No" -KT user[i] = tolower(user[i]); } if (user.compare("yes") == 0) { //guessed the correct animal cout << "I win!" << endl; } else { gameTree->userWon(curr); } break; } case 2: //how to play { cout << "Here's how to play!" << endl; cout << "Think of an animal, and I'll try to guess what animal it is." << endl; cout << "I'll ask you yes or no questions about your animal, so know your stuff!" << endl; cout << "When I ask a question, only answer with 'yes' or 'no' (don't capitalize them)." << endl; cout << "If I guess your animal, I win. If I don't, you win!" << endl; cout << "Ready to play?" << endl; break; } case 3: //how many animals { int numAnimals = gameTree->countAnimals(); cout << "I currently know " << numAnimals << " animals. You'll never beat me!" << endl; break; } case 4: //show all animals { cout << "If you haven't played yet, seeing all the animals is cheating." << endl; cout << "Do you really want to display all animals?\n> "; cin >> user; for (int i = 0; i < user.length(); i++) { //Convert to lower case so that user can input "Yes" or "No" -KT user[i] = tolower(user[i]); } if (user.compare("yes") == 0) gameTree->displayAnimals(); else cout << "Good choice. Look at the animals after you play!" << endl; break; } case 5: //how many questions { int numQuestions = gameTree->countQuestions(); cout << "There are currently " << numQuestions << " possible questions that I could ask you." << endl; cout << "You better know your stuff!" << endl; break; } case 6: //load { cout<< "Enter file path (/home/user/Documents/tree.txt)" << endl; string path; cin.ignore(); getline(cin,path); gameTree->load(path); break; } case 7: //save { cout<< "Enter file path (/home/user/Documents/tree.txt)" << endl; string path; cin.ignore(); getline(cin,path); gameTree->save(path); break; } case 8: //quit { cout << "Thanks for playing!" << endl; break; } default: { cout << "Please enter an in-range integer for the menu options." << endl; break; } } } } delete gameTree; //Destructor called -KT cout << "See you next time!" << endl; return 0; }
void specialKeyboard(int key, int x, int y) { if (key == GLUT_KEY_F1) { fullscreen = !fullscreen; if (fullscreen) glutFullScreen(); else { glutReshapeWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT); glutPositionWindow(50, 50); } } if (key == GLUT_KEY_F2) { //createDecisionTree(); clock_t start = clock(); PixelList* p = createPixelList(); cout << "Time to create pixel list: " << ((clock() - start) / (float)CLOCKS_PER_SEC) << endl; cout << "PixelList size: " << p->size() << endl; if(!p->isEmpty()) { time_t start,end; time (&start); //FeatureDefinition myBestFit = myTree.MaximizeInfoGain(*p); myTree.CreateTree(p); time (&end); double dif = difftime (end,start); //cout << "Time to MaximizeInfoGain: " << dif << " seconds" << endl; //cout << "Defined feature > "; //cout << "Radius = " << myBestFit.radius << ", angle = " << myBestFit.angle << ", ratio = " << myBestFit.ratio << endl; } else { cout << "Error creating PixelList!"; } } if (key == GLUT_KEY_F12) { cout << "Opening Image" << endl; png::image<png::rgb_pixel> img("/home/igormacedo/Blender/images/color0.png"); rgb_pixel pixel = img[119][159]; cout << "RED:" << (int)pixel.red << " GREEN:" << (int)pixel.green << " BLUE:" << (int) pixel.blue << endl; img.read("/home/igormacedo/Blender/images/color12.png"); pixel = img[60][60]; cout << "RED:" << (int)pixel.red << " GREEN:" << (int)pixel.green << " BLUE:" << (int) pixel.blue << endl; } if(key == GLUT_KEY_F3) { } if(key == GLUT_KEY_F4) { evaluateImage(); } }
void createDecisionTree() { myTree.CreateTree(generatedPoints); }
int RandomForest::populateDecisionTrees() { try { vector<double> errorRateImprovements; for (int i = 0; i < numDecisionTrees; i++) { if (m->control_pressed) { return 0; } if (((i+1) % 100) == 0) { m->mothurOut("Creating " + toString(i+1) + " (th) Decision tree\n"); } // TODO: need to first fix if we are going to use pointer based system or anything else DecisionTree* decisionTree = new DecisionTree(dataSet, globalDiscardedFeatureIndices, OptimumFeatureSubsetSelector(optimumFeatureSubsetSelectionCriteria), treeSplitCriterion, featureStandardDeviationThreshold); if (m->debug && doPruning) { m->mothurOut("Before pruning\n"); decisionTree->printTree(decisionTree->rootNode, "ROOT"); } int numCorrect; double treeErrorRate; decisionTree->calcTreeErrorRate(numCorrect, treeErrorRate); double prePrunedErrorRate = treeErrorRate; if (m->debug) { m->mothurOut("treeErrorRate: " + toString(treeErrorRate) + " numCorrect: " + toString(numCorrect) + "\n"); } if (doPruning) { decisionTree->pruneTree(pruneAggressiveness); if (m->debug) { m->mothurOut("After pruning\n"); decisionTree->printTree(decisionTree->rootNode, "ROOT"); } decisionTree->calcTreeErrorRate(numCorrect, treeErrorRate); } double postPrunedErrorRate = treeErrorRate; decisionTree->calcTreeVariableImportanceAndError(numCorrect, treeErrorRate); double errorRateImprovement = (prePrunedErrorRate - postPrunedErrorRate) / prePrunedErrorRate; if (m->debug) { m->mothurOut("treeErrorRate: " + toString(treeErrorRate) + " numCorrect: " + toString(numCorrect) + "\n"); if (doPruning) { m->mothurOut("errorRateImprovement: " + toString(errorRateImprovement) + "\n"); } } if (discardHighErrorTrees) { if (treeErrorRate < highErrorTreeDiscardThreshold) { updateGlobalOutOfBagEstimates(decisionTree); decisionTree->purgeDataSetsFromTree(); decisionTrees.push_back(decisionTree); if (doPruning) { errorRateImprovements.push_back(errorRateImprovement); } } else { delete decisionTree; } } else { updateGlobalOutOfBagEstimates(decisionTree); decisionTree->purgeDataSetsFromTree(); decisionTrees.push_back(decisionTree); if (doPruning) { errorRateImprovements.push_back(errorRateImprovement); } } } double avgErrorRateImprovement = -1.0; if (errorRateImprovements.size() > 0) { avgErrorRateImprovement = accumulate(errorRateImprovements.begin(), errorRateImprovements.end(), 0.0); // cout << "Total " << avgErrorRateImprovement << " size " << errorRateImprovements.size() << endl; avgErrorRateImprovement /= errorRateImprovements.size(); } if (m->debug && doPruning) { m->mothurOut("avgErrorRateImprovement:" + toString(avgErrorRateImprovement) + "\n"); } // m->mothurOut("globalOutOfBagEstimates = " + toStringVectorMap(globalOutOfBagEstimates)+ "\n"); return 0; } catch(exception& e) { m->errorOut(e, "RandomForest", "populateDecisionTrees"); exit(1); } }
bool RandomForests::train_(ClassificationData &trainingData){ //Clear any previous model clear(); const unsigned int M = trainingData.getNumSamples(); const unsigned int N = trainingData.getNumDimensions(); const unsigned int K = trainingData.getNumClasses(); if( M == 0 ){ errorLog << "train_(ClassificationData &trainingData) - Training data has zero samples!" << std::endl; return false; } if( bootstrappedDatasetWeight <= 0.0 || bootstrappedDatasetWeight > 1.0 ){ errorLog << "train_(ClassificationData &trainingData) - Bootstrapped Dataset Weight must be [> 0.0 and <= 1.0]" << std::endl; return false; } numInputDimensions = N; numClasses = K; classLabels = trainingData.getClassLabels(); ranges = trainingData.getRanges(); //Scale the training data if needed if( useScaling ){ //Scale the training data between 0 and 1 trainingData.scale(0, 1); } if( useValidationSet ){ validationSetAccuracy = 0; validationSetPrecision.resize( useNullRejection ? K+1 : K, 0 ); validationSetRecall.resize( useNullRejection ? K+1 : K, 0 ); } //Flag that the main algorithm has been trained encase we need to trigger any callbacks trained = true; //Train the random forest forest.reserve( forestSize ); for(UINT i=0; i<forestSize; i++){ //Get a balanced bootstrapped dataset UINT datasetSize = (UINT)(trainingData.getNumSamples() * bootstrappedDatasetWeight); ClassificationData data = trainingData.getBootstrappedDataset( datasetSize, true ); Timer timer; timer.start(); DecisionTree tree; tree.setDecisionTreeNode( *decisionTreeNode ); tree.enableScaling( false ); //We have already scaled the training data so we do not need to scale it again tree.setUseValidationSet( useValidationSet ); tree.setValidationSetSize( validationSetSize ); tree.setTrainingMode( trainingMode ); tree.setNumSplittingSteps( numRandomSplits ); tree.setMinNumSamplesPerNode( minNumSamplesPerNode ); tree.setMaxDepth( maxDepth ); tree.enableNullRejection( useNullRejection ); tree.setRemoveFeaturesAtEachSpilt( removeFeaturesAtEachSpilt ); trainingLog << "Training decision tree " << i+1 << "/" << forestSize << "..." << std::endl; //Train this tree if( !tree.train_( data ) ){ errorLog << "train_(ClassificationData &trainingData) - Failed to train tree at forest index: " << i << std::endl; clear(); return false; } Float computeTime = timer.getMilliSeconds(); trainingLog << "Decision tree trained in " << (computeTime*0.001)/60.0 << " minutes" << std::endl; if( useValidationSet ){ Float forestNorm = 1.0 / forestSize; validationSetAccuracy += tree.getValidationSetAccuracy(); VectorFloat precision = tree.getValidationSetPrecision(); VectorFloat recall = tree.getValidationSetRecall(); grt_assert( precision.getSize() == validationSetPrecision.getSize() ); grt_assert( recall.getSize() == validationSetRecall.getSize() ); for(UINT i=0; i<validationSetPrecision.getSize(); i++){ validationSetPrecision[i] += precision[i] * forestNorm; } for(UINT i=0; i<validationSetRecall.getSize(); i++){ validationSetRecall[i] += recall[i] * forestNorm; } } //Deep copy the tree into the forest forest.push_back( tree.deepCopyTree() ); } if( useValidationSet ){ validationSetAccuracy /= forestSize; trainingLog << "Validation set accuracy: " << validationSetAccuracy << std::endl; trainingLog << "Validation set precision: "; for(UINT i=0; i<validationSetPrecision.getSize(); i++){ trainingLog << validationSetPrecision[i] << " "; } trainingLog << std::endl; trainingLog << "Validation set recall: "; for(UINT i=0; i<validationSetRecall.getSize(); i++){ trainingLog << validationSetRecall[i] << " "; } trainingLog << std::endl; } return true; }
int GradientBoostingForest::LearnNewInstance() { if(!m_pconfig->IsLearnNewInstances) { Comm::LogErr("GradientBoostingForest::LearnNewInstance IsLearnNewInstances is 0"); return -1; } // std::vector< std::vector<int> > vecTmpInstances(m_pInstancePool->Size()); int LeafCnt = 0; for(int i=0;i<m_Forest.size();i++) { DecisionTree * pTree = m_Forest[i]; for(int j=0;j<pTree->Size();j++) { // printf("SizeSize %d\n",pTree->Size()); DecisionTreeNode & node = pTree->GetNode(j); if(LEAF == node.m_status) { /* if(node.m_InstancesHashCode == 1150390567) { printf("f**k debug"); node.print(); } */ if(NULL == node.m_ppInstances) { Comm::LogErr("GradientBoostingForest::LearnNewInstance fail m_ppInstances is NULL DebugStr = %s",node.DebugStr().c_str()); return -1; } node.m_LeafIndex = LeafCnt; LeafCnt++; node.m_ppInstances = Comm::Free(node.m_ppInstances); } } } m_TotLeafCnt = LeafCnt; if(m_pconfig->OutputNewInstancesFilePath == "null") { Comm::LogInfo("GradientBoostingForest::LearnNewInstance OutputNewInstancesFilePath is null"); return 0; } std::ostringstream oss; oss.clear(); oss.str(""); FILE * fp = fopen(m_pconfig->OutputNewInstancesFilePath.c_str(),"w"); if(NULL == fp) { Comm::LogErr("GradientBoostingForest::LearnNewInstance fail! open %s fail!",m_pconfig->OutputNewInstancesFilePath.c_str()); return -1; } //IsPushBackOgX if(m_pconfig->IsPushBackOgX) oss<<"n_feature,"<<LeafCnt + m_pconfig->FeatureNum<<"\n"; else oss<<"n_feature,"<<LeafCnt<<"\n"; int ret = fputs(oss.str().c_str(),fp); if(ret < 0) { Comm::LogErr("GradientBoostingForest::LearnNewInstance fail!fputs %s fail!",oss.str().c_str()); fclose(fp); return -1; } for(int i=0;i<m_pInstancePool->Size();i++) { Instance newInstance; ret = GetNewInstance(m_pInstancePool->GetInstance(i), newInstance); if(ret != 0) { Comm::LogErr("GradientBoostingForest::LearnNewInstance GetNewInstance i = %d fail!",i); fclose(fp); return -1; } std::string str = newInstance.ToString() + "\n"; ret = fputs(str.c_str(),fp); if(ret < 0) { Comm::LogErr("GradientBoostingForest::LearnNewInstance fputs %s fail!",str.c_str()); fclose(fp); return -1; } } fclose(fp); return 0; }