list<int>::iterator recent(list<int>::iterator p) {
		int key = *p;
		time.erase(p);
		return time.insert(time.end(), key);
	}
Example #2
0
 void touch(int key){
     list<item>::iterator it = kv[key];
     lst.erase(it);
     lst.push_front(*it);
     kv[key] = lst.begin();
 }
void listAllMaximalCliquesMatrixRecursive( long* cliqueCount,
                                           #ifdef RETURN_CLIQUES_ONE_BY_ONE
                                           list<list<int>> &cliques,
                                           #endif
                                           list<int> &partialClique, 
                                           char** adjacencyMatrix,
                                           int* vertexSets, int* vertexLookup, int size,
                                           int beginX, int beginP, int beginR , long &stepsSinceLastReportedClique)
{
////    stepsSinceLastReportedClique++;
    // if X is empty and P is empty, return partial clique as maximal
    if(beginX >= beginP && beginP >= beginR)
    {
        (*cliqueCount)++;

////        if (stepsSinceLastReportedClique > partialClique.size()) {
////            numLargeJumps++;
////            //cout << "steps: " << stepsSinceLastReportedClique << ">" << partialClique.size() << endl;
////            if (largestDifference < (stepsSinceLastReportedClique - partialClique.size())) {
////                largestDifference = stepsSinceLastReportedClique - partialClique.size();
////            }
////        }
////
////        stepsSinceLastReportedClique = 0;
        processClique( 
                       #ifdef RETURN_CLIQUES_ONE_BY_ONE
                       cliques,
                       #endif
                       partialClique );

        return;
    }

    // avoid work if P is empty.
    if(beginP >= beginR)
        return;

    int* myCandidatesToIterateThrough;
    int numCandidatesToIterateThrough;

    // get the candidates to add to R to make a maximal clique
    findBestPivotNonNeighborsMatrix( &myCandidatesToIterateThrough,
                                     &numCandidatesToIterateThrough,
                                     adjacencyMatrix,
                                     vertexSets, vertexLookup, size,
                                     beginX, beginP, beginR);

    // add candiate vertices to the partial clique one at a time and 
    // search for maximal cliques
    if(numCandidatesToIterateThrough != 0)
    {
    int iterator = 0;
    while(iterator < numCandidatesToIterateThrough)
    {
        // vertex is to be added to the partial clique
        int vertex = myCandidatesToIterateThrough[iterator];

        #ifdef PRINT_CLIQUES_TOMITA_STYLE
        printf("%d ", vertex);
        #endif

        int newBeginX, newBeginP, newBeginR;

        // add vertex into partialClique, representing R.
        partialClique.push_back(vertex);
        list<int>::iterator vertexLink = partialClique.end();
        --vertexLink;

        // swap vertex into R and update all data structures 
        moveToRMatrix( vertex, 
                       vertexSets, vertexLookup, 
                       adjacencyMatrix,
                       &beginX, &beginP, &beginR, 
                       &newBeginX, &newBeginP, &newBeginR);

        // recursively compute maximal cliques with new sets R, P and X
        listAllMaximalCliquesMatrixRecursive( cliqueCount, 
                                              #ifdef RETURN_CLIQUES_ONE_BY_ONE
                                              cliques,
                                              #endif
                                              partialClique,
                                              adjacencyMatrix,
                                              vertexSets, vertexLookup, size,
                                              newBeginX, newBeginP, newBeginR, stepsSinceLastReportedClique );

        #ifdef PRINT_CLIQUES_TOMITA_STYLE
        printf("b ");
        #endif

        // remove vertex from partialCliques
        partialClique.erase(vertexLink);

        moveFromRToXMatrix( vertex, 
                            vertexSets, vertexLookup, 
                            &beginX, &beginP, &beginR );

        iterator++;
    }

    // swap vertices that were moved to X back into P, for higher recursive calls.
    iterator = 0;
    while(iterator < numCandidatesToIterateThrough)
    {
        int vertex = myCandidatesToIterateThrough[iterator];
        int vertexLocation = vertexLookup[vertex];

        beginP--;
        vertexSets[vertexLocation] = vertexSets[beginP];
        vertexSets[beginP] = vertex;
        vertexLookup[vertex] = beginP;
        vertexLookup[vertexSets[vertexLocation]] = vertexLocation;

        iterator++;
    }

    Free(myCandidatesToIterateThrough);
    }

    stepsSinceLastReportedClique++;
}
Example #4
0
// ----------------------------------------------------------------------------
void f(const Entry& ee, list<Entry>::iterator p, list<Entry>::iterator q){

  phone_book.insert(p, ee);                                                     // add ee before the element referred to by p
  phone_book.erase(q);                                                          // remove the element referred to by q
}
Example #5
0
	void time_step() {
		clock_t now = clock();
		handle_key_presses();
		if(entity_count <= 0) {
			int new_entity_index = create_entity();
			entities[new_entity_index].location.x = rng<T>::next_neg();
			entities[new_entity_index].location.y = rng<T>::next_neg();
			regions.add_entity(entities[new_entity_index]);
		}
		if(environments.size() < 10) {
			point<T> location(rng<T>::next_neg(), rng<T>::next_neg());
			T magnitude = rng<T>::next_neg() * 2.0;
			long expire_time = gen_count + (rng<T>::next() * util::seconds_to_generations(MAX_ENVIRONMENT_LIFESPAN)) + util::seconds_to_generations(MIN_ENVIRONMENT_LIFESPAN);
			if(environments.empty()) {
				magnitude = 2.0;
				expire_time = std::numeric_limits<long>::max();
			}
			environment<T> new_environment(location, magnitude, expire_time, gen_count);
			environments.push_back(new_environment);
		}
		for(auto& env : environments) {	
			if(gen_count > env.update_time) {
				regions.update_heat_level(env.location, env.get_update_magnitude());
			}
		}
		environments.erase(
			std::remove_if(environments.begin(), environments.end(), [&](const environment<T>& env) {
				if(gen_count > env.expire_time) {
					return true;
				}
				return false;
			}),
			environments.end());
		for(int i=0; i<MAX_ENTITIES; ++i) {
			entity<T>& ent = entities[i];
			if(ent.active) {
				procreate(ent);
				move(ent);
				die(ent);
				draw(ent);
			}
		}
		if(draw_environments_enabled) {
			for(const auto& env : environments) {
				draw(env);
			}
		}
		if(draw_regions_enabled) {
			draw_regions();
		}
		cout << (clock() - now)/1000.0 << "  " << entity_count << endl;
		T avg_power = 0.0;
		int power_count = 0;
		for(int i=0; i<MAX_ENTITIES; ++i) {
			if(entities[i].active && (entities[i].power > .5)) {
				avg_power += entities[i].fertility;
				++power_count;
			}
		}
		++gen_count;
		//cout << avg_power / (T)power_count << endl;
		//cout << entities[0].location.x << " : " << entities[0].location.y << endl;
	}
Example #6
0
 virtual ~Entry()
 {
     auto it = std::find(allEntries.begin(), allEntries.end(), this);
     if(it == allEntries.end()) return;
     allEntries.erase(it);
 }
Example #7
0
 //clear model
 void clear(){
   nInliers = -1;
   fit_set.erase(fit_set.begin(),fit_set.end());
 };
Example #8
0
void parse(list<Feature> & features){
    
    printf("1\n");
    tree_visitor(features, reduce_double_features);
    printf("2\n");
    tree_visitor(features, reduce_boxes);
    //tree_visitor(features, tag);
    printf("3\n");
    tree_visitor(features, flatten_tree);
    printf("4\n");
    tree_visitor(features, containment);
    printf("5\n");
    tree_visitor(features, bindtext);
    printf("6\n");

    /*for(list<Feature>::iterator it = features.begin();
            it != features.end(); it++){
      
        // Stamp id
        char tmp[100];
        for(int x=0;x<100;x++){tmp[x]='\0';}

        sprintf ( tmp, "%d", it->id);
        it->text += string() + " id= " + tmp;

        for(int x=0;x<100;x++){tmp[x]='\0';}
        if(it->parent != NULL)
            sprintf ( tmp, "%d", it->parent->id);
        it->text += string() + ", p=" + tmp;

        for(int x=0;x<100;x++){tmp[x]='\0';}
        if(it->child != NULL)
            sprintf ( tmp, "%d", it->child->id);
        it->text += string() + ", c=" + tmp;

        for(int x=0;x<100;x++){tmp[x]='\0';}
        if(it->next != NULL)
            sprintf ( tmp, "%d", it->next->id);
        it->text += string() + ", n=" + tmp;

    }*/


    // Set up heuristic variables
    /*double dist_weight = 0.2;
    double logo_rank = 0;
    CvRect logo_box;
    int m_y = img_rgb.rows/2;
    int m_x = img_rgb.cols/2;
    double max_dist = edist(m_x, m_y);*/


    /*Feature * logo;
    double l_area = 0;

    // Find logo
    for(list<Feature>::iterator it = features.begin();
            it != features.end(); it++){
      
        if(it->type == LOGO){
            it->type = UNCLASSIFIED;
            double area = fabs(contourArea(Mat(it->points)));
            if(l_area < area){
                logo = &*it;
                l_area = area;
            }
        }

    }

    if(l_area != 0){
        logo->type = LOGO;
        logo->text = "__LOGO__";
    }
   

    //HEURISTICS
    int max_y_delta = 15;
    int box_count = 0;
    int box_y = 0;
    bool reducing = false;
    */
    // Convert boxes to rectangles
    /*for(list<Feature>::iterator it = features.begin();
            it != features.end(); it++){
        Feature & f = *it;

        if(f.type == SQUARE){
            box_count++;
            if(box_count == 1){
                box_y = f.box.height + f.box.y;
                bool reducing = true;
            }
        }

        if((reducing && ( f.type != SQUARE) ||
                abs(box_y - (f.box.height + f.box.y)) > max_y_delta) ){

            if(box_count > 1){
                (it-1)->box.width = (it-1)->box.x + (it-1)->box.width -
                        (it-box_count)->box.x;
                (it-1)->box.x = (it-box_count)->box.x;
                (it-1)->type = RECT;
                (it-1)->input_limit = box_count;
                features.erase(it-box_count, it-2);
            }
            box_count = 0;
            reducing = false;
            
        }
            
    }*/


    // Calculate mode for font height...
    // Should look at stdev

    /*float avg_text_size = 0;
    vector<int> text_height = vector<int>(200);
    list<Feature>::iterator it;
    for(it = features.begin(); it != features.end(); it++){
        if(it->type == TEXT && it->box.height < 200){
            text_height[it->box.height]++;
        }
        avg_text_size += it->box.height;
    }

    avg_text_size/=features.size();

    int max = -1;
    int max_idx = -1;
    for(int i = 0; i < text_height.size(); i++){
        if(text_height[i] > max){
            max_idx=i;
        }
    }

    int approx_label_size = text_height[max_idx];


    // HEURISTIC
    // Neighbourhood that needs to be searched for text
    
    int range = 20;
*/
    // Bind text to box
    /*for(it = features.begin(); it != features.end(); it++){
     
        if(it->type == TEXT && approx_label_size+20 > it->box.height
            && approx_label_size-20 < it->box.height){

            int begin = i-range < 0 ? 0 : i-range;
            int end = i+range > features.size()  ? features.size() : i+range;

            double max_dist = -99999999;//DBL_MIN;
            
            list<Feature>::iterator best_match;

            Point2f p = Point2f(it->box.x+it->box.width,
                it->box.y+it->box.height);

            list<Feature>::iterator it2;
            for(it2 = features.begin(); it2 != features.end(); it2++){
                if(it2->type == TEXT || it2->type == INVALID ||
                        it2->type == UNCLASSIFIED || it2->text != "")
                    continue;
                
                
                double dist = pointPolygonTest(Mat(it2->points), p, true);
                //printf("dist %f\n", dist);
                
                double x_dist = fabs(p.x - (it2->box.x+it2->box.width));
                double y_dist = fabs(p.y - (it2->box.y+it->box.height));

                if (dist > 0 && (x_dist > it2->box.width ||
                        y_dist > it2->box.height))
                    continue;

                if(dist > max_dist){
                    max_dist = dist;
                    best_match = it2;
                }

            }

            if(idx != -1){
                best_match->text = it->text;
                it->type = INVALID;
            }
        }
    }*/

    // Delete invalid elements
    list<Feature>::iterator itc=features.begin();
    while (itc!=features.end()) {
        if(itc->type == INVALID || itc->type == UNCLASSIFIED)
            itc=features.erase(itc);
        else
            itc++;
    }
}
Example #9
0
    //---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>
    // Solves a sudoku problem. Tries to apply the rules until
    // the problem is solved or either stagnates. In the last
    // case, start guessing for the cell with lowest number of
    // admissible entries and continue. Returns number of
    // posible solutions. If the board is overdetermined then
    // return 0.
    void solve_aux() {

        if (!compute_all_solutions
                && solutions.size()>1) return;
        int retval = apply_rules();
        if (retval==1) {
            solutions.insert(solutions.begin(),w);
            if (!compute_all_solutions
                    && solutions.size()>1) return;
        }
        if (retval==-1) return;

        int jmin=-1, kmin=-1, admiss;

        // Look for the cell not yet determined
        // with the lower number of admissible
        // values
        for (int j=0; j<sizer; j++) {
            for (int k=0; k<sizer; k++) {
                int cellindx = j*sizer+k, sz;
                cell_t &cell = w[cellindx];
                sz = cell.admissible.size();
                // warning: size==1 means the cell
                // has been already filled. Don't take
                // into account.
                if (sz>1 && (jmin==-1 || sz<admiss)) {
                    jmin = j;
                    kmin=k;
                    admiss = sz;
                }
            }
        }

        // Didn't find a cell, the problem
        // is overdetermined.
        if (!(admiss>1 && jmin>=0)) return;

        // Found a cell
        int cellmin = jmin*sizer+kmin;
        // This is the admissible set of values
        // for the cell
        set<int> s = w[cellmin].admissible;
        // Push current state into the stack
        state_stack.insert(state_stack.begin(),w);

        // Try each of the admissible values
        set<int>::iterator q = s.begin();
        while (q!=s.end()) {
            // Reset current state
            w = *state_stack.begin();

            if (verbose) print();

            // Set entry to the guessed value
            set_entry(jmin,kmin,*q);

            if (verbose) {
                printf("guessing (%d,%d) set to %d, current board: \n",
                       jmin,kmin,*q);
                print();
            }

            // Try to solve again (recursively).
            solve_aux();
            q++;
        }
        // Restore state
        state_stack.erase(state_stack.begin());
    }
 void reduce() {
     listIterator it = pool.begin();
     Map.erase( *it );
     pool.erase( it );
 }
Example #11
0
void GenericTrace::UpdateTraceSourceRegistration()
{
    if (!sti)  // RegisterSimulation() not yet called
        return;

    // step 1: Parse trace_sources string:
    list<SourceInfo> new_sources;
    if (enabled) // if not enabled we will unregister all sources
        new_sources = ParseSourceList(trace_sources);

    // step 2: Now unregister sources no longer wanted:
    for(list<SourceInfo>::iterator it = registered_sources.begin();
        it != registered_sources.end();)
    {
        list<SourceInfo>::iterator next_it = it; ++next_it;
        if (std::find(new_sources.begin(), new_sources.end(), *it) == new_sources.end())
        { // if not contained in new sources unregister it:
            EventClass *event_class = it->event_class;
            assert(event_class);
            if (event_class->UnregisterCallback(&TraceCallbackThunk, &*it) == MTI_OK)
            {
                // Remove from list of registered sources:
                if (verbose)
                    printf("GenericTrace: Removed %s.%s=0x%x\n",
                           it->component_path.c_str(),
                           it->source_name.c_str(),
                           it->field_mask);
                registered_sources.erase(it);
            }
        }
        it = next_it;
    }

    // step 3: Now add new sources which are not already registered:
    for(list<SourceInfo>::iterator it = new_sources.begin();
        it != new_sources.end();)
    {
        list<SourceInfo>::iterator next_it = it; ++next_it;
        if (std::find(registered_sources.begin(), registered_sources.end(), *it) == registered_sources.end())
        { // Not found in registered sources, so register it:
            it->event_class = it->trace_source->CreateEventClass(it->field_mask);
            assert(it->event_class);
            if (it->event_class->RegisterCallback(&TraceCallbackThunk, &*it) == MTI_OK)
            {
                // move *it from new_sources to registered_sources list:
                registered_sources.splice(registered_sources.end(), new_sources, it);
                if (verbose)
                    printf("GenericTrace: Added   %s.%s=0x%x\n",
                           it->component_path.c_str(),
                           it->source_name.c_str(),
                           it->field_mask);
            }
            else if (it->event_class->DumpState(&TraceCallbackThunk, &*it) == MTI_OK)
            {
                if (verbose)
                    printf("GenericTrace: Dumped state of %s.%s=0x%x\n",
                           it->component_path.c_str(),
                           it->source_name.c_str(),
                           it->field_mask);
            }
            else
            {
                fprintf(stderr, "GenericTrace: Error: Can neither register a callback nor can trigger a state dump on trace source %s.%s\n",
                        it->component_path.c_str(),
                        it->source_name.c_str());

            }
        }
        it = next_it;
    }

    // Calculate print_paths:
    if (enabled && !registered_sources.empty())
    {
        string common_path;
        if (shorten_paths)
        {
            // Step 1: Find the longest common prefix of all component paths:
            list<SourceInfo>::iterator it = registered_sources.begin();
            common_path = it->component_path + '.';
            ++it;
            for(;it != registered_sources.end(); ++it)
            {
                string full_path = it->component_path + '.';
                string::iterator first_mismatch =
                    mismatch(common_path.begin(), common_path.end(),
                             full_path.begin()).first;
                common_path.erase(first_mismatch, common_path.end());
            }
            // Ensure the common path contains only full component names, so it ends with a dot:
            string::size_type last_dot = common_path.rfind('.');
            if (last_dot != string::npos)
                common_path.erase(last_dot + 1, string::npos);
            else
                common_path.erase();
        }
        // Step2: Cut off the common prefix to create the path for printing:
        for(list<SourceInfo>::iterator it = registered_sources.begin();
            it != registered_sources.end(); ++it)
        {
            string full_path = it->component_path + '.';
            it->print_path = full_path.substr(common_path.length());
        }
    }
}
Example #12
0
 list<openEntry>::iterator Erase(list<openEntry>::iterator it) {
   return (baseList.erase(it));
 }
Example #13
0
// callback when we press a key
static void keyboard(const unsigned char key, const int x, const int y) {

  switch (key) {
  case 27:
    exit(0);                                  // ESC

  // Spacebar
  case 32:
    if(currentKeyFrame != keyFrames.end()){
      cout << "Restoring to Current Frame: keyFrames[" << currentIndex << "].\n"; 
      frameToSgRbtNodes(*currentKeyFrame);
    }
    break;

  // -'a' control whether draw the sphere
  case 'a':
    DRAW_SPHERE = !DRAW_SPHERE;

    cout << "Now in ";
    if(DRAW_SPHERE)cout << "SPHERE";
    else cout << "NO-SPHERE";  
    cout << " mode.\n";
    break;


  case 'd':
    if(currentKeyFrame != keyFrames.end()){
      cout << "Deleting Current Frame: keyFrames[" << currentIndex << "].\n";
      // delete current key frame
      list<vector<RigTForm> >::iterator tempFrame = currentKeyFrame;
      tempFrame++;
      keyFrames.erase(currentKeyFrame);

      if(!keyFrames.empty()){
        if(tempFrame != keyFrames.begin()){
          currentKeyFrame = --tempFrame;
          currentIndex--;
        }
        else{
          currentKeyFrame = tempFrame;
        }
        cout << "Now Current Frame: keyFrames[" << currentIndex << "].\n";
        frameToSgRbtNodes((*currentKeyFrame));
      }
      else{
        cout << "Now it is an empty list.\n";
        currentKeyFrame = keyFrames.end();
        currentIndex = -1;
      }

    }
    break;
  case 'h':
    cout << " ============== H E L P ==============\n\n"
    << "h\t\thelp menu\n"
    << "s\t\tsave screenshot\n"
    << "f\t\tToggle flat shading on/off.\n"
    << "p\t\tChoose object to edit\n"
    << "v\t\tChoose view\n"
    << "drag left mouse to rotate\n" << endl;
    break;

  case 's':
    glFlush();
    writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
    break;

  case 'f':
    g_activeShader ^= 1;
    break;

  // update a frame
  case 'u':
    // if not empty
    if(currentKeyFrame != keyFrames.end()){
      cout << "Updating Current Frame: keyFrames[" << currentIndex << "].\n";
      sgRbtNodesToFrame(false);
      break;
    }

  // add a new frame
  case 'n':
  {

    vector<RigTForm> newFrame = sgRbtNodesToFrame(true);
    // if not empty
    if(currentKeyFrame != keyFrames.end()){
      keyFrames.insert(next(currentKeyFrame), newFrame);
      currentKeyFrame++;
    }
    // if empty
    else{
      keyFrames.push_back(newFrame);
      currentKeyFrame = keyFrames.begin();
    }

    cout << "Added a new frame at keyFrames[" << ++currentIndex << "].\n";

    break;
  }

  case '>':
    if(currentKeyFrame != prev(keyFrames.end()) && currentKeyFrame != keyFrames.end()){
      currentKeyFrame++;
      currentIndex++;
      cout << "Forward to: keyFrames[" << currentIndex << "].\n";
      frameToSgRbtNodes((*currentKeyFrame));
    }
    break;

  case '<':
    if(currentKeyFrame != keyFrames.begin() && currentKeyFrame != keyFrames.end()){
      currentKeyFrame--;
      currentIndex--;
      cout << "Backward to: keyFrames[" << currentIndex << "].\n";
      frameToSgRbtNodes(*currentKeyFrame);
    }
    break;

  case 'i':
  {
    ifstream input;
    input.open("Frames.txt", ifstream::in);
    int frameNumber, frameSize;
    input >> frameNumber >> frameSize;
    keyFrames.clear();

    cout << "Reading keyFrameList from file Frame.txt.\n";
    for(int i = 0;i < frameNumber;i++){
      vector<RigTForm> tempFrame;
      for(int j = 0;j < frameSize;j++){
        Cvec3 t;
        Quat q;
        for(int k = 0;k < 7;k++){
          double temp;
          input >> temp;
          if(k < 3){t[k] = temp;}
          else{q[k - 3] = temp;}
        }
        tempFrame.push_back(RigTForm(t, q));
      }
      keyFrames.push_back(tempFrame);
    }

    currentKeyFrame = keyFrames.begin();
    if(keyFrames.empty()){
      currentIndex = -1;
    }
    else{
      currentIndex = 0;
    }
    frameToSgRbtNodes((*currentKeyFrame));
    input.close();

    break;
  }

  case 'w':
  {
    ofstream output;
    output.open("Frames.txt", ofstream::out);
    int frameNumber = keyFrames.size();
    int frameSize;

    if(!frameNumber){
      frameSize = 0;
    }
    else{
      frameSize = keyFrames.front().size();
    }

    cout << "Writring keyFrameList to file Frame.txt.\n";
    output << frameNumber << " " << frameSize << endl;
    for(list<vector<RigTForm> >::iterator i = keyFrames.begin();i != keyFrames.end();i++){
      for(vector<RigTForm>::iterator j = (*i).begin();j != (*i).end();j++){
        for(int i = 0;i < 3;i++){
          output << (*j).getTranslation()[i] << " ";
        }
        for(int i = 0;i < 4;i++){
          if(i < 3){output << (*j).getRotation()[i] << " ";}
          else{output << (*j).getRotation()[i] << endl;}
        }
      }
    }

    break;
  }

  case 'y':
    if(keyFrames.size() < 4){
      cout << "Warning: not enough frames, must be at lease 4.\n";
      break;
    }
    else{
      PLAYING = !PLAYING;
      if(PLAYING){
        cout << "Staring Animation Playback...\n";
        glutTimerFunc(0, animateTimerCallback, 0);
      }
      else{
        list<vector<RigTForm> >::iterator t = keyFrames.end();
        t--;t--;
        currentKeyFrame = t;
        currentIndex = keyFrames.size() - 2;
        cout << "Currently Frame: keyFrames[" << currentIndex << "].\n";
        frameToSgRbtNodes(*currentKeyFrame);
      }
      break;
    }


  case '+':
    if(g_msBetweenKeyFrames > 100){
      g_msBetweenKeyFrames-=100;
      cout << "accelerating..." << g_msBetweenKeyFrames << " ms between frames\n";
    }
    break;
  case '-': 
    if(g_msBetweenKeyFrames < 4000){
      g_msBetweenKeyFrames+=100;
      cout << "slowing..." << g_msBetweenKeyFrames << " ms between frames\n";
    }
    break;
  // - 'v': cycle through the 3 views
  case 'v':
    CHOOSEN_FRAME += (CHOOSEN_FRAME == 2) ? -2 : 1;
    cerr << "Currently active eye frame: " << MODE[CHOOSEN_FRAME] <<"\n";

    break;
  // - 'o': cycle through the 3 objects being manipulated

  case 'm':
    if(CHOOSEN_FRAME == 0){
      WORLD_SKY = !WORLD_SKY;
      cerr << "Switching to " << SKY_MODE[WORLD_SKY?0:1] << " frame" << "\n";
    }
    break;

  case 'p':
    PICKING = true;
    cout << "PICKING: " << "ON" << endl;
    return;

  // - 'r': reset the scene
  case 'r':
    reset();
    break;
  }
  glutPostRedisplay();
}
Example #14
0
void DoAnswer(MCONTACT hContact, const TalkBot::MessageInfo *info, bool sticky = false)
{
	if (info->Answer[0] == _T('\0'))
		return;
	int waitTime, thinkTime = 0;
	int defWaitTime = Config.AnswerPauseTime * 1000;
	if (Config.PauseDepends)
		waitTime = defWaitTime * (int)info->Answer.length() / 25;
	else
		waitTime = defWaitTime;
	if (Config.PauseRandom)
	{
		//Let it be up to 4 times longer.
		waitTime = waitTime * (rand() % 300) / 100 + waitTime;
	}
	if (waitTime == 0)
		waitTime = 50; //it's essential, because otherwise message will be added later 
	//then its response, that will cause incorrect ordering of 
	//messages in the opened history (reopening will
	//help, but anyway it's no good)
	if (NotifyTyping(hContact) && Config.AnswerThinkTime)
	{
		thinkTime = Config.AnswerThinkTime * 1000;
		if (Config.PauseRandom)
		{
			//Let it be up to 4 times longer.
			thinkTime = thinkTime * (rand() % 300) / 100 + thinkTime;
		}
	}
	
	mir_cslock lck(cs);
	//Check if this contact's timer handler is now waiting for a cs.
	bool needTimerRearrange = false;
	if (!actionQueue.empty() && actionQueue.front().hContact == hContact)
	{
		needTimerRearrange = true;
		KillTimer(NULL, timerID);
	}
	if (!actionQueue.empty())
	{
		list<QueueElement>::iterator it = actionQueue.end();
		--it;
		while (true)
		{
			if ((*it).hContact == hContact)
			{
				if ((*it).Sticky)
					break;
				list<QueueElement>::iterator tmp = it;
				if (tmp != actionQueue.begin())
					--tmp;
				actionQueue.erase(it);
				it = tmp;
				if (actionQueue.empty())
					break;
			}
			if (it == actionQueue.begin())
				break;
			--it;
		}
	}
	{
		mir_cslock tcl(typingContactsLock);
		if (typingContacts.find(hContact) != typingContacts.end())
		{
			CallService(MS_PROTO_SELFISTYPING, hContact, (LPARAM)PROTOTYPE_SELFTYPING_OFF);
			typingContacts.erase(hContact);
		}
	}
	if (actionQueue.empty())
		needTimerRearrange = true;
	if (thinkTime)
		actionQueue.push_back(QueueElement(hContact, StartTyping, thinkTime, NULL, sticky));
	actionQueue.push_back(QueueElement(hContact, TimerAnswer, waitTime, info, sticky));
	if (needTimerRearrange)
		UpdateTimer();
}
static int next_generation(struct robby **rl, unsigned long int couplenum,
        unsigned long int robbynum)
{
    unsigned long int coup,size, input_no;
    unsigned long int i;
    unsigned long int r1, r2;
    int r;
    unsigned long int j;
    double breed, tot_fitness;
    Genome *gen;
    Species *s;
    list <Species *>::iterator rs1, rs2;
    Genome *rg1, *rg2;
    list<Genome*> children;
    list<Genome*>::iterator g_it, end_git;
    vector<Genome*>::iterator vg_it, vend_git;
    list <Species *>::iterator s_it, end_sit;

    for (coup = 0; coup < couplenum; coup++) {
        rl[coup][0].genome->fitness = rl[coup][0].fitness;
#ifdef KNOWN_MAP
    for(i=0; i<rl[coup][0].m_sizex; i++) {
        memset(rl[coup][0].known_map[i], VIEW_TOO_FAR, rl[coup][0].m_sizey);
    }
#endif
    }
    
    /*clear last modification map for each generation*/
    last_modifications.clear();
    
    cout << "Species size: " << species_list.size() << endl;

    species_list.sort(species_desc_cmp);

    tot_fitness=0;
    size=0;
    
    remove_species(&species_list, couplenum, tot_fitness);
    
    /*cut the species in half*/
    for (s_it = species_list.begin(); s_it != species_list.end();) {
	if(!(*s_it)->cull(false)) {
	    delete (*s_it);    
	    s_it=species_list.erase(s_it);
	}
	else {
	    ++s_it;
	}
    }
    
    /*create children */
    for (s_it = species_list.begin(), end_sit = species_list.end(); s_it != end_sit; ++s_it) {
        /* Crossover children */
        breed=floor((((*s_it)->average_fitness / (double) tot_fitness))*(double) couplenum * .75)-1;
        for(i=0; i<breed; i++) {
            if (RANDOM_DOUBLE(1) >= INTERSPECIES_CROSSOVER_PROB) {
		    gen=new Genome(*s_it, false);
	    } else {
		    /* Crossover between different species */
		    r1 = (long unsigned int)round(RANDOM_DOUBLE(species_list.size() - 1));
		    do {
			    r2 = (long unsigned int)round(RANDOM_DOUBLE(species_list.size() - 1));
		    } while(r1 == r2 && species_list.size() > 1);

		    rs1 = species_list.begin();
		    advance(rs1, r1);

		    rs2 = species_list.begin();
		    advance(rs2, r2);

		    r1 = (long unsigned int)round(RANDOM_DOUBLE(((*rs1)->genomes.size() - 1)));
		    r2 = (long unsigned int)round(RANDOM_DOUBLE(((*rs2)->genomes.size() - 1)));

		    rg1 = (*rs1)->genomes[r1];
		    //rg1 = (*rs1)->genomes.begin();
		    //advance(rg1, r1);

		    rg2 = (*rs2)->genomes[r2];
		    //rg2 = (*rs2)->genomes.begin();
		    //advance(rg2, r2);

		    gen=new Genome(rg1, rg2);
            }
            children.push_back(gen);
            size++;
        }

        /* Mutate children */
        breed=floor((((*s_it)->average_fitness / (double) tot_fitness))*(double) couplenum * .25)-1;
        for(i=0; i<breed; i++) {
            gen=new Genome(*s_it, true);
            children.push_back(gen);
            size++;
        }
    }

    /*keep only 1 genome per species, delete empty ones*/
    for (s_it = species_list.begin(); s_it != species_list.end();) {
        if(!(*s_it)->cull(true)) {
            delete (*s_it);
            s_it=species_list.erase(s_it);
        } else {
            size+=(*s_it)->genomes.size();
            ++s_it;
        }
    }


    while(size<couplenum) {
        /* Add remaining children */
        r=(int)round(RANDOM_DOUBLE(species_list.size()-1));
#ifdef KNOWN_MAP
        input_no = rl[0][0].m_sizex*rl[0][0].m_sizey;
#else
        input_no = get_dis_circle_area(VIEW_RADIUS);
#endif
        s=LIST_GET(Species*, species_list, r);

	if(RANDOM_DOUBLE(1) < MISSING_GENOME_CROSSOVER_PROB)
		gen=new Genome(s, true);
	else
		gen=new Genome(input_no, POSSIBLE_MOVES,robbynum);
	
        children.push_back(gen);

        size++;
    }

    /*assign each children to a species*/
    for(g_it=children.begin(), end_git = children.end(); g_it!=end_git; ++g_it) {
        (*g_it)->specialize(&species_list);
    }

    i=0;

    /*assign genomes to robbies and clean up*/
    for(s_it=species_list.begin(), end_sit = species_list.end(); s_it!=end_sit; ++s_it){

        for(vg_it=(*s_it)->genomes.begin(), vend_git = (*s_it)->genomes.end(); vg_it!=vend_git; ++vg_it) {
            rl[i][0].genome=(*vg_it);

            for(j=1; j<robbynum; j++) {
                if(rl[i][j].genome)
                    delete rl[i][j].genome;
                rl[i][j].genome=new Genome(*vg_it);
            }

            i++;
        }

    }

    return 0;
}
Example #16
0
/**
 * THREAD -> KeepAlive partidas y torneo (tambien lee los puntajes de los juagadores)
 */
void* keepAlive(void* data) {
	puntajesPartida* resumenPartida;

	Semaforo auxSemSHMTorneo("/auxTorneo");
	sem_t * auxSemSHMToreno_Sem_t = auxSemSHMTorneo.getSem_t();
	Semaforo auxSemSHMPartida("/auxPartida");
	sem_t * auxSemSHMPartida_Sem_t = auxSemSHMPartida.getSem_t();
	bool allMatchsFinished = false;
	while (!allMatchsFinished) {
		cout << "mutex keepAlive partidasActivas" << endl;
		pthread_mutex_lock(&mutex_partidasActivas);
		for (list<datosPartida>::iterator it = partidasActivas.begin(); it != partidasActivas.end(); it++) {

			auxSemSHMPartida.setSem_t(it->semaforo_pointerSem_t_Partida);
			cout << "TIME WAIT IN" << endl;
			if (auxSemSHMPartida.timedWait(400000) == 0) {
				//Pudo acceder a la SHM
				cout << "Accedio por el Sem SHM" << endl;

				resumenPartida = (struct puntajesPartida *) shmat(it->idShm, (char *) 0, 0);
				resumenPartida->keepAliveTorneo = true;

				if (resumenPartida->keepAlivePartida == true) {
					it->lecturasFallidasSHM_Partida = 0;
					resumenPartida->keepAlivePartida = false;
				}// else {
				//	it->lecturasFallidasSHM_Partida++;
				//}

				if (it->lecturasFallidasSHM_Partida >= 5) {
					cout << "+5 Fallas -> entra por el Semaforo que lo habilito" << endl;
					cout << "mutex keepAlive listJugadores" << endl;
					pthread_mutex_lock(&mutex_listJugadores);
					if (resumenPartida->jugando == false) {
						//SERVIDOR PARTIDA termino OK
						cout << "SERVIDOR PARTIDA termino OK" << endl;
						//verificar y sumar pts y cant partidas jugadas

						//si el jugador No se desconecto le sumo su puntaje y cantPartidasJugadas
						if (listJugadores.count(resumenPartida->idJugador1) == 1) {
							listJugadores[resumenPartida->idJugador1]->Puntaje += resumenPartida->puntajeJugador1;
							listJugadores[resumenPartida->idJugador1]->CantPartidasJugadas++;

							//si el otro jugador se desconecto asumo que este gano porque el otro avandono
							if (listJugadores.count(resumenPartida->idJugador2) == 0) {
								listJugadores[resumenPartida->idJugador1]->PartidasGanadas++;
							}
						}
						//si el jugador No se desconecto le sumo su puntaje y cantPartidasJugadas
						if (listJugadores.count(resumenPartida->idJugador2) == 1) {
							listJugadores[resumenPartida->idJugador2]->Puntaje += resumenPartida->puntajeJugador2;
							listJugadores[resumenPartida->idJugador2]->CantPartidasJugadas++;

							//si el otro jugador se desconecto asumo que este gano porque el otro avandono
							if (listJugadores.count(resumenPartida->idJugador1) == 0) {
								listJugadores[resumenPartida->idJugador2]->PartidasGanadas++;
							}
						}

						//si los dos estan vivos veo quien gano
						if (listJugadores.count(resumenPartida->idJugador1) == 1 && listJugadores.count(resumenPartida->idJugador2) == 1) {
							if ((listJugadores[resumenPartida->idJugador1]->Puntaje / listJugadores[resumenPartida->idJugador1]->CantPartidasJugadas) > (listJugadores[resumenPartida->idJugador2]->Puntaje / listJugadores[resumenPartida->idJugador2]->CantPartidasJugadas)) {
								//J1 Gana
								listJugadores[resumenPartida->idJugador1]->PartidasGanadas++;
								listJugadores[resumenPartida->idJugador2]->PartidasPerdidas++;
							} else {
								//J2 Gana
								listJugadores[resumenPartida->idJugador2]->PartidasGanadas++;
								listJugadores[resumenPartida->idJugador1]->PartidasPerdidas++;
							}
						}
					} else {
						//SERVIDOR PARTIDA MURIO
						cout << "SERVIDOR PARTIDA MURIO" << endl;
						//actualizo los jugadores porque ya no estan jugando mas y asi les van a asignar una nueva partida
						listJugadores[resumenPartida->idJugador1]->Jugando = false;
						listJugadores[resumenPartida->idJugador2]->Jugando = false;
					}
					pthread_mutex_unlock(&mutex_listJugadores);
					cout << "unmutex keepAlive listJugadores" << endl;
				}

				auxSemSHMTorneo.setSem_t(it->semaforo_pointerSem_t_Torneo);
				auxSemSHMTorneo.V();

			} else {
				//No pudo acceder a la SHM por el Semaforo
				cout << "No pudo acceder a SHM por el semaforo" << endl;
				if (it->lecturasFallidasSHM_Partida >= 5) {

					cout << "No accedio al semaforo y hay +5 fallas" << endl;

					//quitar partida el de la lista
					partidasActivas.erase(it);

					//cerrar SEMAFOROS
					auxSemSHMPartida.close();
					auxSemSHMTorneo.close();

					//limpiar memoria compartida
					shmdt((struct datosPartida *) resumenPartida);
					shmctl(it->idShm, IPC_RMID, (struct shmid_ds *) NULL);
				}

				it->lecturasFallidasSHM_Partida++;
			}
		}
		pthread_mutex_unlock(&mutex_partidasActivas);
		cout << "unmutex keepAlive partidasActivas" << endl;

		usleep(400000);

		pthread_mutex_lock(&mutex_todasLasPartidasFinalizadas);
		cout << "keepalive torneos y partidas mutex  todasLasPartidasFinalizadas" << endl;
		allMatchsFinished = todasLasPartidasFinalizadas;
		pthread_mutex_unlock(&mutex_todasLasPartidasFinalizadas);
		cout << "keepalive torneos y partidas unmutex todasLasPartidasFinalizadas" << endl;

	}

	auxSemSHMPartida.setSem_t(auxSemSHMPartida_Sem_t);
	auxSemSHMPartida.close();
	auxSemSHMTorneo.setSem_t(auxSemSHMToreno_Sem_t);
	auxSemSHMTorneo.close();

	//hacer en algun lado o aca mismo el DELETE(semaforo)
	pthread_exit(NULL);
}
Example #17
0
//-----------------------------------------------------------------------------
// <OnNotification>
// Callback that is triggered when a value, group or node changes
//-----------------------------------------------------------------------------
void OnNotification
(
	Notification const* _notification,
	void* _context
)
{
	// Must do this inside a critical section to avoid conflicts with the main thread
	pthread_mutex_lock( &g_criticalSection );

	switch( _notification->GetType() )
	{
		case Notification::Type_ValueAdded:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// Add the new value to our list
				nodeInfo->m_values.push_back( _notification->GetValueID() );
			}
			break;
		}

		case Notification::Type_ValueRemoved:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// Remove the value from out list
				for( list<ValueID>::iterator it = nodeInfo->m_values.begin(); it != nodeInfo->m_values.end(); ++it )
				{
					if( (*it) == _notification->GetValueID() )
					{
						nodeInfo->m_values.erase( it );
						break;
					}
				}
			}
			break;
		}

		case Notification::Type_ValueChanged:
		{
			// One of the node values has changed
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo = nodeInfo;		// placeholder for real action
			}
			break;
		}

		case Notification::Type_Group:
		{
			// One of the node's association groups has changed
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo = nodeInfo;		// placeholder for real action
			}
			break;
		}

		case Notification::Type_NodeAdded:
		{
			// Add the new node to our list
			NodeInfo* nodeInfo = new NodeInfo();
			nodeInfo->m_homeId = _notification->GetHomeId();
			nodeInfo->m_nodeId = _notification->GetNodeId();
			nodeInfo->m_polled = false;		
			g_nodes.push_back( nodeInfo );
		        if (temp == true) {
			    Manager::Get()->CancelControllerCommand( _notification->GetHomeId() );
                        }
			break;
		}

		case Notification::Type_NodeRemoved:
		{
			// Remove the node from our list
			uint32 const homeId = _notification->GetHomeId();
			uint8 const nodeId = _notification->GetNodeId();
			for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it )
			{
				NodeInfo* nodeInfo = *it;
				if( ( nodeInfo->m_homeId == homeId ) && ( nodeInfo->m_nodeId == nodeId ) )
				{
					g_nodes.erase( it );
					delete nodeInfo;
					break;
				}
			}
			break;
		}

		case Notification::Type_NodeEvent:
		{
			// We have received an event from the node, caused by a
			// basic_set or hail message.
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo = nodeInfo;		// placeholder for real action
			}
			break;
		}

		case Notification::Type_PollingDisabled:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo->m_polled = false;
			}
			break;
		}

		case Notification::Type_PollingEnabled:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo->m_polled = true;
			}
			break;
		}

		case Notification::Type_DriverReady:
		{
			g_homeId = _notification->GetHomeId();
			break;
		}

		case Notification::Type_DriverFailed:
		{
			g_initFailed = true;
			pthread_cond_broadcast(&initCond);
			break;
		}

		case Notification::Type_AwakeNodesQueried:
		case Notification::Type_AllNodesQueried:
		case Notification::Type_AllNodesQueriedSomeDead:
		{
			pthread_cond_broadcast(&initCond);
			break;
		}

		case Notification::Type_DriverReset:
		case Notification::Type_Notification:
		case Notification::Type_NodeNaming:
		case Notification::Type_NodeProtocolInfo:
		case Notification::Type_NodeQueriesComplete:
		default:
		{
		}
	}

	pthread_mutex_unlock( &g_criticalSection );
}
Example #18
0
/*
==================================================================
// This is winmain, the main entry point for Windows applications
==================================================================
*/
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	
	// Initialize the window
	if ( !initWindow( hInstance ) )
		return false;
	// called after creating the window
	if ( !d3dMgr->initD3DManager(wndHandle) )
		return false;
	if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice()))
		return false;


	// Grab the frequency of the high def timer
	__int64 freq = 0;				// measured in counts per second;
	QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
	float sPC = 1.0f / (float)freq;			// number of seconds per count

	__int64 currentTime = 0;				// current time measured in counts per second;
	__int64 previousTime = 0;				// previous time measured in counts per second;

	float numFrames   = 0.0f;				// Used to hold the number of frames
	float timeElapsed = 0.0f;				// cumulative elapsed time

	GetClientRect(wndHandle,&clientBounds);

	float fpsRate = 1.0f/25.0f;

	D3DXVECTOR3 aballoonPos;

	sprintf_s( gBalloonsBurstStr, 50, "Zombies Killed: %d", gBalloonsBurst);


	//====================================================================
	// Load four textures for the balloons; yellow, green, red & explosion
	//====================================================================
	for (int txture = 0; txture < 5; txture++)
	{
		balloonTextures[txture] = new cD3DXTexture(d3dMgr->getTheD3DDevice(), balloonTxtres[txture]);
	}

	// Initial starting position for Rocket
	D3DXVECTOR3 balloonPos;

	/* initialize random seed: */
	srand ( (unsigned int)time(NULL) );

	/* generate random number of balloons */
	int numBalloons = (8);//(rand() % 10 + 1);

	for(int loop = 0; loop < numBalloons; loop++)
	{
		balloonPos = D3DXVECTOR3((float)clientBounds.right/(loop+2),(float)clientBounds.bottom/(loop+2),0);
		aBalloon.push_back(new cBalloon());
		aBalloon[loop]->setSpritePos(balloonPos);
		aBalloon[loop]->setTranslation(D3DXVECTOR2(39.0f,0.0f));
		aBalloon[loop]->setTexture(balloonTextures[(loop % 3)]);
	}

	LPDIRECT3DSURFACE9 aSurface;				// the Direct3D surface
	LPDIRECT3DSURFACE9 theBackbuffer = NULL;  // This will hold the back buffer

	//the starting position for the player 

	D3DXVECTOR3 playerPos = D3DXVECTOR3(300,300,0);
	//cPlayer thePlayer(playerPos,d3dMgr->getTheD3DDevice(), "Images\\Survivor.png");	
	cPlayer thePlayer = cPlayer();
	thePlayer.setTranslation(D3DXVECTOR2(5.0f,0.0f));
	thePlayer.setTexture(balloonTextures[4]);
	thePlayer.setSpritePos(playerPos);
	
	thePlayer.update();

	MSG msg;
	ZeroMemory( &msg, sizeof( msg ) );

	if ( intro = true) 
	{
		aSurface = d3dMgr->getD3DSurfaceFromFile("Images\\zombiebackground.jpg");
	} 

	else 
	{
	// Create the background surface
			aSurface = d3dMgr->getD3DSurfaceFromFile("Images\\zombiebackground.jpg");
	}

	// load custom font
	cD3DXFont* balloonFont = new cD3DXFont(d3dMgr->getTheD3DDevice(),hInstance, "JI Balloon Caps");

	RECT textPos;
	SetRect(&textPos, 50, 10, 550, 100);

	QueryPerformanceCounter((LARGE_INTEGER*)&previousTime);

	while( msg.message!=WM_QUIT )
	{
		// Check the message queue
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else
		{
			// Game code goes here
			QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
			float dt = (currentTime - previousTime)*sPC;

			// Accumulate how much time has passed.
			timeElapsed += dt;
				
			/*
			==============================================================
			| Update the postion of the balloons and check for collisions
			==============================================================
			*/
			if(timeElapsed > fpsRate)
			{
				thePlayer.setSpritePos(D3DXVECTOR3(playerTrans.x,playerTrans.y,0.0f));
				thePlayer.update();

				for(iter = aBalloon.begin(); iter != aBalloon.end(); ++iter)
				{
					(*iter)->update(timeElapsed);			// update balloon
					aballoonPos = (*iter)->getSpritePos();  // get the position of the current balloon
					/*
					==============================================================
					| Check for boundry collision and change balloon direction
					==============================================================
					*/
					if (aballoonPos.x>(clientBounds.right - 60) || aballoonPos.x < 2 )
					{
						(*iter)->setTranslation((*iter)->getTranslation()*(-1));
					}
					/*
					==============================================================
					| Check each balloon against each other for collisions
					==============================================================
					*/				
					for(index = aBalloon.begin(); index != aBalloon.end(); ++index)
					{
						if ((*iter)->collidedWith((*iter)->getBoundingRect(),(*index)->getBoundingRect()))
						{
							// if a collision occurs change the direction of each balloon that has collided
							OutputDebugString("Collision!!");
							(*iter)->setTranslation((*iter)->getTranslation()*(-1));
							(*index)->setTranslation((*index)->getTranslation()*(-1));
						}
					}
				}
				d3dMgr->beginRender();
				theBackbuffer = d3dMgr->getTheBackBuffer();
				d3dMgr->updateTheSurface(aSurface, theBackbuffer);
				d3dMgr->releaseTheBackbuffer(theBackbuffer);
				
				d3dxSRMgr->beginDraw();
				vector<cBalloon*>::iterator iterB = aBalloon.begin();
				for(iterB = aBalloon.begin(); iterB != aBalloon.end(); ++iterB)
				{
					d3dxSRMgr->setTheTransform((*iterB)->getSpriteTransformMatrix());  
					d3dxSRMgr->drawSprite((*iterB)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF);
				
				}
				list<cExplosion*>::iterator iter = gExplode.begin();
				while(iter != gExplode.end())
				{
					if((*iter)->isActive() == false)
					{
						iter = gExplode.erase(iter);
					}
					else
					{
						(*iter)->update(timeElapsed);
						d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix());  
						d3dxSRMgr->drawSprite((*iter)->getTexture(),&((*iter)->getSourceRect()),NULL,NULL,0xFFFFFFFF);
						++iter;
					}
				}
				d3dxSRMgr->setTheTransform(thePlayer.getSpriteTransformMatrix());
				d3dxSRMgr->drawSprite(thePlayer.getTexture(), NULL, NULL, NULL, 0xFFFFFFFF);
				d3dxSRMgr->endDraw();
				balloonFont->printText(gBalloonsBurstStr,textPos);
				d3dMgr->endRender();
				timeElapsed = 0.0f;
			}

			previousTime = currentTime;
		}
	}
	d3dxSRMgr->cleanUp();
	d3dMgr->clean();
	return (int) msg.wParam;
}
Example #19
0
void update()
{
  static float h = 0;
  static float t = 0;
  static float ttn = 300;
  t++;
  h++;
  if (h > 360)
  {
    h -= 360;
  }
  if(mouse_left_down && !mouse_right_down)
  {
    for(int i = 0; i < 10; i++)
    {
      Vec2 pos = {mouse_x, mouse_y};
      Vec2 mom;
      float theta = rand() / (float) RAND_MAX * 3.1416 * 2;
      float scale = rand() / (float) RAND_MAX;
      mom.x = 2*cos(theta)*scale;
      mom.y = 2*sin(theta)*scale;
      Particle* test = new Red(pos, mom, 1, 5 + 5*rand() /(float) RAND_MAX, 3*rand() /(float) RAND_MAX,
                    (int)(30*2 + 30*rand() / (float) RAND_MAX - 15), R, G, B);
      particles.push_back(test);
      reds.push_back(test);
    }
  }
  //printf("Particles: %d\n", particles.size());

  if(t > ttn)
  {
    Vec2 pos = {-SCREEN_WIDTH / 2 + SCREEN_WIDTH * rand() / (float) RAND_MAX,
                -SCREEN_HEIGHT / 2 + SCREEN_HEIGHT * rand() / (float) RAND_MAX};
    while(pos.x*pos.x + pos.y*pos.y < 1)
    {
      pos.x = -SCREEN_WIDTH * 2 + 4*SCREEN_WIDTH * rand() / (float) RAND_MAX;
      pos.y = -SCREEN_HEIGHT * 2 + 4*SCREEN_HEIGHT * rand() / (float) RAND_MAX;
    }
    Vec2 mom = {0, 0};
    Enemy test(pos, mom, 1000, 30, 6);
    enemies.push_back(test);
    t = 0;
    ttn -= 10;
    if(ttn < 1)
      ttn = 1;

    if(player.health == -1)
    {
      player.health = 0;
      ttn = 300;
    }
  }

  for(list<Particle*>::iterator it = particles.begin(); it != particles.end(); it++)
  {
    (*it)->step();
    if((*it)->life > (*it)->max_life)
    {
      it = particles.erase(it);
    }
  }

  for(list<Particle*>::iterator it = reds.begin(); it != reds.end(); it++)
  {
    if((*it)->life > (*it)->max_life)
    {
      it = reds.erase(it);
    }
  }

  for(list<Enemy>::iterator it = enemies.begin(); it != enemies.end(); it++)
  {
    it->step();
    if(it->radius < 4)
    {
      it = enemies.erase(it);
    }
  }

  player.step();
}
void Region::merge( Region& r, int* labels, const int& label, double* ucm, const double& saliency, const int& son, const int& tx )
{
  /* 			I. BOUNDARY        */

  // 	Ia. update father's boundary
  list<Bdry_element>::iterator itrb, itrb2;
  itrb = boundary.begin();
  while ( itrb != boundary.end() )
  {
    if( labels[(*itrb).cc_neigh] == son )
    {
      itrb2 = itrb;
      ++itrb;
      boundary.erase(itrb2);
    }
    else ++itrb;
  }

  int coord_contour;

  //	Ib. move son's boundary to father
  for( itrb = r.boundary.begin(); itrb != r.boundary.end(); ++itrb )
  {
    if (ucm[(*itrb).coord] < saliency ) ucm[(*itrb).coord] = saliency;

    if ( labels[(*itrb).cc_neigh] != label )
      boundary.push_back( Bdry_element(*itrb) );

  }
  r.boundary.erase( r.boundary.begin(), r.boundary.end() );

  /* 			II. ELEMENTS      */

  for( list<int>::iterator p = r.elements.begin(); p != r.elements.end(); ++p ) labels[*p] = label;
  elements.insert( elements.begin(), r.elements.begin(), r.elements.end() );
  r.elements.erase( r.elements.begin(), r.elements.end() );


  /* 			III. NEIGHBORS        */

  map<int,Neighbor_Region, less<int> >::iterator itr, itr2;

  // 	IIIa. remove inactive neighbors from father
  itr = neighbors.begin();
  while( itr != neighbors.end() )
  {
    if ( labels[(*itr).first] != (*itr).first )
    {
      itr2 = itr;
      ++itr;
      neighbors.erase(itr2);
    } else ++itr;
  }

  // 	IIIb. remove inactive neighbors from son y and neighbors belonging to father
  itr = r.neighbors.begin();
  while ( itr != r.neighbors.end() )
  {
    if ( ( labels[(*itr).first] != (*itr).first ) || ( labels[(*itr).first] == label ) )
    {
      itr2 = itr;
      ++itr;
      r.neighbors.erase(itr2);
    } else ++itr;
  }
}
Example #21
0
void Trajectory::integrateBackward(list<TrajectoryStep> &trajectory, list<TrajectoryStep> &startTrajectory, double acceleration) {
	list<TrajectoryStep>::reverse_iterator before = startTrajectory.rbegin();
	double pathPos = trajectory.front().pathPos;
	double pathVel = trajectory.front().pathVel;

	while(true)
	{
		//pathPos -= timeStep * pathVel;
		//pathVel -= timeStep * acceleration;

		double oldPathVel = pathVel;
		pathVel -= timeStep * acceleration;
		pathPos -= timeStep * 0.5 * (oldPathVel + pathVel);

		trajectory.push_front(TrajectoryStep(pathPos, pathVel));
		acceleration = getMinMaxPathAcceleration(pathPos, pathVel, false);

		if(pathVel < 0.0 || pathPos < 0.0) {
			valid = false;
			cout << "error " << pathPos << " " << pathVel << endl;
			return;
		}

		while(before != startTrajectory.rend() && before->pathPos > pathPos) {
			before++;
		}

		bool error = false;

		if(before != startTrajectory.rbegin() && pathVel >= before->pathVel + getSlope(before.base()) * (pathPos - before->pathPos)) {
			TrajectoryStep overshoot = trajectory.front();
			trajectory.pop_front();
			list<TrajectoryStep>::iterator after = before.base();
			TrajectoryStep intersection = getIntersection(startTrajectory, after, overshoot, trajectory.front());
			//cout << "set arrow from " << intersection.pathPos << ", " << intersection.pathVel - 0.8 << " to " << intersection.pathPos << ", " << intersection.pathVel - 0.3 << endl;
		
			if(after != startTrajectory.end()) {
				startTrajectory.erase(after, startTrajectory.end());
				startTrajectory.push_back(intersection);
			}
			startTrajectory.splice(startTrajectory.end(), trajectory);

			return;
		}
		else if(pathVel > getAccelerationMaxPathVelocity(pathPos) + eps || pathVel > getVelocityMaxPathVelocity(pathPos) + eps) {
			// find more accurate intersection with max-velocity curve using bisection
			TrajectoryStep overshoot = trajectory.front();
			trajectory.pop_front();
			double slope = getSlope(overshoot, trajectory.front());
			double before = overshoot.pathPos;
			double after = trajectory.front().pathPos;
			while(after - before > 0.00001) {
				const double midpoint = 0.5 * (before + after);
				double midpointPathVel = overshoot.pathVel + slope * (midpoint - overshoot.pathPos);

				if(midpointPathVel > getAccelerationMaxPathVelocity(midpoint) || midpointPathVel > getVelocityMaxPathVelocity(midpoint))
					before = midpoint;
				else
					after = midpoint;
			}
			trajectory.push_front(TrajectoryStep(after, overshoot.pathVel + slope * (after - overshoot.pathPos)));

			if(getAccelerationMaxPathVelocity(before) < getVelocityMaxPathVelocity(before)) {
				if(trajectory.front().pathVel > getAccelerationMaxPathVelocity(before) + 0.0001) {
					error = true;
				}
				else if(getMinMaxPhaseSlope(trajectory.front().pathPos, trajectory.front().pathVel, false) < getAccelerationMaxPathVelocityDeriv(trajectory.front().pathPos)) { 
					error = true;
				}
			}
			else {
				if(getMinMaxPhaseSlope(trajectory.back().pathPos, trajectory.back().pathVel, false) < getVelocityMaxPathVelocityDeriv(trajectory.back().pathPos)) {
					error = true;
				}
			}
			
		}

		if(error) {
			ofstream file("trajectory.txt");
			for(list<TrajectoryStep>::iterator it = startTrajectory.begin(); it != startTrajectory.end(); it++) {
				file << it->pathPos << "  " << it->pathVel << endl;
			}
			for(list<TrajectoryStep>::iterator it = trajectory.begin(); it != trajectory.end(); it++) {
				file << it->pathPos << "  " << it->pathVel << endl;
			}
			file.close();
			cout << "error" << endl;
			valid = false;
			return;
		}
	}
}
Example #22
0
void StopLineDetector::EvaluateStopLineMarkers(list<Point2i> & stopMarkers, Point2f dir) {
	//clear upper row if two rows are detected

	Rect boundingRect = Rect(0, BINARY_IMAGE_HEIGHT, 0, 00);
	for (list<Point2i>::iterator it = stopMarkers.begin(); it != stopMarkers.end(); it++) {
		if(boundingRect.y > it->y) {
			boundingRect.y = it->y;
			boundingRect.height += boundingRect.y - it->y;
		}

		if(boundingRect.y + boundingRect.height < it->y) {
			boundingRect.height = it->y - boundingRect.y;
		}
	}

	if(boundingRect.height > METER_TO_PIXEL(0.10)) {
		int limit = boundingRect.y + boundingRect.height / 2;
		for (list<Point2i>::iterator it = stopMarkers.begin(); it != stopMarkers.end(); ) {
			if(it->y < limit) {
				it = stopMarkers.erase(it);
			} else {
				it++;
			}
		}
	}

	list<Point2i>::iterator it = stopMarkers.begin();
	int i = 0;
	list<Point2i>::iterator last = it;
	it++;
	if(it == stopMarkers.end()) {
		stopMarkers.clear();
		return;
	}

	dir = CVMath::RotateCW90(dir);

	float limit_ANG = cosf(15 * CV_PI / 180);
	float limit_LEN = METER_TO_PIXEL(0.44) / 3.9;

	list<Point2i>::iterator itC = last;

	bool chainFound = false;

	//find chain of three succeeding points
	for (i = 1; it != stopMarkers.end(); it++, i++) {
		if(i > 1) {
			last = it, last--;
			itC = last, itC--;

			Point2i c = *itC;
			Point2i b = *last;
			Point2i a = *it;

			Point2f CB = b-c;
			float lenCB = cv::norm(CB);
			CB /= lenCB;
			float cosAngleCB = abs(dir.dot(CB));

			Point2f BA = a-b;
			float lenBA = cv::norm(BA);
			BA /= lenBA;
			float cosAngleBA = abs(dir.dot(BA));

			Point2f CA = a-c;
			float lenCA = cv::norm(CA);
			CA /= lenCA;
			float cosAngleCA = abs(dir.dot(CA));

			if(Helper_CheckCondition(cosAngleCB, limit_ANG, lenCB, limit_LEN)) {
				if(Helper_CheckCondition(cosAngleBA, limit_ANG, lenBA, limit_LEN) || chainFound) {
					stopMarkers.erase(last);
					i--;
				}

				if(chainFound) {
					if(Helper_CheckCondition(cosAngleCA, limit_ANG, lenCA, limit_LEN)) {
						it = stopMarkers.erase(it, stopMarkers.end());
						//i--;
						break;
					}
				} else {
					if(Helper_CheckCondition(cosAngleCA, limit_ANG, lenCA, limit_LEN)) {
						stopMarkers.erase(itC);
						i--;
					}
				}
			} else {
				if(Helper_CheckCondition(cosAngleBA, limit_ANG, lenBA, limit_LEN)) {
					if(chainFound == false) {
						stopMarkers.erase(last);
						stopMarkers.erase(itC);
						i -= 2;
					} else if(Helper_CheckCondition(cosAngleCA, limit_ANG, lenCA, limit_LEN)) {
						it = stopMarkers.erase(it);
						it--;
						i--;
					}
				} else if (chainFound == false){
					chainFound = true;
					dir = (CB + BA + CA) * 0.3333333f;
					float dirLength = cv::norm(dir);
					dir /= dirLength;
					limit_LEN = lenCA * 0.5 * 1.1;
					limit_ANG = cosf(10 * CV_PI / 180);
				}
			}
		}
	}

	if (i < 3) {
		stopMarkers.clear();
	}
}
Example #23
0
void greedy()
{
	int i,j;
	int minS;
	int s;
	int total;
	int ma[maxN] = {0};
	int ar[maxN] = {0};
	list<int>::iterator it,it2,nextc;
	
	for(it2 = adj[c2].begin(); it2 != adj[c2].end(); it2 ++)
		ine[*it2] = 1;
		
	total = 1;
	wcs.push_front(c1);
	while(!wcs.empty())
	{
		minS = 0x7fffffff;
		memset(ma,0x7f,sizeof(ma));
		for(it = wcs.begin(); it != wcs.end(); it ++)
		{
			s = -1;
			//fout << *it << ' ';
			for(it2 = adj[*it].begin(); it2 != adj[*it].end(); it2 ++)
			{
				if(!v[*it2] && !inw[*it2])
				{
					s ++;
					ar[s] = *it2;
				}
			}
			if(s < minS)
			{
				minS = s;
				nextc = it;
			}
			else if(s == minS)
			{
				int t = 0;
				for(i = 0; i <= s ; i ++)
					if(ma[i] > ar[i])
					{
						t = 1;
						break;
					}
					else if(ma[i] < ar[i])
						break;
				if(t)
				{
					for(i = 0; i <= s ; i ++)
						ma[i] = ar[i];
					nextc = it;// 加入答案最小 
				}
			}
		}
		//fout << endl;
		for(it2 = adj[*nextc].begin(); it2 != adj[*nextc].end(); it2 ++)
		{
			if(!v[*it2] && !inw[*it2])
			{
				if(!ine[*it2])
					wcs.push_front(*it2);
				inw[*it2] = 1;
			}
		}
		wcs.erase(nextc);
		v[*nextc] = 1;
		inw[*nextc] = 0;
		total += minS;
		if(total == 3)
		{
			for(i = 1; i <= n; i ++)
				if(inw[i])
					fout << i << ' ';
			fout << endl;
		}
		if(total < ans)
		{
			ansl.clear();
			for(i = 0; i <= n; i ++)
				if(inw[i])
					ansl.push_back(i);
			ans = total;
		}
		else if(total == ans)
		{
			j = 0;
			int t = 0;
			for(i = 0; i < ansl.size(); i ++)
			{
				for(; j < ansl[i]; j ++)
					if(inw[j])
					{
						t = 1;
						break;
					}
				if(inw[ansl[i]] != 1)
					break;
			}
			if(t)
			{
				ansl.clear();
				for(i = 0; i <= n; i ++)
					if(inw[i])
						ansl.push_back(i);
			}
		}
	}
}
Example #24
0
  bool OCVLbp::ProcessOptionsAndRemove(list<string>& opts) {
    for (list<string>::iterator i = opts.begin(); i!=opts.end();) {
      string key, value;
      SplitOptionString(*i, key, value);

      // if (key=="crop") {
      // 	vector<string> cropvals = SplitInCommasObeyParentheses(value);
      // 	switch (cropvals.size()) {
      // 	case (1):
      // 	  options.crop.set(atoi(cropvals[0].c_str()));
      // 	  break;
      // 	case (2):
      // 	  options.crop.set(atoi(cropvals[0].c_str()),atoi(cropvals[1].c_str()));
      // 	  break;
      // 	case (4):
      // 	  options.crop.set(atoi(cropvals[0].c_str()),atoi(cropvals[1].c_str()),
      // 			   atoi(cropvals[2].c_str()),atoi(cropvals[3].c_str()));
      // 	  break;
      // 	default:
      // 	  cerr << "OCVLbp(): Parsing option \"crop\" failed: value=\"" 
      // 	       << value << "\"" << endl;
      // 	  return false;
      // 	}

      // } else 

      // obs! this and "blocks" in Caffe should be harmonized and
      // moved to Feature
      if (key=="blocks") {
	vector<string> blockvals = SplitInCommasObeyParentheses(value);
	vector<string>::const_iterator i;
	for (i = blockvals.begin(); i!=blockvals.end(); i++) {
	  if (*i=="1x1" || *i=="full") {
	    blocktypes.push_back(BLOCKS_1x1); 
	  } else if (*i=="2x2") {
	    blocktypes.push_back(BLOCKS_2x2); 
	  } else if (*i=="2x2s") { 
	    blocktypes.push_back(BLOCKS_2x2); 
	    blocktypes.push_back(BLOCKS_2x2_SPLITS);
	  } else if (*i=="3x3") {
	    blocktypes.push_back(BLOCKS_3x3); 
	  } else if (*i=="3x3s") { 
	    blocktypes.push_back(BLOCKS_3x3); 
	    blocktypes.push_back(BLOCKS_3x3_SPLITS);
	  } else if (*i=="4x4") {
	    blocktypes.push_back(BLOCKS_4x4); 
	  } else if (*i=="4x4s") { 
	    blocktypes.push_back(BLOCKS_4x4); 
	    blocktypes.push_back(BLOCKS_4x4_SPLITS);
	  } else if (*i=="5x5") {
	    blocktypes.push_back(BLOCKS_5x5); 
	  } else if (*i=="6x6") {
	    blocktypes.push_back(BLOCKS_6x6); 
	  } else if (*i=="7x7") {
	    blocktypes.push_back(BLOCKS_7x7); 
	  } else if (*i=="8x8") {
	    blocktypes.push_back(BLOCKS_8x8); 
	  } else if (*i=="9x9") {
	    blocktypes.push_back(BLOCKS_9x9); 
	  } else if (*i=="10x10") {
	    blocktypes.push_back(BLOCKS_10x10); 
	  } else if (*i=="8x15") {
	    blocktypes.push_back(BLOCKS_8x15); 
	  } else if (*i=="pyramid4") {
	    blocktypes.push_back(BLOCKS_1x1); 
	    blocktypes.push_back(BLOCKS_2x2);
	    blocktypes.push_back(BLOCKS_4x4);
	  } else if (*i=="pyramid8") {
	    blocktypes.push_back(BLOCKS_1x1); 
	    blocktypes.push_back(BLOCKS_2x2);
	    blocktypes.push_back(BLOCKS_4x4);
	    blocktypes.push_back(BLOCKS_8x8);
	  } else if (*i=="fgbg") {
	    blocktypes.push_back(BLOCKS_FGBG); 
	  } else {
	    cerr << "OCVLbp(): Parsing option \"blocks\" failed: value=\"" 
		 << value << "\"" << endl;
	    return false;
	  }
	}

      } else if (key=="nbh") {
	options.neighborhood = LBP_CIRCULAR;
	vector<string> nbhvals = SplitInCommasObeyParentheses(value);
	if (nbhvals.size() == 2) {
	  options.nneighbors = atoi(nbhvals[0].c_str());
	  options.radius     = atof(nbhvals[1].c_str());
	  if (options.nneighbors>8) {
	    cerr << "OCVLbp(): Maximum number of neighbors is currently 8" 
		 " due to use of CV_8UC1-type matrices. Should be fixed."
		 << endl;
	    return false;
	  }
	    
	} else {
	  cerr << "OCVLbp(): Parsing option \"nbh\" failed: value=\"" 
	       << value << "\"" << endl;
	  return false;
	}	  

      } else if (key=="map") {
	if (value=="u2")
	  options.mapping = LBP_MAPPING_UNIFORM2;
	else {
	  cerr << "OCVLbp(): Unsupported value for option \"map\": value=\"" 
	       << value << "\"" << endl;
	  return false;
	}

      } else if (key == "normhist")
	if (atoi(value.c_str())==2) {
	  options.normalize_histogram = HISTNORM_CAPPED;
	} else {
	  options.normalize_histogram = HISTNORM_NORMAL;
	}

      else if (key == "cslbp") {
	options.lbptype = CSLBP;
	options.cslbp_threshold = atof(value.c_str());	

      } else if (key == "overlap") 
	options.overlapping_blocks = true;

      else if (key == "imgout")
        options.write_image = true;

      else if (key == "funnel") {
        options.do_funneling = true;
	funneling_modelfile = value;

      } else if (key == "illnorm") {
        options.do_illnorm = true;
	if (atoi(value.c_str())==2)
	  options.cropfirst = false;

      } else { // else continue without erasing option from list
        i++;
        continue;
      }

      i = opts.erase(i);
    }

    return Feature::ProcessOptionsAndRemove(opts);
  }
Example #25
0
void szuk(){
for(int i=1; i<pot; i++){
	prev[i][0]=0;
	prev[i][1]=0;
	next[i][0]=0;
	next[i][1]=0;
	}
list<int>::iterator iter=czarne.begin();
int nr=0;
while(!czarne.empty()){
	int poz=(*iter);
			int nextc=0;
			int nextb=0;
			int prevc=0;
			int prevb=0;
			int akt=poz+pot;
			nextc+=next[akt][0];
			nextb+=next[akt][1];
			prevc+=prev[akt][0];
			prevb+=prev[akt][1];
			akt/=2;
			while(akt!=0){
				nextc-=next[akt][0];
				nextb-=next[akt][1];
				prevc-=prev[akt][0];
				prevb-=prev[akt][1];
					akt/=2;
				}
	if(k*(prevc+1)==prevb){
		wynik.push_back(poz);
		us[poz]=1;
		funkcja1(nr,poz, prevc, prevb);
		czarne.erase(iter);
		iter=czarne.begin();
		for(int i=0; i<k+1; i++) cout << wynik[i]+1 << " ";
		cout << endl;
		wynik.clear();
		} 
	else{
		if(k*(nextc+1)==nextb){
			wynik.push_back(poz);
			us[poz]=1;
			funkcja2(nr,poz, prevc, prevb);
			czarne.erase(iter);
			iter=czarne.begin();
			for(int i=0; i<k+1; i++) cout << wynik[i]+1 << " ";
			cout << endl;
			wynik.clear();
			} 
		else{
			if(nextb-nextc*k+(prevb-prevc*k)==k&&(nextb-nextc*k)>0&&(prevb-prevc*k)>0){
				wynik.push_back(poz);
				us[poz]=1;
				funkcja3(nr,poz, prevc, prevb,nextc, nextb);
				czarne.erase(iter);
				iter=czarne.begin();
				for(int i=0; i<k+1; i++) cout << wynik[i]+1 << " ";
				cout << endl;
				wynik.clear();
				} 
			else{
				  iter++; 
				}
			}
		}
	}
}
Example #26
0
void Iterate()
{
	list<Star*>::iterator tempsi;
	float timepassed;
	QueryPerformanceCounter(&currenttime);
	timepassed = (currenttime.QuadPart - starttime.QuadPart)/(float)timerfreq.QuadPart;
	starttime.QuadPart = currenttime.QuadPart;

	time_to_next_state -= timepassed;
	if(savecpu != 0)
		if(timepassed < 0.025f)
			Sleep((int)((0.025f-timepassed)*1000));


	Star* tempstar;
	if((state < 5) || (state > 7))
	{
		float sptp = speed*timepassed;
		for(tempsi= stars.begin();tempsi != stars.end();)
		{
			if((*tempsi)->movestar(sptp))
			{
				tempstar = (*tempsi);
				stars.push_back(tempstar);
				tempsi = stars.erase(tempsi);
			}
			else
			{
				tempsi++;
			}
		}
	}
//	for(int count = 0;count < 10000;count++)
//		stars[count].movestarturn(speed*timepassed,-speed*timepassed*0.5f,speed*timepassed*0.5f);
	if((state > 0) && (state < 4)) planet->movestar(speed*timepassed);
	if((state > 0) && (state < 4)) planet->MoveSky(timepassed);

	switch(state)
	{
	case 0:
		if(planetsyn != 0)
		{
			if(time_to_next_state < 0)
			{
				state = 1;
				planet->createnewstar();
			}
		}
		break;
	case 1:
		if(planet->GetZ() < 50000)
		{
			state = 2;
			acceleration = ((300*300) - (speed*speed))*0.0000125f/*/(float)(2*(50000-10000))*/;
		}
		break;
	case 2:
		speed += acceleration*timepassed;
		if(speed <= 300)
		{
			speed = 300;
			state = 3;
		}
		break;
	case 3:
		if(planet->IsDone())
		{
			acceleration = ((full_speed*full_speed) - (speed*speed))/(float)(2*(50000-10000));
			state = 4;
		}
		break;
	case 4:
		speed += acceleration*timepassed;
		if(speed >= full_speed)
		{
			speed = full_speed;
			float angle = (rand() % 6283) / 1000.0f;
			full_speedx = cos(angle)*20000;
			full_speedy = sin(angle)*20000;
			speedx = 0;
			speedy = 0;
			state = 5;
		}
		break;
	case 5:
		speedx += full_speedx *0.2f * timepassed;
		speedy += full_speedy *0.2f * timepassed;
		for(tempsi= stars.begin();tempsi != stars.end();)
		{
			if((*tempsi)->movestarturn(speed*timepassed,speedx*timepassed,speedy*timepassed))
			{
				tempstar = (*tempsi);
				tempsi = stars.erase(tempsi);
				stars.push_back(tempstar);
			}
			else
			{
				tempsi++;
			}
		}
		if(fabs(speedx) >= fabs(full_speedx))
		{
			time_to_next_state = ((rand()%6000)+2000)/1000.0f;

			state = 6;
		}
		break;
	case 6:
		for(tempsi= stars.begin();tempsi != stars.end();)
		{
			if((*tempsi)->movestarturn(speed*timepassed,speedx*timepassed,speedy*timepassed))
			{
				tempstar = (*tempsi);
				tempsi = stars.erase(tempsi);
				stars.push_back(tempstar);
			}
			else
			{
				tempsi++;
			}
		}
		if(time_to_next_state <= 0)
		{
			time_to_next_state = 5.0f;
			state = 7;
		}
		break;
	case 7:
		speedx -= full_speedx *0.2f * timepassed;
		speedy -= full_speedy *0.2f * timepassed;
		for(tempsi= stars.begin();tempsi != stars.end();)
		{
			if((*tempsi)->movestarturn(speed*timepassed,speedx*timepassed,speedy*timepassed))
			{
				tempstar = (*tempsi);
				tempsi = stars.erase(tempsi);
				stars.push_back(tempstar);
			}
			else
			{
				tempsi++;
			}
		}
		if(time_to_next_state <= 0)
		{
			time_to_next_state = ((rand()%30000)+5000)/1000.0f;

			state = 0;
		}
		break;

	};
	gengine->BeginFrame();
	for(list<Star*>::reverse_iterator temprsi= stars.rbegin();temprsi != stars.rend();temprsi++)
		(*temprsi)->drawstar();
	if((state > 0) && (state < 4)) planet->drawstar();
/*	tempobject->Render();*/
//	tempobjectp->Render();
//	tempobjectp2->Render();

	nframes++;
	time_elapsed += timepassed;
	if(nframes > 100)
	{
		if(time_elapsed <= 0) time_elapsed = 0.000001f;
		frame_rate = nframes/time_elapsed;
		nframes = 0;
		time_elapsed = 0;

	}
	char tempstring[30];
	sprintf(tempstring,"Frame rate is %f",frame_rate);
/*	int pos = 0;
	for(unsigned int count = 0;count < strlen(temp);count++)
	{
		if(temp[count] != '0') pos = count;
	}
	temp[pos+1] = 0;
*/
	gengine->Position(0,0);
	if(framecounteryn != 0) (*gengine) << tempstring;

#if defined DEMO
	if(check_input)
	{
		gengine->Position(0.05f*width,0.2f*height);
		(*gengine) << "This is a DEMO version, Full version does not have these messages.";

		gengine->Position(0.08f*width,0.4f*height);
		(*gengine) << "Full version supports high resolution textures.";
		
		gengine->Position(0.11f*width,0.6f*height);
		(*gengine) << "Visit http://www.hpt-interactive.com to get your copy today!!!";

		gengine->Position(0.14f*width,0.8f*height);
		(*gengine) << "Only $6.95!!!";
	}
#endif
	
	gengine->EndFrame();

}
Example #27
0
// SPLIT toSPLIT LIST OF PHANTOMTRIANGLE'S ON PLANE.
// Uses a variant of the Sutherland-Hodgman algorithm.
void splitTris( Plane plane, list<PhantomTriangle*> & toSplit, list<PhantomTriangle*> & newTris )
{
  // We create 9 pointers, but only 3 will be used.
  // Each of the 3 points a,b,c of each tri needs
  // to be classified as negative-side, +-side, or
  // ON the splitting plane.
  Vector *nS[3] ;
  Vector *pS[3] ; // ptr to the vert on the _other_ side,
  Vector *on[3] ;

  int origTris = toSplit.size() ;

  for( list<PhantomTriangle*>::iterator iter = toSplit.begin() ; iter != toSplit.end() ; )
  {
    // these are counters for how many
    // vertices so far were on what side of the plane.
    int pSide=0, nSide=0, onPlane=0 ;

    PhantomTriangle* pTri = *iter ;
    Vector* triVectors = &pTri->a ; // start here
    
    // test 3 vertices
    for( int i = 0 ; i < 3 ; i++ )
    {
      int v = plane.iSide( triVectors[i] ) ;
      //triVectors[i].print() ;
      //printf( "  v=%f\n", v ) ;
      if( v == 0 ) on[onPlane++]= &triVectors[i];
      else if( v < 0 ) nS[nSide++]= &triVectors[i];
      else pS[pSide++]= &triVectors[i] ;
    }

    ///info( "pSide=%d, nSide=%d, onPlane=%d", pSide, nSide, onPlane ) ;

    if( nSide>=1 && pSide>=1 ) // split.
    {
      // NOT keeping the winding order.  it doesn't matter anyway because
      // these are intersectable, not renderable.

      // the first ray finds the intersection between the negative side and the ps,
      Intersection i1 ;

      //---|+++
      // o |   
      // |\|--->N
      // | |\  
      // o-X-o 

      // Make a ray FROM a point on the negative side,
      // to a point on the +side of the plane
      Ray r1( *(nS[0]), *(pS[0]) ) ;
      
      // use the plane to get the intersection point
      plane.intersectsPlane( r1, &i1 ) ;
      ///pTri->tri->intersects( r1, &mi1 ) ; // use the original tri to get the 3d space intersection point

      // A vertex is on or very near the plane, so 
      // we'll split AT the vertex (cut only one edge)
      if( onPlane==1 )
      {
        // split using the VERTEX on the plane as the splitter.
        // gen 2 tris.
        // 1) nS, D, ONPLANE,
        // 2) pS, ONPLANE, D.
        PhantomTriangle *pt1 = new PhantomTriangle( *(nS[0]), i1.point, *(on[0]), pTri->tri ) ;
        PhantomTriangle *pt2 = new PhantomTriangle( *(pS[0]), *(on[0]), i1.point, pTri->tri ) ;
        if( pt1->isDegenerate() || pt2->isDegenerate() )
        {
          // This is a very important error to catch, because it happens
          // when something is terribly screwed up.
          window->addSolidDebugTri( pTri, Vector(1,0,0) ) ;
          error( "split fail." ) ;
          delete pt1 ; delete pt2 ;
          ++iter ;
          continue ;
        }
        newTris.push_back( pt1 ) ;
        newTris.push_back( pt2 ) ;
      }
      else 
      {
        // 2 points on nSide
        // We cut 2 edges.

        // if there are 2 nsides, use nS[1] and pS[0]. If 2 psides, nS[0],ps[1].

        // get the side with 2 verts on it
        Vector** sideWith2 = (pSide>nSide)?pS:nS;
        Vector** sideWith1 = (pSide<nSide)?pS:nS;
        
        // Get the second intersection point, from sideWith2[1] to sidewith1[0]
        Ray r2( *(sideWith2[1]), *(sideWith1[0]) ) ;
        Intersection i2 ;
        plane.intersectsPlane( r2, &i2 ) ;

        // 3 tris.
        //      *   
        //     / \
        //    /___\  
        //   / __/ \ 
        //  /_/     \ 
        // *---------*
        //
        // LET D be mi1.point, E mi2.point
        // 1)  sw2[0],D,E
        // 2)  sw2[0],E,sw2[1]
        // 3)  E,D,sw1[0]
        PhantomTriangle *pt1 = new PhantomTriangle( *(sideWith2[0]), i1.point, i2.point, pTri->tri ) ;
        PhantomTriangle *pt2 = new PhantomTriangle( *(sideWith2[0]), i2.point, *(sideWith2[1]), pTri->tri ) ;
        PhantomTriangle *pt3 = new PhantomTriangle( i2.point, i1.point, *(sideWith1[0]), pTri->tri ) ;
        if( pt1->isDegenerate() || pt2->isDegenerate() || pt3->isDegenerate() )
        {
          // This is a very important error to catch, because it happens
          // when something is terribly screwed up.
          window->addSolidDebugTri( pTri, Vector(1,0,0) ) ;
          error( "split fail." ) ; // split fail.
          delete pt1 ; delete pt2 ; delete pt3 ;
          ++iter ;
          continue ;
        }
        newTris.push_back( pt1 ) ;
        newTris.push_back( pt2 ) ;
        newTris.push_back( pt3 ) ;
      }

      // destroy the old PhantomTriangle that got split,
      // we don't need it anymore.
      DESTROY( *iter ) ;
      iter = toSplit.erase( iter ) ; // ADVANCES ITER
    }
    else
    {
      // Here you cannot split the polygon, either because 
      // all 3 are on one side, or one is on the plane and the
      // other 2 are on the same side.
      // I mean this is not a big deal and it is expected to happen a lot,
      // because a lot of tris you try to split will be on one side of the plane,
      // more rarely all 3 verts will be IN the plane.

      // if it does happen then like ASUS RMA you get the same triangle back.
      ///info( "Could not split the polygon, pSide=%d, nSide=%d, onPlane=%d", pSide, nSide, onPlane ) ;
      ++iter ; // advance iterator
    }
  }

  // Splits fail a lot, because this gets called 3x per division.
  ////info( "%d tris became %d tris, %d remain", origTris, newTris.size(), toSplit.size() ) ;
}
Example #28
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

	//MessageBox(NULL,"start","start",MB_OK);
	OutputDebugString("start stars");
/*	HANDLE mutex;
	char name[9] = "stars v4";
	name[8] = 0;
	mutex = CreateMutex(NULL,TRUE,name);
	if(GetLastError() == ERROR_ALREADY_EXISTS) return 0;
	//MessageBox(NULL,"mutex","mutex",MB_OK);
	OutputDebugString("created mutex");*/

	
	GetModuleFileName(NULL,path,256);
	path[_tcslen(path) - 12] = 0;
		done = false;
	srand(GetTickCount());
	MSG msg;

	if(strlen(lpCmdLine) == 0)
	{
		check_input = true;
		SystemParametersInfo(SPI_SETSCREENSAVERRUNNING,TRUE,0,0);
		width = GetSystemMetrics(SM_CXSCREEN); 
		height = GetSystemMetrics(SM_CYSCREEN);

 	// TODO: Place code here.
		WNDCLASS wc;
		wc.style = 0;
		wc.lpfnWndProc = WndProcsaver;
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hInstance = hInstance;
		wc.hIcon = LoadIcon(hInstance,NULL/*MAKEINTRESOURCE(IDI_ICON1)*/);
		wc.hCursor = LoadCursor(NULL,IDC_ARROW);
		wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
		wc.lpszMenuName = NULL;
		wc.lpszClassName = _T("STARS V4EXE");
		RegisterClass(&wc);
	
		hwndm = CreateWindowEx(0/*WS_EX_TOPMOST*/,_T("STARS V4EXE"),NULL,WS_POPUP,0,0,width,height,NULL,NULL,hInstance,NULL);
			if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		ShowWindow(hwndm,SW_SHOW);
		SetFocus(hwndm);
		
		ShowCursor(false);
		
		HPTSetWindow(hInstance,hwndm);
		LoadRegistry();
		
		gengine = GetHPTGraphicsEngine(quality,widescreen);
		gengine->BeginFrame();
		gengine->Position(0.4f*width,0.4f*height);
		(*gengine) << "Loading Stars Version 4!!!";
		gengine->EndFrame();

		if(texturequality == 0) gengine->LoadHGF(hptstrcat(path,"low texture pack.hgf"));
		if(texturequality == 1) gengine->LoadHGF(hptstrcat(path,"med texture pack.hgf"));
		if(texturequality == 2) gengine->LoadHGF(hptstrcat(path,"high texture pack.hgf"));
	}
	else
	{
		if(lpCmdLine[0] != 'f')
		{
			check_input = false;
			HWND hwndt;
			sscanf(lpCmdLine,"%d",&hwndt);
			RECT rc; GetWindowRect(hwndt,&rc);
			int cx=rc.right-rc.left, cy=rc.bottom-rc.top;
			width = cx;
			width = cy;
			WNDCLASS wc;
			wc.style = 0;
			wc.lpfnWndProc = WndProcsaver;
			wc.cbClsExtra = 0;
			wc.cbWndExtra = 0;
			wc.hInstance = hInstance;
			wc.hIcon = LoadIcon(hInstance,NULL/*MAKEINTRESOURCE(IDI_ICON1)*/);
			wc.hCursor = LoadCursor(NULL,IDC_ARROW);
			wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
			wc.lpszMenuName = NULL;
			wc.lpszClassName = _T("STARS V4EXE");
			RegisterClass(&wc);

			hwndm=CreateWindowEx(0,_T("STARS V4EXE"),NULL,WS_CHILD|WS_VISIBLE,
								  0,0,cx,cy,hwndt,NULL,hInstance,NULL);
			
			HPTSetWindow(hInstance,hwndm);
 
  
			starfielddensity = 100;

			planetsyn = false;
			framecounteryn = false;
			speed = 50 * 1000.0f;
			full_speed = 70 * 1000.0f;
			savecpu = true;
			quality = 0;

			gengine = GetHPTGraphicsEngine(quality,false);
			gengine->BeginFrame();
			gengine->Position(0.4f*width,0.4f*height);
			(*gengine) << "Loading Stars Version 4!!!";
			gengine->EndFrame();
			if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}

			Sleep(0);
			gengine->LoadHGF(hptstrcat(path,"preview texture pack.hgf"));
		}
		else
		{
			check_input = true;
			HWND hwndt;
			sscanf(lpCmdLine+1,"%d",&hwndt);
			width = GetSystemMetrics(SM_CXSCREEN); 
			height = GetSystemMetrics(SM_CYSCREEN);
			//RECT rc; GetWindowRect(hwndt,&rc);
			//int cx=rc.right-rc.left, cy=rc.bottom-rc.top;  
			WNDCLASS wc;
			wc.style = 0;
			wc.lpfnWndProc = WndProcsaver;
			wc.cbClsExtra = 0;
			wc.cbWndExtra = 0;
			wc.hInstance = hInstance;
			wc.hIcon = LoadIcon(hInstance,NULL/*MAKEINTRESOURCE(IDI_ICON1)*/);
			wc.hCursor = LoadCursor(NULL,IDC_ARROW);
			wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
			wc.lpszMenuName = NULL;
			wc.lpszClassName = _T("STARS V4EXE");
			RegisterClass(&wc);

			hwndm=CreateWindowEx(WS_EX_TOPMOST,_T("STARS V4EXE"),NULL,WS_CHILD|WS_VISIBLE|WS_POPUP,
								  0,0,width,height,hwndt,NULL,hInstance,NULL);
			ShowCursor(false);
			
			HPTSetWindow(hInstance,hwndm);
 
  
			//starfielddensity = 100;

			/*planetsyn = false;
			framecounteryn = false;
			speed = 50 * 1000.0f;
			full_speed = 70 * 1000.0f;
			savecpu = true;
			quality = 0;*/
			LoadRegistry();
			
			gengine = GetHPTGraphicsEngine(quality,widescreen);
			gengine->BeginFrame();
			gengine->Position(0.4f*width,0.4f*height);
			(*gengine) << "Loading Stars Version 4!!!";
			gengine->EndFrame();

			if(texturequality == 0) gengine->LoadHGF(hptstrcat(path,"low texture pack.hgf"));
			if(texturequality == 1) gengine->LoadHGF(hptstrcat(path,"med texture pack.hgf"));
			if(texturequality == 2) gengine->LoadHGF(hptstrcat(path,"high texture pack.hgf"));

		}
	}
		//	MessageBox(NULL,"init","init",MB_OK);
	OutputDebugString("init window");

		for(int count1 = 0;count1 < starfielddensity;count1++)
			stars.push_back(new Star);
		planet = new Planet;
		for(int count1 = 0;count1 < 200;count1++)
			for(list<Star*>::iterator tempsi= stars.begin();tempsi != stars.end();)
			{
				Star* tempstar;
				if((*tempsi)->movestarsetup(5000.0f))
				{
					tempstar = (*tempsi);
					tempsi = stars.erase(tempsi);
					stars.push_back(tempstar);
				}
				else
				{
					tempsi++;
				}
			}

		if(starfielddensity == 100)
			for(list<Star*>::iterator tempsi= stars.begin();tempsi != stars.end();tempsi++)
			{
				(*tempsi)->SetSizeMult(8);
			}
		time_to_next_state = ((rand()%5000)+1000)/1000.0f;
	/*	tempobject = gengine->Create3DObject();
		tempobject->Scale(60);
		tempobject->Position(-300,-150,800);
		tempobject->SetImage(0,1);
		tempobject->SetColor(1.1f,1.05f,0.70f,1);
		tempobject->Rotate(1.5f,0.5f);
*/
/*		tempobjectp = gengine->Create3DObjectP();
		tempobjectp->Scale(100);
		tempobjectp->Position(150,-100,500);
		tempobjectp->SkyPosition(0.1f);
		tempobjectp->SetImage(2,3);
		tempobjectp->SetColor(0.01f,0.01f,0.01f,0.0f);
		tempobjectp->SetLightVec(-1,0,-0.1f);
		tempobjectp->Rotate(2.4f,0.0f);
	*/	
	/*	tempobjectp2 = gengine->Create3DObjectP();
		tempobjectp2->Scale(100);
		tempobjectp2->Position(0,250,2000);
		tempobjectp2->SkyPosition(0.1f);
		tempobjectp2->SetImage(4,5);
		tempobjectp2->SetColor(0.01f,0.01f,0.01f,0.0f);
		tempobjectp2->SetLightVec(-0.2f,-1,-0.4f);
		tempobjectp2->Rotate(0,0.0f);
		tempobjectp2->AddRing(6);*/


		Music *musicobject;
		if(music)
		{
			musicobject = new Music(path);
		}
		QueryPerformanceFrequency(&timerfreq);
		QueryPerformanceCounter(&starttime);

		/*while(PeekMessage(&msg,NULL,WM_KEYDOWN,WM_KEYDOWN,PM_REMOVE) != 0)
		{
		};*/
	//MessageBox(NULL,"loop","loop",MB_OK);
		OutputDebugString("begin loop");
//		try
//		{
			while(!done)
			{
				//OutputDebugString("iterate");
				Iterate();
				if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
				{
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
			}
//		}
//		catch(...)
//		{
//			MessageBox(NULL,"unkown error","error",MB_OK);
//			exit(0);
//		}
	//	MessageBox(NULL,"error","error",MB_OK);
	//	tempobject->Release();
			if(music)
			{
				delete musicobject;
			}
	gengine->Release();
	delete planet;
	for(list<Star*>::iterator tempsi= stars.begin();tempsi != stars.end();)
	{
		Star* tempstar;
		tempstar = (*tempsi);
		tempsi = stars.erase(tempsi);
		delete tempstar;
	}
	ShowCursor(true);
	//ReleaseMutex(mutex);
	//CloseHandle(mutex);
	SystemParametersInfo(SPI_SETSCREENSAVERRUNNING,FALSE,0,0);

	return 0;
}
Example #29
0
/*
==================================================================
// This is winmain, the main entry point for Windows applications
==================================================================
*/
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	// Initialize the window
	if ( !initWindow( hInstance ) )
		return false;
	// called after creating the window
	if ( !d3dMgr->initD3DManager(wndHandle) )
		return false;
	if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice()))
		return false;

	// Grab the frequency of the high def timer
	__int64 freq = 0;				// measured in counts per second;
	QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
	float sPC = 1.0f / (float)freq;			// number of seconds per count

	__int64 currentTime = 0;				// current time measured in counts per second;
	__int64 previousTime = 0;				// previous time measured in counts per second;

	float numFrames   = 0.0f;				// Used to hold the number of frames
	float timeElapsed = 0.0f;				// cumulative elapsed time

	GetClientRect(wndHandle,&clientBounds);
	float fpsRate = 1000.0f/25.0f;
	/* initialize random seed: */
	srand ( (unsigned int)time(NULL) );

	D3DXVECTOR3 BalloonPos;
	/* generate random number of Balloons */
	int numBalloons = (50);
	D3DXVECTOR3 knightPos;
	POINT pknightPos;
	knightPos = D3DXVECTOR3((float)clientBounds.right/2-100,clientBounds.bottom-360,0);
	gKnight.push_back(new cKnight(knightPos,d3dMgr->getTheD3DDevice(),"Images\\KnightBodytwo.png"));
	for(int loop = 0; loop < numBalloons; loop++)
	{
		BalloonPos = D3DXVECTOR3(clientBounds.right/2-200+(loop*400),(float)clientBounds.bottom-100,0);
		aBalloon.push_back(new cBalloon(BalloonPos,d3dMgr->getTheD3DDevice(),"Images\\Platform.png"));
		aBalloon[loop]->setTranslation(D3DXVECTOR2(0.0f,0.0f));
	}


	LPDIRECT3DSURFACE9 aSurface;				// the Direct3D surface
	LPDIRECT3DSURFACE9 theBackbuffer = NULL;  // This will hold the back buffer
	
	D3DXVECTOR3 aBalloonPos;

	MSG msg;
	ZeroMemory( &msg, sizeof( msg ) );

	// Create the background surface
	aSurface = d3dMgr->getD3DSurfaceFromFile("Images\\SkyBackgroundSmall.png");

	while( msg.message!=WM_QUIT )
	{
		// Check the message queue
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) )
		{
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}
		else
		{
			// Game code goes here
			BalloonPos = D3DXVECTOR3(BalloonTrans.x,BalloonTrans.y,0);
			
			/*
			==============================================================
			| Update the postion of the Balloons and check for collisions
			==============================================================
			*/

			for(iter = aBalloon.begin(); iter != aBalloon.end(); ++iter)
			{
				
				(*iter)->update();			// update Balloon
				aBalloonPos = (*iter)->getSpritePos();  // get the position of the current Balloon
				/*
				==============================================================
				| Check for boundry collision and change Balloon direction
				==============================================================
				*/
				/*
				if ((*iter)->getTranslation().x>0 && aBalloonPos.x>(clientBounds.right - 60))
				{
					(*iter)->setTranslation(D3DXVECTOR2(-((*iter)->getTranslation().x), (*iter)->getTranslation().y ));

				}
				if((*iter)->getTranslation().x<0 && aBalloonPos.x<(clientBounds.left + 10))
				{
					(*iter)->setTranslation( D3DXVECTOR2(-((*iter)->getTranslation().x), (*iter)->getTranslation().y ));

				}
				if ((*iter)->getTranslation().y<0 && aBalloonPos.y<(clientBounds.top))
				{
					(*iter)->setTranslation(D3DXVECTOR2((*iter)->getTranslation().x ,-((*iter)->getTranslation().y )));

				}
				if((*iter)->getTranslation().y>0 && aBalloonPos.y>(clientBounds.bottom-60))
				{
					(*iter)->setTranslation(D3DXVECTOR2((*iter)->getTranslation().x ,-((*iter)->getTranslation().y )));
				}
				*/
				/*
				for(index = aBalloon.begin(); index != aBalloon.end(); ++index)
				{
					if ((*iter)->collidedWith((*iter)->getBoundingRect(),(*index)->getBoundingRect()))
					{
						// if a collision occurs change the direction of each Balloon that has collided
						//OutputDebugString("Collision!!");
						(*iter)->setTranslation((*iter)->getTranslation()*(-1));
						(*index)->setTranslation((*index)->getTranslation()*(-1));
					}
				}*/
			}


			QueryPerformanceCounter((LARGE_INTEGER*)&currentTime);
			float dt = (currentTime - previousTime)*sPC;

			// Accumulate how much time has passed.
			timeElapsed = dt+timeElapsed;
			if(timeElapsed > fpsRate)
			{
				d3dMgr->beginRender();
				theBackbuffer = d3dMgr->getTheBackBuffer();
				d3dMgr->updateTheSurface(aSurface, theBackbuffer);
				d3dMgr->releaseTheBackbuffer(theBackbuffer);

				d3dxSRMgr->beginDraw();
				for(iter = aBalloon.begin(); iter != aBalloon.end(); ++iter)
				{
					d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix());  
					d3dxSRMgr->drawSprite((*iter)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF);
				}
				d3dxSRMgr->endDraw();
					
				d3dxSRMgr->beginDraw();
				list<cKnight*>::iterator bite = gKnight.begin();
				int frog=0;
				while(bite != gKnight.end())
				{
						(*bite)->setSpritePos(knightPos);
						(*bite)->update(dt);
						d3dxSRMgr->setTheTransform((*bite)->getSpriteTransformMatrix());  
						d3dxSRMgr->drawSprite((*bite)->getTexture(),&((*bite)->getSourceRect()),NULL,NULL,0xFFFFFFFF);
						++bite;
						int sexy;
						int frisky;
						float gravity=315;
						pknightPos.x = knightTrans.x;
						pknightPos.y = knightTrans.y;
						for(iter = aBalloon.begin(); iter != aBalloon.end(); ++iter)
						{
							/*sexy=(clientBounds.right/2+(frog*400));
							frisky=(499+clientBounds.right/2+(frog*400));
							if (BalloonPosition>sexy&&BalloonPosition<frisky){gravity=0;}*/
							if(((*iter)->insideRect((*iter)->getBoundingRect(),pknightPos)))
							{
								gravity = 0;
							}
							frog++; 
						}
						if (knightPos.y<(clientBounds.bottom-gravity)){knightTrans.y += 30;}
						knightPos = D3DXVECTOR3(knightTrans.x,knightTrans.y,0);
						

				}
				list<cExplosion*>::iterator iter = gExplode.begin();
				while(iter != gExplode.end())
				{
					if((*iter)->isActive() == false)
					{
						iter = gExplode.erase(iter);
						}
					else
					{
						(*iter)->update(dt);
						d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix());  
						d3dxSRMgr->drawSprite((*iter)->getTexture(),&((*iter)->getSourceRect()),NULL,NULL,0xFFFFFFFF);
						++iter;
					}

				}
				previousTime = currentTime;
				d3dxSRMgr->endDraw();
				
			}
			d3dMgr->endRender();
			
		}
	}
	d3dxSRMgr->cleanUp();
	d3dMgr->clean();
	return (int) msg.wParam;
}
Example #30
0
//-----------------------------------------------------------------------------
// <OnNotification>
// Callback that is triggered when a value, group or node changes
//-----------------------------------------------------------------------------
void OnNotification
(
	Notification const* _notification,
	void* _context
)
{
	// Must do this inside a critical section to avoid conflicts with the main thread
	pthread_mutex_lock( &g_criticalSection );

	switch( _notification->GetType() )
	{
		case Notification::Type_ValueAdded:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// Add the new value to our list
				nodeInfo->m_values.push_back( _notification->GetValueID() );
			}
			break;
		}

		case Notification::Type_ValueRemoved:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// Remove the value from out list
				for( list<ValueID>::iterator it = nodeInfo->m_values.begin(); it != nodeInfo->m_values.end(); ++it )
				{
					if( (*it) == _notification->GetValueID() )
					{
						nodeInfo->m_values.erase( it );
						break;
					}
				}
			}
			break;
		}

		case Notification::Type_ValueChanged:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// One of the node values has changed
				// TBD...
			}
			break;
		}

		case Notification::Type_Group:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// One of the node's association groups has changed
				// TBD...
			}
			break;
		}

		case Notification::Type_NodeAdded:
		{
			// Add the new node to our list
			NodeInfo* nodeInfo = new NodeInfo();
			nodeInfo->m_homeId = _notification->GetHomeId();
			nodeInfo->m_nodeId = _notification->GetNodeId();
			nodeInfo->m_polled = false;		
			g_nodes.push_back( nodeInfo );
			break;
		}

		case Notification::Type_NodeRemoved:
		{
			// Remove the node from our list
			uint32 const homeId = _notification->GetHomeId();
			uint8 const nodeId = _notification->GetNodeId();
			for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it )
			{
				NodeInfo* nodeInfo = *it;
				if( ( nodeInfo->m_homeId == homeId ) && ( nodeInfo->m_nodeId == nodeId ) )
				{
					g_nodes.erase( it );
					break;
				}
			}
			break;
		}

		case Notification::Type_NodeEvent:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				// We have received an event from the node, caused by a
				// basic_set or hail message.
				// TBD...
			}
			break;
		}

		case Notification::Type_PollingDisabled:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo->m_polled = false;
			}
			break;
		}

		case Notification::Type_PollingEnabled:
		{
			if( NodeInfo* nodeInfo = GetNodeInfo( _notification ) )
			{
				nodeInfo->m_polled = true;
			}
			break;
		}

		case Notification::Type_DriverReady:
		{
			g_homeId = _notification->GetHomeId();
			break;
		}
	}

	pthread_mutex_unlock( &g_criticalSection );
}