Пример #1
0
CNode* VariableEliminator::eliminate_mod_temps(CNode* node, set<VariableTerm*>&
		to_eliminate)
{
	set<VariableTerm*> new_vars;
	set<VariableTerm*>::iterator it = to_eliminate.begin();
	for(; it!= to_eliminate.end(); it++)
	{
		VariableTerm* old_t = *it;
		string fresh_name = ELIMINATE_PREFIX + int_to_string(fresh_var_counter++);
		VariableTerm* new_t = (VariableTerm*)VariableTerm::make(fresh_name);
		map<Term*, Term*> subs;
		subs[old_t] = new_t;
		node = node->substitute(subs);
		new_vars.insert(new_t);
	}

	set<VariableTerm*>::iterator it2 = new_vars.begin();
	for(; it2!= new_vars.end(); it2++) {
		node = eliminate_var(node, *it2);
	}
	return node;
}
Пример #2
0
 void cPlayerPoints::Add_Points(unsigned int points, float x, float y, std::string strtext, const Color& color, bool allow_multiplier)
 {
     if (allow_multiplier)
     {
         points = static_cast<unsigned int>(pPlayer->kill_multiplier * static_cast<float>(points));
     }
     
     Set_Points(pPlayer->points + points);
     
     if (x == 0 || y == 0 || m_points_objects.size() > 50)
     {
         return;
     }
     
     if (strtext.empty())
     {
         strtext = int_to_string(points);
     }
     
     PointsText* new_obj = new PointsText();
     new_obj->Set_Image(pFont->Render_Text(pFont->m_font_small, strtext, color), 1, 1);
     
     new_obj->Set_Pos(x, y);
     new_obj->m_vely = -1.4f;
     new_obj->m_points = points;
     
     for (PointsTextList::iterator itr = m_points_objects.begin(); itr != m_points_objects.end(); ++itr)
     {
         PointsText* obj = (*itr);
         
         if (new_obj->m_rect.Intersects(obj->m_col_rect))
         {
             new_obj->Move(obj->m_col_rect.m_w + 5, 0, 1);
         }
     }
     
     m_points_objects.push_back(new_obj);
 }
Пример #3
0
std::string last_to_str(int last) {
    std::string str;
    char faces[] = { 'f', 'b', 'r', 'l', 't', 'd' };

    switch (last % 3) {
        case 0:
            str = "+";
            break;
        case 1:
            str = "-";
            break;
        case 2:
            str = "|";
            break;
        case -1:
            return "  ";
        default:
            error("last_to_str | last % 3 = " + int_to_string(last % 3), __LINE__, __FILE__);
            throw -1;
    }

    return faces[last / 3] + str;
}
void lcd_menu_edit_setting()
{
    if (lcd_lib_encoder_pos < lcd_setting_min)
        lcd_lib_encoder_pos = lcd_setting_min;
    if (lcd_lib_encoder_pos > lcd_setting_max)
        lcd_lib_encoder_pos = lcd_setting_max;

    if (lcd_setting_type == 1)
        *(uint8_t*)lcd_setting_ptr = lcd_lib_encoder_pos;
    else if (lcd_setting_type == 2)
        *(uint16_t*)lcd_setting_ptr = lcd_lib_encoder_pos;
    else if (lcd_setting_type == 3)
        *(float*)lcd_setting_ptr = float(lcd_lib_encoder_pos) / 100.0;
    else if (lcd_setting_type == 4)
        *(int32_t*)lcd_setting_ptr = lcd_lib_encoder_pos;
    else if (lcd_setting_type == 5)
        *(uint8_t*)lcd_setting_ptr = lcd_lib_encoder_pos * 255 / 100;
    else if (lcd_setting_type == 6)
        *(float*)lcd_setting_ptr = float(lcd_lib_encoder_pos) * 60;
    else if (lcd_setting_type == 7)
        *(float*)lcd_setting_ptr = float(lcd_lib_encoder_pos) * 100;
    else if (lcd_setting_type == 8)
        *(float*)lcd_setting_ptr = float(lcd_lib_encoder_pos);

    lcd_lib_clear();
    lcd_lib_draw_string_centerP(20, lcd_setting_name);
    char buffer[16];
    if (lcd_setting_type == 3)
        float_to_string(float(lcd_lib_encoder_pos) / 100.0, buffer, lcd_setting_postfix);
    else
        int_to_string(lcd_lib_encoder_pos, buffer, lcd_setting_postfix);
    lcd_lib_draw_string_center(30, buffer);
    lcd_lib_update_screen();

    if (lcd_lib_button_pressed)
        lcd_change_to_menu(previousMenu, previousEncoderPos);
}
Пример #5
0
 void cPath::Save_To_Stream(ofstream& file)
 {
     file << "\t<path>" << std::endl;
     
     file << "\t\t<Property name = \"posx\" value = \"" << static_cast<int>(m_start_pos_x) << "\" />" << std::endl;
     file << "\t\t<Property name = \"posy\" value = \"" << static_cast<int>(m_start_pos_y) << "\" />" << std::endl;
     
     file << "\t\t<Property name = \"identifier\" value = \"" << string_to_xml_string(m_identifier) << "\" />" << std::endl;
     file << "\t\t<Property name = \"rewind\" value=\"" << m_rewind << "\" />" << std::endl;
     
     unsigned int count = segments.size();
     
     for (unsigned int pos = 0; pos < count; pos++)
     {
         std::string str_pos = int_to_string(pos);
         
         file << "\t\t<Property name=\"" << "segment_" + str_pos + "_x1" << "\" value=\"" << segments[pos].m_x1 << "\" />" << std::endl;
         file << "\t\t<Property name=\"" << "segment_" + str_pos + "_y1" << "\" value=\"" << segments[pos].m_y1 << "\" />" << std::endl;
         file << "\t\t<Property name=\"" << "segment_" + str_pos + "_x2" << "\" value=\"" << segments[pos].m_x2 << "\" />" << std::endl;
         file << "\t\t<Property name=\"" << "segment_" + str_pos + "_y2" << "\" value=\"" << segments[pos].m_y2 << "\" />" << std::endl;
     }
     
     file << "\t</path>" << std::endl;
 }
static void lcd_menu_material_settings_store()
{
    uint8_t count = eeprom_read_byte(EEPROM_MATERIAL_COUNT_OFFSET());
    if (count == EEPROM_MATERIAL_SETTINGS_MAX_COUNT)
        count--;
    lcd_scroll_menu(PSTR("PRESETS"), 2 + count, lcd_menu_material_settings_store_callback, lcd_menu_material_settings_store_details_callback);

    if (lcd_lib_button_pressed)
    {
        if (!IS_SELECTED_SCROLL(0))
        {
            uint8_t idx = SELECTED_SCROLL_MENU_ITEM() - 1;
            if (idx == count)
            {
                char buffer[9] = "CUSTOM";
                int_to_string(idx - 1, buffer + 6);
                eeprom_write_block(buffer, EEPROM_MATERIAL_NAME_OFFSET(idx), 8);
                eeprom_write_byte(EEPROM_MATERIAL_COUNT_OFFSET(), idx + 1);
            }
            lcd_material_store_material(idx);
        }
        lcd_change_to_menu(lcd_menu_material_settings, SCROLL_MENU_ITEM_POS(6));
    }
}
Пример #7
0
	void process( array * base ) {
		if ( base->k * 2 >= MAXK ) {
			return;
		}

		if ( base->t != 3 ) {
			return;
		}

		// first, try this array is the main array
		array * subarray = getBestArray( base->k, base->v, 2 );

		int l = 2;
		bool toobig = false;

		if ( subarray != NULL ) {
			while ( !toobig ) {	
				array * leftover = getBestArray( l, base->v, 3 );

				if ( leftover != NULL ) {
					int pdcan = PDCAN( l, base->v );

					array * arr = new array();
					arr->N = base->N + pdcan * subarray->N + leftover->N;
					arr->k = base->k * l;
					arr->v = base->v;
					arr->t = 3;

					arr->type = 'C';
					arr->source = id;

					arr->ingredients.push_back( base );
					arr->ingredients.push_back( cleanCopy(subarray) );
					arr->ingredients.push_back( leftover );

					std::string value;
					int_to_string( l, value );
					arr->parameters[ "l" ] = value;

					int_to_string( pdcan, value );
					arr->parameters[ "pdcan" ] = value;

					insertArray( arr );
				}

				if ( (l * base->k) >= MAXK ) {
					toobig = true;
				}

				l++;				
			}

			deleteIfRule(subarray);
		}		

		// then, try it as the leftover array
		array * prev = getPreviousArray( base );

		int minL = prev != NULL ? prev->k + 1 : 2;

		fullSortTableType arrays;
		query( arrays, 3, 3, base->v, base->v, 0, (MAXK / l) * 3 );

		// TODO: step through PDCANs

		bool end = false;

		int pdV = PDCAN_v( base->v );

		l = pdV;
		while ( !end ) {
			l *= pdV;

			if ( l < minL )
				continue;

			if ( l >= base->k ) {
				l = base->k;
				end = true;
			}
			
			int deadV = 2;

			fullSortTableType::const_iterator superIt;
			for ( superIt = arrays.begin(); superIt != arrays.end(); superIt++ ) {
				array * superarray = *superIt;
					
				if ( superarray->v <= deadV ) {
					continue;
				}

				array * subarray = getBestArray( superarray->k, superarray->v, 2 );

				if ( subarray != NULL ) {
					int pdcan = PDCAN( l, base->v );

					array * arr = new array();
					arr->N = superarray->N + pdcan * subarray->N + base->N;
					arr->k = superarray->k * l;
					arr->v = superarray->v;
					arr->t = 3;

					arr->type = 'C';
					arr->source = id;

					arr->ingredients.push_back( superarray );
					arr->ingredients.push_back( subarray );
					arr->ingredients.push_back( base );

					std::string value;
					int_to_string( l, value );
					arr->parameters[ "l" ] = value;

					int_to_string( pdcan, value );
					arr->parameters[ "pdcan" ] = value;

					insertArray( arr, &arrays );

					if ( arr->k >= MAXK ) {
                        deadV = arr->v;
					}
				}

			}
		}	
	}
static void lcd_menu_material_export()
{
    if (!card.sdInserted)
    {
        LED_GLOW();
        lcd_lib_encoder_pos = MAIN_MENU_ITEM_POS(0);
        lcd_info_screen(lcd_menu_material_select);
        lcd_lib_draw_string_centerP(15, PSTR("No SD-CARD!"));
        lcd_lib_draw_string_centerP(25, PSTR("Please insert card"));
        lcd_lib_update_screen();
        card.release();
        return;
    }
    if (!card.isOk())
    {
        lcd_info_screen(lcd_menu_material_select);
        lcd_lib_draw_string_centerP(16, PSTR("Reading card..."));
        lcd_lib_update_screen();
        card.initsd();
        return;
    }

    card.setroot();
    card.openFile("MATERIAL.TXT", false);
    uint8_t count = eeprom_read_byte(EEPROM_MATERIAL_COUNT_OFFSET());
    for(uint8_t n=0; n<count; n++)
    {
        char buffer[32];
        strcpy_P(buffer, PSTR("[material]\n"));
        card.write_string(buffer);

        strcpy_P(buffer, PSTR("name="));
        char* ptr = buffer + strlen(buffer);
        eeprom_read_block(ptr, EEPROM_MATERIAL_NAME_OFFSET(n), 8);
        ptr[8] = '\0';
        strcat_P(buffer, PSTR("\n"));
        card.write_string(buffer);

        strcpy_P(buffer, PSTR("temperature="));
        ptr = buffer + strlen(buffer);
        int_to_string(eeprom_read_word(EEPROM_MATERIAL_TEMPERATURE_OFFSET(n)), ptr, PSTR("\n"));
        card.write_string(buffer);

#if TEMP_SENSOR_BED != 0
        strcpy_P(buffer, PSTR("bed_temperature="));
        ptr = buffer + strlen(buffer);
        int_to_string(eeprom_read_word(EEPROM_MATERIAL_BED_TEMPERATURE_OFFSET(n)), ptr, PSTR("\n"));
        card.write_string(buffer);
#endif

        strcpy_P(buffer, PSTR("fan_speed="));
        ptr = buffer + strlen(buffer);
        int_to_string(eeprom_read_byte(EEPROM_MATERIAL_FAN_SPEED_OFFSET(n)), ptr, PSTR("\n"));
        card.write_string(buffer);

        strcpy_P(buffer, PSTR("flow="));
        ptr = buffer + strlen(buffer);
        int_to_string(eeprom_read_word(EEPROM_MATERIAL_FLOW_OFFSET(n)), ptr, PSTR("\n"));
        card.write_string(buffer);

        strcpy_P(buffer, PSTR("diameter="));
        ptr = buffer + strlen(buffer);
        float_to_string(eeprom_read_float(EEPROM_MATERIAL_DIAMETER_OFFSET(n)), ptr, PSTR("\n\n"));
        card.write_string(buffer);

#ifdef USE_CHANGE_TEMPERATURE
        strcpy_P(buffer, PSTR("change_temp="));
        ptr = buffer + strlen(buffer);
        float_to_string(eeprom_read_word(EEPROM_MATERIAL_CHANGE_TEMPERATURE(n)), ptr, PSTR("\n\n"));
        card.write_string(buffer);
        
        strcpy_P(buffer, PSTR("change_wait="));
        ptr = buffer + strlen(buffer);
        float_to_string(eeprom_read_byte(EEPROM_MATERIAL_CHANGE_WAIT_TIME(n)), ptr, PSTR("\n\n"));
        card.write_string(buffer);
#endif
    }
    card.closefile();

    currentMenu = lcd_menu_material_export_done;
}
Пример #9
0
void ip_address::set_port(unsigned port)
{
	port_ = int_to_string(port);
}
Пример #10
0
// -----------------------------------------------------------------------------
//  Modify the Header line of the ANG file if necessary
// -----------------------------------------------------------------------------
std::string Hex2SqrConverter::modifyAngHeaderLine(char* buf, size_t length)
{
  std::string line = "";
  if (buf[0] != '#')
  {
    line = buf;
    m_HeaderIsComplete = true;
    return line;
  }
  // Start at the first character and walk until you find another non-space character
  size_t i = 1;
  while(buf[i] == ' ')
  {
    ++i;
  }
  size_t wordStart = i;
  size_t wordEnd = i+1;
  while(1)
  {
    if (buf[i] == 45 || buf[i] == 95) { ++i; } // "-" or "_" character
    else if (buf[i] >= 65 && buf[i] <=90) { ++i; } // Upper case alpha character
    else if (buf[i] >= 97 && buf[i] <=122) {++i; } // Lower case alpha character
    else { break;}
  }
  wordEnd = i;

  std::string word( &(buf[wordStart]), wordEnd - wordStart);

  if (word.size() == 0)
  {
    line = buf;
    return line;
  }
  if (word.compare(Ebsd::Ang::Grid) == 0)
  {
    line = "# " + word + ": SqrGrid";
  }
  else if (word.compare(Ebsd::Ang::XStep) == 0)
  {
    line = "# " + word + ": " + float_to_string(m_XResolution);
  }
  else if (word.compare(Ebsd::Ang::YStep) == 0)
  {
    line = "# " + word + ": " + float_to_string(m_YResolution);
  }
  else if (word.compare(Ebsd::Ang::NColsOdd) == 0)
  {
    line = "# " + word + ": " + int_to_string(m_NumCols);
  }
  else if (word.compare(Ebsd::Ang::NColsEven) == 0)
  {
    line = "# " + word + ": " + int_to_string(m_NumCols);
  }
  else if (word.compare(Ebsd::Ang::NRows) == 0)
  {
    line = "# " + word + ": " + int_to_string(m_NumRows);
  }
  else
  {
    line = buf;
  }
  return line;
}
Пример #11
0
std::string SocketConnection::to_string() {
	return int_to_string(connfd);
}
Пример #12
0
/*****************************************************************************
* void main(void)
*
* Main application.
*
* In:  n/a
*
* Out: n/a
*****************************************************************************/
void main(void)
{
  UInt16 state;
  char *temp_ptr;
  extern word _vba;
  uint8_t sw0, sw1;
  
  
  INTC_VBA = ((word)&_vba) >> (21-INTC_VBA_BITS);			   /* Set Vector Base Address */
  
  /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/
  PE_low_level_init();
  /*** End of Processor Expert internal initialization.                    ***/
    
    /*StartDelay = pmem_read((unsigned int *)BOOT_START_DELAY_PLACE) & 0x00FF;
    if(!StartDelay)  bootExit();
    else bootTimerInit();*/ 
   
    /* Write your code here */

   GPIO_A_PER &= ~GPIO_A_PER_PE0_MASK; // set to GPIO mode
   GPIO_A_PER &= ~GPIO_A_PER_PE1_MASK;
   GPIO_A_DDR |= GPIO_A_DDR_DD0_MASK;  // set as output
   GPIO_A_DDR |= GPIO_A_DDR_DD1_MASK;
   GPIO_A_DR &= ~GPIO_A_DR_D0_MASK;  // set low
   GPIO_A_DR &= ~GPIO_A_DR_D1_MASK; 			
			    
    Cpu_Delay100US(5000); // power-up delay
  
   // Initialize R0,R1,M01, and N for circular buffer (including shadows)
   asm {
        swap shadows                    ;// Switch to shadow registers
        moveu.w #(RX_DATA_SIZE-1),M01   ;// Set buffer size
        moveu.w #rx_data,R0             ;// Set starting address
        moveu.w #QSCI_STAT,R1           ;// Use R1 for SCI status register
        moveu.w #0,N                    ;// N is unused
        swap shadows                    ;// Switch back to normal registers
   }

		// with DEFCON 17, we used a timer to keep the badge in bootloader mode on power up for 10 seconds
		// for DEFCON 18, the bootloader mode is only enabled if both buttons are held down on power up
		// otherwise it jumps directly to the user application. no timer necessary, so that code is commented out
		
		// check buttons
   GPIO_C_PUR |= GPIO_C_PUR_PU0_MASK; // enable pull-up
   GPIO_C_PUR |= GPIO_C_PUR_PU1_MASK;   
   GPIO_C_DDR &= ~GPIO_C_DDR_DD0_MASK; // set as input
   GPIO_C_DDR &= ~GPIO_C_DDR_DD1_MASK;
   GPIO_C_PER &= ~GPIO_C_PER_PE0_MASK; // set to GPIO mode
   GPIO_C_PER &= ~GPIO_C_PER_PE1_MASK;
   Cpu_Delay100US(1000); // setup delay
   
   #define SW0_PIN_MASK       ((byte)1) /* Pin mask */
   #define SW1_PIN_MASK       ((byte)2) /* Pin mask */
	 sw0 = !((bool)(getRegBits(GPIO_C_RAWDATA,SW0_PIN_MASK)));
   sw1 = !((bool)(getRegBits(GPIO_C_RAWDATA,SW1_PIN_MASK)));

   if (sw0 || sw1) // one or more buttons has been pressed
	 {
		 Cpu_Delay100US(1000); 	// give the user time to press both buttons (also serves as 100mS debounce)

	 	 sw0 = !((bool)(getRegBits(GPIO_C_RAWDATA,SW0_PIN_MASK)));
     sw1 = !((bool)(getRegBits(GPIO_C_RAWDATA,SW1_PIN_MASK)));
	 }
	
   if (sw0 && sw1) // if both buttons have been pressed, enter bootloader
   {
     // Turn on LEDs so the user knows we're here
     GPIO_A_DR |= GPIO_A_DR_D0_MASK;  // set high
   	 GPIO_A_DR |= GPIO_A_DR_D1_MASK;  
   
	   // Initialize globals
	   mem_init(rx_data, NULL, RX_DATA_SIZE);
	   data_out = data_in = rx_data; 
	   
	   state = INITIAL_STATE;
	   temp_ptr = rx_data;

	   // Disable protection
	   setReg(FM_PROT,BOOT_PROT_VALUE);

	   // Output banner
	   sci_tx(&StrCopyright[0]);
	   
	   // Now it is safe to enable interrupts
	   Cpu_EnableInt();

	   do  {
	      // State: Initial State
	      if (state == INITIAL_STATE) {
	         status = 0;
	         sci_tx(&StrWaitingSrec[0]);
	         sci_tx_char(XON);
	         state = WAIT_FOR_S;
	      }

	      if (data_in != temp_ptr) {
	         //Timer_Disable();

	         // State: Wait for Header "S"
	         if (state == WAIT_FOR_S) {
	            temp_ptr = data_out;
	            if (get_char(&temp_ptr) == 'S') { state = WAIT_FOR_0; }
	            else { get_char(&data_out); }
	         }
	         // State: Wait for Header "0"
	         else if (state == WAIT_FOR_0) {
	            if (get_char(&temp_ptr) == '0') { state = WAIT_FOR_EOL; }
	            else {
	               get_char(&data_out);
	               state = WAIT_FOR_S;
	            }
	         }
	         // State: Wait for EOL
	         else if (state == WAIT_FOR_EOL) {
	            if (get_char(&temp_ptr) == '\r') {
	               if (!(status & TX_XOFF)) {
	                  sci_tx_char(XOFF);
	                  status |= TX_XOFF;
	               }
	               srec_decode();
	               temp_ptr = data_out;
	            }
	         }
	      }
	      else {
	         if (status & TX_XOFF) {
	            sci_tx_char(XON);
	            status &= ~TX_XOFF;
	         }
	      }
	      // State: Error
	      if (status & DOWNLOAD_ERROR) {
	         sci_tx(StrErr);
	         sci_tx(int_to_string(status));
	         state = INITIAL_STATE;
	         sci_tx(StrNewLine);
	      }
	      
	      //bootTimerCheck();
	      
	   } while (status != DOWNLOAD_OK);
	   
	   sci_tx(StrNewLine); 
	   sci_tx(&StrLoaded[0]);
   }
   
   bootExit();
}
Пример #13
0
void Legami::leggi(vector<string>* v)
{
	vector<User*>* vu = new vector<User*>;

	// aggiungo gli user senza la lista contatti e gruppi
	for(unsigned int i=0; i< v->size()-1; ++i)
	{
		// l'ultima riga e' per i gruppi
		string ruolo = tag((*v)[i], "<ruolo>", "</ruolo>");

		// all'interno del tag User ci sono nick, password e profilo dello user
		// ma non i gruppi o i collegamenti, perchè devo prima popolare la base
		// di dati con tutti gli user per garantire uno stato consistente del db
		string s = tag((*v)[i], "<user>", "</user>");
		User* user = User::leggi(s);

		// ora leggo il profilo dello user
		s = tag((*v)[i], "<profilo>", "</profilo>");
		Profilo* p = Profilo::leggi(s);

		// collego il profilo allo user
		user->profilo = p;

		// aggiungo lo user nel db
		if(ruolo == "base")
			vu->push_back(user);

		else if(ruolo == "business")
			vu->push_back(new BusinessUser(*user));

		else if(ruolo == "executive")
			vu->push_back(new ExecutiveUser(*user));
	}

	// assegno il db all'oggetto di legami
	database = vu;

	// collegamenti
	for(unsigned int i=0; i < v->size()-1; ++i)
	{
		string s = (*v)[i];

		string c = tag(s, "<collegamenti>", "</collegamenti>");
		int num_coll = string_to_int(tag(c, "<numeroColl>", "</numeroColl>"));

		for(int j = 0; j < num_coll; ++j)
		{
			string t = tag(c, "<C" + int_to_string(j+1) + ">", "</C" + int_to_string(j+1) + ">");
			string n = tag(t, "<nick>", "</nick>");
			string ta = tag(t, "<tag>", "</tag>");
			// cerco lo user con quel nick per aggiungere il puntatore al vettore dei collegamenti
			for(unsigned int k=0; k<database->size(); ++k)
			{
				if( ((*database)[k])->getNick() == n )
					((*database)[i])->insertContatto(new Contatto( ((*database)[k]), ta) );
			}
		}
	}

	// gruppi (sono alla fine del file)

	string s = (*v)[v->size()-1];

	string group = tag(s, "<gruppi>", "</gruppi>");
	if(!group.empty())
	{
		int num_gr = string_to_int( tag(group, "<numeroGr>", "</numeroGr>"));

		for(int i = 0; i<num_gr; ++i)
		{
			// i-esimo gruppo
			string t = tag(group,	"<G" + int_to_string(i+1) + ">", "</G" + int_to_string(i+1) + ">");

			string nomegr = tag(t, "<nomeGr>", "</nomeGr>");

			string descgr = tag(t, "<descGr>", "</descGr>");

			int numeroMembri = string_to_int(tag(t, "<numeroMembri>", "</numeroMembri>"));

			Gruppo* g = new Gruppo(nomegr, descgr, new vector<User*>);

			for(int j=0; j<numeroMembri; ++j)
			{
				// j-esimo membro dell'i-esimo gruppo
				string w = tag(t, "<" + int_to_string(j+1) + ">", "</" + int_to_string(j+1) + ">");

				string nick = tag(w, "<nick>", "</nick>");

				// cerco lo user con quel nick
				for(unsigned int k=0; k<database->size(); ++k)
				{
					if( ((*database)[k])->getNick() == nick )
					{
						// aggiungo lo user alla lista degli appartenenti al gruppo
						g->aggiungi((*database)[k]);
						// aggiungo il gruppo alla lista dei gruppi dello user
						((*database)[k])->insertGruppo(g);
					}
				}
			}
		}
	}

}
string copy_file(string title, const char *dirfrom, const char *dirto, const char *filename, double filesize, double copy_currentsize, double copy_totalsize, int numfiles_current, int numfiles_total, int check_flag, int showprogress)
{
	string cfrom=(string)dirfrom+(string)filename;
	string ctoo=(string)dirto+(string)filename;
	FILE *from, *to;
	string ret="";
	double percent=copy_currentsize/copy_totalsize*100, oldpercent=percent, changepercent=0, current_copy_size=0;
	string current;
	string sfilename=(string)filename;
	string scurrent_files=int_to_string(numfiles_current);
	string stotal_files=int_to_string(numfiles_total);
	string stotal_size=convert_size(copy_totalsize, "auto");

	PF.printf((title+" '"+sfilename+"'\r\n").c_str());
	PF.printf(("- source: "+cfrom+" \r\n").c_str());
	PF.printf(("- dest: "+ctoo+" \r\n").c_str());

	if ((from = fopen(cfrom.c_str(), "rb"))==NULL) return "Cannot open source file ("+cfrom+") for reading!";
	if (check_flag!=1)
	{
		char* buf = (char*) calloc (1, CHUNK+1);
		size_t size;
		if ((to = fopen(ctoo.c_str(), "wb"))==NULL) return "Cannot open destination file ("+ctoo+") for writing!";
		do
		{
			//draw_copy(title, dirfrom, dirto, filename, cfrom, copy_currentsize, copy_totalsize, numfiles_current, numfiles_total, countsize);
			size = fread(buf, 1, CHUNK, from);
			if(ferror(from)) return "Error reading source file ("+cfrom+")!";
			fwrite(buf, 1, size, to);
			if (ferror(to)) return "Error writing destination file ("+ctoo+")!";
			
			if (showprogress==0)
			{
				current_copy_size=current_copy_size+(double)size;
				percent=(copy_currentsize+current_copy_size)/copy_totalsize*100;
				changepercent=percent-oldpercent;
				current="Processing "+scurrent_files+" of "+stotal_files+" files ("+convert_size(copy_currentsize+current_copy_size, "auto")+"/"+stotal_size+")";
				//PF.printf((" "+int_to_string((int)percent)+"%% "+current+" \r\n").c_str());
				//PF.printf((" change"+int_to_string((int)changepercent)+"%% real"+int_to_string((int)percent)+"%% "+current+" \r\n").c_str());
				Mess.ProgressBarDialogFlip();
				if (changepercent>1)
				{
					Mess.SingleProgressBarDialogChangeMessage(current.c_str());
					Mess.ProgressBarDialogFlip();
					Mess.SingleProgressBarDialogIncrease(changepercent);
					Mess.ProgressBarDialogFlip();
					oldpercent=percent-(changepercent-(int)changepercent);
				}
			}
		}
		while(!feof(from));
		free(buf);
	}
	else
	{
		char* buf = (char*) calloc (1, CHUNK+1);
		char* buf2 = (char*) calloc (1, CHUNK+1);
		size_t size, size2;
		if ((to = fopen(ctoo.c_str(), "rb"))==NULL) return "Cannot open destination file ("+ctoo+") for reading!";
		do
		{
			size = fread(buf, 1, CHUNK, from);
			if(ferror(from)) return "Error reading source file ("+cfrom+")!";
			size2 = fread(buf2, 1, CHUNK, to);
			if (ferror(to)) return "Error reading destination file ("+ctoo+")!";
			if (size != size2) return "Source and destination files have different sizes!";
			if (memcmp(buf, buf2, size)!=0) return "Source and destination files are different!";

			if (showprogress==0)
			{
				current_copy_size=current_copy_size+(double)size;
				percent=(copy_currentsize+current_copy_size)/copy_totalsize*100;
				changepercent=percent-oldpercent;
				current="Processing "+scurrent_files+" of "+stotal_files+" files ("+convert_size(copy_currentsize+current_copy_size, "auto")+"/"+stotal_size+")";
				//PF.printf((" "+int_to_string((int)percent)+"%% "+current+" \r\n").c_str());
				//PF.printf((" change"+int_to_string((int)changepercent)+"%% real"+int_to_string((int)percent)+"%% "+current+" \r\n").c_str());
				Mess.ProgressBarDialogFlip();
				if (changepercent>1)
				{
					Mess.SingleProgressBarDialogChangeMessage(current.c_str());
					Mess.ProgressBarDialogFlip();
					Mess.SingleProgressBarDialogIncrease((int)changepercent);
					Mess.ProgressBarDialogFlip();
					oldpercent=percent-(changepercent-(int)changepercent);
				}
			}
		}
		while(!feof(from) || !feof(to));
		free(buf);
		free(buf2);
	}

	if (fclose(from)==EOF) return "Cannot close source file ("+cfrom+")!";
	if (fclose(to)==EOF) return "Cannot close destination file ("+ctoo+")!";

	return "";
}
Пример #15
0
string AstInt::to_string(int d) {
    return get_depth(d) + "INT: " + int_to_string(this->i) + "\n";
}
Пример #16
0
size_t simple_vsnprintf(char *buf, size_t size, const char *format, va_list va)
{
  char *s = NULL;
  char *fp = (char *) format;
  size_t c = 0;
  unsigned long i = 0;
  long width = 0;
  bool islong = 0, caps = false, width_modifier = false, rpad = false;
  char pad = ' ';

re_eval:
  while (*fp && c < size - 1) {
    if (*fp == '%' || width_modifier) {
re_eval_with_modifier:
      ++fp;
      if (unlikely(width_modifier)) {
        if (egg_isdigit(*fp)) {
          width = 10 * width + (*fp - '0');
          goto re_eval;
        } else
          width_modifier = false;
      }

      switch (*fp) {
      /* Left padding with zeroes */
      case '0':
        width_modifier = true;
        pad = '0';
        goto re_eval_with_modifier;
      /* Right padding with spaces */
      case '-':
        rpad = true;
        goto re_eval_with_modifier;
      /* Left padding with spaces */
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
        width_modifier = true;
        width = 10 * width + (*fp - '0');
        pad = ' ';
        goto re_eval_with_modifier;
      case 'z':
      case 'l':
        islong = 1;
        goto re_eval_with_modifier;
      case '^': //STRING
        caps = true;
        goto re_eval_with_modifier;
      case 's': //string
        s = va_arg(va, char *);
        break;
      case 'd': //int
      case 'i':
        if (islong) {
          i = va_arg(va, long);
          islong = 0;
        } else
          i = va_arg(va, int);
        s = int_to_string(i, 10);
        break;
      case 'D': //stupid eggdrop base64
        i = va_arg(va, int);
        s = int_to_base64((unsigned int) i);
        break;
      case 'u': //unsigned
        if (islong) {
          i = va_arg(va, unsigned long);
          islong = 0;
        } else
          i = va_arg(va, unsigned int);
        s = unsigned_int_to_string(i, 10);
        break;
      case 'X': //HEX
        caps = true;
      case 'x': //hex
        if (islong) {
          i = va_arg(va, unsigned long);
          islong = 0;
        } else
Пример #17
0
void Usermanage::push_offline_line(int fd){
    int found = this->find_user("fd", int_to_string(fd));

    if(found != -1 && this->users[found].is_online())
        this->users[found].send_offline_message();
}
Пример #18
0
void Usermanage::setcolor(int fd, int color){
    int found = this->find_user("fd", int_to_string(fd));

    if(found != -1)
        this->users[found].setcolor(color);
}
Пример #19
0
   int read_atom_data(int *p_ichar, int *p_num_atoms, int at_end,
                      int num_of_chars, int *p_next_mol, atom *p_atom,
                      int *p_mol_number)

{
int is_end,idummy,place,itsanum,iloop,ndigi,sign;
int idum[10], igroup;
char *p_key;

/* check for end of molecule or file */
 
 p_key= "end";
 is_end= locate_string( p_key, p_ichar, num_of_chars);

 if (is_end && !at_end )
   {
/* first end encountered for a while, just end of molecule */
 
     (*p_next_mol)++;
     return 1;
   }
 else if (is_end && at_end )
   {
/* the end of the atom list */

     return 2;
   }
 else
   {
/* a normal atom data line */

/* copy over atom name */

   copy_int( p_ichar, &idum[0], 0, 3); 
   int_to_string(&idum[0], &(p_atom->label[0]), 4);

/* get x,y,z co-ordinates */

      place= 1;
      place= next_space (p_ichar, place, num_of_chars );

      p_atom->x = get_doub(p_ichar, num_of_chars, &place, &itsanum);
      p_atom->y = get_doub(p_ichar, num_of_chars, &place, &itsanum);
      p_atom->z = get_doub(p_ichar, num_of_chars, &place, &itsanum);

/* get group label */ 

      place= next_none_space( p_ichar, place, num_of_chars );

      if (place == -1 )
	{
       printf("Read error whilst trying to get the group from car file line:");
       put_string(stdout, p_ichar,200);
       return -1;
         }
      
       copy_int( p_ichar, &idum[0], place, place+3); 
       int_to_string(&idum[0],&(p_atom->group[0]), 4);

       place= next_space (p_ichar, place, num_of_chars );

/******* Get the group number, which can contain a string!! ***********/

      place++;

      if (place == -1 )
        {
       printf("Read error whilst trying to get the group number from car file line:");
       put_string(stdout, p_ichar,200);
       return -1;
         }

       copy_int( p_ichar, &idum[0], place, place+3);
       int_to_string(&idum[0],&(p_atom->group_no[0]), 4);

       place= next_space (p_ichar, place, num_of_chars );

/* get potential type */

      place= next_none_space( p_ichar, place, num_of_chars );

      if (place == -1 )
	{
       printf("Read error whilst trying to get the potential type from car file line:");
       put_string(stdout, p_ichar,200);
       return -1;
         }

       copy_int( p_ichar, &idum[0], place, place+2);
       int_to_string( &idum[0], &(p_atom->pot[0]), 2);

       place= next_space (p_ichar, place, num_of_chars );

/* get element type */

      place= next_none_space( p_ichar, place, num_of_chars );

      if (place == -1 )
	{
       printf("Read error whilst trying to get the element type from car file line:");
       put_string(stdout,p_ichar,200);
       return -1;
         }

       copy_int( p_ichar, &idum[0], place, place+1); 
       int_to_string( &idum[0], &(p_atom->elem[0]), 2);

       if (p_atom->elem[1] == ' ') p_atom->elem[1] = '\0';

       place= next_space (p_ichar, place, num_of_chars );

/* get partial charge */

       p_atom->part_chge= get_doub(p_ichar, num_of_chars, &place, &itsanum);

       if (!itsanum)
         {
            printf("Failed to find partial charge on car file line: \n");
            put_string(stdout, p_ichar,200);
         }

/* sort out molecule number and increment atom counter */

      *p_mol_number= *p_next_mol; 
      (*p_num_atoms)++;

      return 0;
   }
 
     
}
Пример #20
0
/******************************************************************************
 * BrowseAction
 *****************************************************************************/
static int
BrowseOrSearchAction (ContentDir* cds,
		      void* result_context,
		      const char* objectId, 
		      const char* criteria,
		      Index starting_index,
		      Count requested_count,
		      Count* nb_matched,
		      Count* nb_returned,
		      PtrArray* objects)
{
	if (cds == NULL || objectId == NULL || criteria == NULL) {
		Log_Printf (LOG_ERROR, 
			    "BrowseOrSearchAction NULL parameter");
		return UPNP_E_INVALID_PARAM; // ---------->
	}
	
	// Create a working context for temporary allocations
	void* tmp_ctx = talloc_new (NULL);
	
	const bool browse = is_browse (criteria);
	IXML_Document* doc = NULL;
	int rc = Service_SendActionVa
		(OBJECT_SUPER_CAST(cds), &doc, 
		 (browse ? "Browse" : "Search"),
		 (browse ? "ObjectID" : "ContainerID"),		objectId,
		 (browse ? "BrowseFlag" : "SearchCriteria"),	criteria,
		 "Filter", 	      "*",
		 "StartingIndex",     int_to_string (tmp_ctx, starting_index),
		 "RequestedCount",    int_to_string (tmp_ctx, requested_count),
		 "SortCriteria",      "",
		 NULL, 		      NULL);
	if (doc == NULL && rc == UPNP_E_SUCCESS)
		rc = UPNP_E_BAD_RESPONSE;
	if (rc != UPNP_E_SUCCESS) {
		Log_Printf (LOG_ERROR, "BrowseOrSearchAction ObjectId='%s'",
			    NN(objectId));
		goto cleanup; // ---------->
	}
	
	const char* s = XMLUtil_FindFirstElementValue 
		(XML_D2N (doc), "TotalMatches", true, true);
	STRING_TO_INT (s, *nb_matched, 0);
	
	s = XMLUtil_FindFirstElementValue 
		(XML_D2N (doc), "NumberReturned", true, true);
	STRING_TO_INT (s, *nb_returned, 0);
	
	Log_Printf (LOG_DEBUG, "+++BROWSE RESULT+++\n%s\n", 
		    XMLUtil_GetDocumentString (tmp_ctx, doc));
	
	const char* const resstr = XMLUtil_FindFirstElementValue
		(XML_D2N (doc), "Result", true, true);
	if (resstr == NULL) {
		Log_Printf (LOG_ERROR, "BrowseOrSearchAction ObjectId=%s : "
			    "can't get 'Result' in doc=%s",
			    objectId, 
			    XMLUtil_GetDocumentString (tmp_ctx, doc));
		rc = UPNP_E_BAD_RESPONSE;
		goto cleanup; // ---------->
	}

	IXML_Document* const subdoc = 
		ixmlParseBuffer (discard_const_p (char, resstr));
	if (subdoc == NULL) {
		Log_Printf (LOG_ERROR, "BrowseOrSearchAction ObjectId=%s : "
			    "can't parse 'Result'=%s", objectId, resstr);
		rc = UPNP_E_BAD_RESPONSE;
	} else {
		IXML_NodeList* containers = ixmlDocument_getElementsByTagName
			(subdoc, "container"); 
		ContentDir_Count const nb_containers = 
			ixmlNodeList_length (containers);
		IXML_NodeList* items =
			ixmlDocument_getElementsByTagName (subdoc, "item"); 
		ContentDir_Count const nb_items = ixmlNodeList_length (items);
		if (nb_containers + nb_items != *nb_returned) {
			Log_Printf (LOG_ERROR, 
				    "BrowseOrSearchAction ObjectId=%s "
				    "got %d containers + %d items, "
				    "expected %d", objectId, 
				    (int) nb_containers, (int) nb_items,
				    (int) *nb_returned);
			*nb_returned = nb_containers + nb_items;
		}
		if (criteria == CRITERIA_BROWSE_METADATA && *nb_returned != 1){
			Log_Printf (LOG_ERROR, "ContentDir_Browse Metadata : "
				    "not 1 result exactly ! Id=%s", 
				    NN(objectId));
		}

		ContentDir_Count i; 
		for (i = 0; i < *nb_returned; i++) {
			bool const is_container = (i < nb_containers);
			IXML_Element* const elem = (IXML_Element*) 
				ixmlNodeList_item
				(is_container ? containers : items, 
				 is_container ? i : i - nb_containers);
			DIDLObject* o = DIDLObject_Create (result_context, 
							   elem, is_container);
			if (o) {
				PtrArray_Append (objects, o);
			}
		}
		
		if (containers)
			ixmlNodeList_free (containers);
		if (items)
			ixmlNodeList_free (items);
		ixmlDocument_free (subdoc);
	}
	
 cleanup:
	
	ixmlDocument_free (doc);
	doc = NULL;
	
	// Delete all temporary storage
	talloc_free (tmp_ctx);
	tmp_ctx = NULL;
	
	if (rc != UPNP_E_SUCCESS)
		*nb_returned = *nb_matched = 0;
	
	return rc;
}
Пример #21
0
string AstInt::to_value() {
	return int_to_string(this->i);
}
Пример #22
0
// central dispatcher of all url requests arriving at the webserver
// returns true, if request has been dispatched within dispatch. Otherwise the caller
// should assume that static content is to be displayed.
bool  CommandDispatcher::dispatch(string uri, string query, string body, string &response, bool &okOrNOk) {

	response = "";
	string urlPath = getPath(uri);

	vector<string> urlParamName;
	vector<string> urlParamValue;

	compileURLParameter(query,urlParamName,urlParamValue);

	// check if direct cortex command defined via URL parameter
	// example: /cortex/LED?blink
	if (hasPrefix(uri, "/cortex")) {
		LOG(DEBUG) << uri << " " << query;

		string cmd = uri.substr(string("/cortex/").length());
		for (int i = 0;i<CommDefType::NumberOfCommands;i++) {
			string cortexCmdStr = string(commDef[i].name);
			if (hasPrefix(cmd, cortexCmdStr)) {
				string command = string(commDef[i].name);
				// are there any parameters ?
				if (query.length() > 0) {
					std::istringstream iss(query);
					std::string token;
					while (std::getline(iss, token, '&'))
					{
						// extract name and value of parameter
						int equalsIdx = token.find("=");
						if (equalsIdx > 0) {
							string name = token.substr(0,equalsIdx);
							string value = token.substr(equalsIdx+1);
							command += " " + name + "=" + value;
						} else {
							command += " " + token;
						}
					}
				};
				LOG(DEBUG) << "calling cortex with \"" << command << "\"";
				string cmdReply;
				TrajectoryExecution::getInstance().directAccess(command, cmdReply, okOrNOk);

				if (cmdReply.length() > 0)
					response += cmdReply + "";
				if (okOrNOk)
					response += "ok";
				else
					response += "failed";
				return true;
			}
		}
	}

	// check, if cortex is called via one command string
	// example /direct?param=LED+blink
	if (hasPrefix(uri, "/direct")) {
		if (hasPrefix(query, "param=")) {
			LOG(DEBUG) << uri << " " << query;

			string cmd = urlDecode(query.substr(string("param=").length()));
			LOG(DEBUG) << "calling cortex with \"" << cmd << "\"";
			string cmdReply;

			TrajectoryExecution::getInstance().directAccess(cmd, cmdReply, okOrNOk);
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response += s.str();
			return true;
		}
	}

	// check, if TransactionExecutor is called with orchestrated calls
	if (hasPrefix(uri, "/executor/")) {
		string executorPath = uri.substr(string("/executor/").length());

		if (hasPrefix(executorPath, "startupbot")) {
			LOG(DEBUG) << uri << " " << query;


			okOrNOk =  TrajectoryExecution::getInstance().startupBot();
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response = s.str();
		}
		else if (hasPrefix(executorPath, "teardownbot")) {
			LOG(DEBUG) << uri << " " << query;


			okOrNOk = TrajectoryExecution::getInstance().teardownBot();
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response = s.str();
			return true;
		}
		else if (hasPrefix(executorPath, "nullpositionbot")) {
			LOG(DEBUG) << uri << " " << query;


			okOrNOk = TrajectoryExecution::getInstance().moveToNullPosition();
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response = s.str();
			return true;
		}
		else if (hasPrefix(executorPath, "isupandrunning")) {
			response = "";
			bool result = TrajectoryExecution::getInstance().isBotUpAndReady();
			okOrNOk = true;
			response = result?"true":"false";
			return true;
		}
		else if (hasPrefix(executorPath, "emergencystop")) {
			LOG(DEBUG) << uri << " " << query;


			response = "";
			bool result = TrajectoryExecution::getInstance().emergencyStopBot();
			okOrNOk = true;
			response = result?"true":"false";
			return true;
		}
		else if (hasPrefix(executorPath, "setangles")) {
			LOG(DEBUG) << uri << " " << query;


			string param = urlDecode(query.substr(string("param=").length()));
			okOrNOk = TrajectoryExecution::getInstance().setAnglesAsString(param);
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response = s.str();
			return true;
		}
		else if (hasPrefix(executorPath, "getangles")) {
			LOG(DEBUG) << uri << " " << query;

			int indent = 0;
			response  = TrajectoryExecution::getInstance().currentTrajectoryNodeToString(indent);
			okOrNOk = !isError();
			return true;
		}
		else if (hasPrefix(executorPath, "settrajectory")) {
			LOG(DEBUG) << uri << " " << query;

			string param = urlDecode(body);
			LOG(DEBUG) << "body:" << param;

			TrajectoryExecution::getInstance().runTrajectory(param);
			okOrNOk = !isError();
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response += s.str();
			return true;
		}
		else if (hasPrefix(executorPath, "stoptrajectory")) {
			LOG(DEBUG) << uri << " " << query;


			TrajectoryExecution::getInstance().stopTrajectory();
			okOrNOk = !isError();
			std::ostringstream s;
			if (okOrNOk) {
				s << "OK";
			} else {
				s << "NOK(" << getLastError() << ") " << getErrorMessage(getLastError());
			}
			response = s.str();
			return true;
		}

	}

	if (hasPrefix(uri, "/web")) {
		string keyValue;
		if (getURLParameter(urlParamName, urlParamValue, "key", keyValue)) {
			if (keyValue.compare(string("cortexcmd")) == 0) {
				if (getURLParameter(urlParamName, urlParamValue, "from", keyValue)) {
					int from = string_to_int(keyValue);
					if (from >=0 )
						response = getCmdLineJson(from+1);
					else
						response = getCmdLineJson(0);
				} else
					response = getCmdLineJson(0);
				okOrNOk = true;
				return true;
			} else {
				if (keyValue.compare(string("cortexlog")) == 0) {
					if (getURLParameter(urlParamName, urlParamValue, "from", keyValue)) {
						int from = string_to_int(keyValue);
						if (from >=0)
							response = getLogLineJson(from+1);
						else
							response = getLogLineJson(0);
					} else
						response = getLogLineJson(0);
					okOrNOk = true;
					return true;
				} else {
					if (keyValue.compare(string("alert")) == 0) {
						if (getURLParameter(urlParamName, urlParamValue, "from", keyValue)) {
							int from = string_to_int(keyValue);
							if (from >=0) {
								response = getAlertLineJson(from);
								okOrNOk = true;
								return true;
							}
						} else {
							response = int_to_string(alertCounter);
							okOrNOk = true;
							return true;
						}
					}
					else {
						if (keyValue.compare(string("heartbeat")) == 0) {
							response = getHeartbeatJson();
							okOrNOk = true;
							return true;
						}
					}
				}
			}
		} else {
			if (getURLParameter(urlParamName, urlParamValue, "action", keyValue)) {
				if (keyValue.compare("savecmd") == 0) {
					LOG(DEBUG) << uri << " " << query;


					string value;
					if (getURLParameter(urlParamName, urlParamValue, "value", value)) {
						string cmdReply;
						TrajectoryExecution::getInstance().directAccess(value, cmdReply, okOrNOk);
						response = cmdReply;
						return true;
					}
				}
			}
		}
	}

	okOrNOk = false;
	return false;
}
Пример #23
0
bool Process::start() {

#ifdef WIN32

	handle_IN_Rd = NULL;
	handle_IN_Wr = NULL;
	handle_OUT_Rd = NULL;
	handle_OUT_Wr = NULL;
	handle_ERR_Rd = NULL;
	handle_ERR_Wr = NULL;

	p_stdin = -1;
	p_stdout = -1;
	p_stderr = -1;

	SECURITY_ATTRIBUTES saAttr; 

	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
	saAttr.bInheritHandle = TRUE; 
	saAttr.lpSecurityDescriptor = NULL; 

	// Create a pipe for the child process's STDOUT. 
   if ( ! CreatePipe(&handle_OUT_Rd, &handle_OUT_Wr, &saAttr, 0) ) 
      return false; 

	// Create a pipe for the child process's STDERR. 
   if ( ! CreatePipe(&handle_ERR_Rd, &handle_ERR_Wr, &saAttr, 0) ) 
      return false; 

    // Create a pipe for the child process's STDIN. 
    if (! CreatePipe(&handle_IN_Rd, &handle_IN_Wr, &saAttr, 0)) 
        return false; 

    if (explicit_mode) {
 
        if ( ! SetHandleInformation(handle_IN_Rd, HANDLE_FLAG_INHERIT, 1) )
            return false; 

        if ( ! SetHandleInformation(handle_OUT_Wr, HANDLE_FLAG_INHERIT, 1) )
            return false; 

    } 

    // Ensure the write handle to the pipe for STDIN is not inherited.  
    if ( ! SetHandleInformation(handle_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
        return false; 

    // Ensure the read handle to the pipe for STDOUT is not inherited.
    if ( ! SetHandleInformation(handle_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
        return false; 

    // Ensure the read handle to the pipe for STDERR is not inherited.
    if ( ! SetHandleInformation(handle_ERR_Rd, HANDLE_FLAG_INHERIT, 0) )
        return false; 


	STARTUPINFO siStartInfo;
	BOOL bSuccess = FALSE; 
 
	// Set up members of the PROCESS_INFORMATION structure. 
 
	ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
 

	stringstream cmdbuffer;
	int curargument = 0;
	while (arguments[curargument]) {
		cmdbuffer << "\"" << arguments[curargument] << "\" ";
		curargument++;
	}


	stringstream envbuffer;
    map<string, string>::iterator iter;
    for (iter = env.begin(); iter != env.end(); ++iter) {
        envbuffer << iter->first << string("=") << iter->second << '\0';
    }

	// Set up members of the STARTUPINFO structure. 
	// This structure specifies the STDIN and STDOUT handles for redirection.
	ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
	siStartInfo.cb = sizeof(STARTUPINFO); 
    if (!explicit_mode) {
	    siStartInfo.hStdError = handle_ERR_Wr;
	    siStartInfo.hStdOutput = handle_OUT_Wr;
	    siStartInfo.hStdInput = handle_IN_Rd;
        siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
    } else {
	    siStartInfo.hStdError = handle_ERR_Wr;
		HANDLE pHandle = GetCurrentProcess();
		HANDLE handle_IN_Rd2, handle_OUT_Wr2;
		DuplicateHandle(pHandle, handle_IN_Rd, pHandle, &handle_IN_Rd2, DUPLICATE_SAME_ACCESS, true, DUPLICATE_SAME_ACCESS);
		DuplicateHandle(pHandle, handle_OUT_Wr, pHandle, &handle_OUT_Wr2, DUPLICATE_SAME_ACCESS, true, DUPLICATE_SAME_ACCESS);
        envbuffer << string("TRAX_IN=") << handle_IN_Rd2 << '\0';
        envbuffer << string("TRAX_OUT=") << handle_OUT_Wr2 << '\0';
    }
	
    envbuffer << '\0';
	
	LPCSTR curdir = directory.empty() ? NULL : directory.c_str();

	if (!CreateProcess(NULL, (char *) cmdbuffer.str().c_str(), NULL, NULL, true, 0,
		(void *)envbuffer.str().c_str(),
		curdir, &siStartInfo, &piProcInfo )) {

		std::cout << "Error: " << GetLastError()  << std::endl;
		cleanup();
		return false;
	}

	int wrfd = _open_osfhandle((intptr_t)handle_IN_Wr, 0);
	int rdfd = _open_osfhandle((intptr_t)handle_OUT_Rd, _O_RDONLY);
	int erfd = _open_osfhandle((intptr_t)handle_ERR_Rd, _O_RDONLY);

	if (wrfd == -1 || rdfd == -1) {
		stop();
		return false;
	}

    p_stdin = wrfd;
    p_stdout = rdfd;
    p_stderr = erfd;

	if (!p_stdin || !p_stdout) {
		stop();
		return false;
	}

#else

    if (pid) return false;

    pipe(out);
    pipe(in);
    pipe(err);

    vector<string> vars;

    map<string, string>::iterator iter;
    for (iter = env.begin(); iter != env.end(); ++iter) {
       // if (iter->first == "PWD") continue;
        vars.push_back(iter->first + string("=") + iter->second);
    }

    posix_spawn_file_actions_init(&action);
    posix_spawn_file_actions_addclose(&action, out[1]);
    posix_spawn_file_actions_addclose(&action, in[0]);
    posix_spawn_file_actions_addclose(&action, err[0]);

    if (!explicit_mode) {
        posix_spawn_file_actions_adddup2(&action, out[0], 0);
        posix_spawn_file_actions_adddup2(&action, in[1], 1);
        posix_spawn_file_actions_adddup2(&action, err[1], 2);
    } else {
        posix_spawn_file_actions_adddup2(&action, err[1], 2);
        vars.push_back(string("TRAX_OUT=") + int_to_string(in[1]));
        vars.push_back(string("TRAX_IN=") + int_to_string(out[0]));
    }

    std::vector<char *> vars_c(vars.size() + 1); 

    for (std::size_t i = 0; i != vars.size(); ++i) {
        vars_c[i] = &vars[i][0];
    }

    vars_c[vars.size()] = NULL;

    string cwd = __getcwd();

    if (directory.size() > 0)
        chdir(directory.c_str());

    if (posix_spawnp(&pid, program, &action, NULL, arguments, vars_c.data())) {
        cleanup();
        pid = 0;
        if (directory.size() > 0) chdir(cwd.c_str());
        return false;
    }

    if (directory.size() > 0) chdir(cwd.c_str());

    p_stdin = out[1];
    p_stdout = in[0];
    p_stderr = err[0];

#endif

    return true;

}
Пример #24
0
char* itos(int number)
{
    return int_to_string(number);
}
Пример #25
0
int main()
{

    // On aura TOUJOURS comme première fichier map "Map1.tmx" puis un nombre de map a définir

    string etatMap = "start";
    int nbMap = 20;

    // Tableau des différentes Maps
    vector<string> Maps;

    for(int i = 1; i < (nbMap + 1); i++)
    {
        string nomMap = "map/Map";
        nomMap.append(int_to_string(i));
        nomMap.append(".tmx");

        Maps.push_back(nomMap);

        //cout << "la map " << nomMap << " a ete pushe" << endl;
    }

    string Map_EnCours = Maps[0];


    unsigned int Map_Actuelle = 0;

    tile** Matrice;
    //tile** MatriceTest;



    //int LARGEUR_MAP = NbColonnes * LARGEUR_TILE;
    //int HAUTEUR_MAP = NbLignes * HAUTEUR_TILE;

    bool debugMode = true;



    // Fenêtre
    RenderWindow app(VideoMode((int)WINDOW_SIZE.x, (int)WINDOW_SIZE.y, 32), "Another : Beta v0.2");

	// Frames Per Second (FPS)
    //app.setFramerateLimit(60); // limite la fenêtre à 60 images par seconde

    // NE PAS mettre les deux en meme temps

    app.setVerticalSyncEnabled(true);

	Texture myTile, myEchelle, myBullet, myEnnemi, myEnnemi2, myPlayer, myPlayer2, lifeBonus,
	myEndBlock, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward;

	if (!myBullet.loadFromFile(SPRITES_FILE_PATH_BULLET)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myBullet.SetSmooth(false);
    }

	if (!myEnnemi.loadFromFile(SPRITES_FILE_PATH_ENNEMI)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myEnnemi.SetSmooth(false);
    }

	if (!myEnnemi2.loadFromFile(SPRITES_FILE_PATH_ENNEMI_2)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myEnnemi2.SetSmooth(false);
    }

	if (!myPlayer.loadFromFile(SPRITES_FILE_PATH_PLAYER)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myPlayer.SetSmooth(false);
    }

	if (!lifeBonus.loadFromFile(SPRITES_FILE_PATH_LIFEBONUS)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //lifeBonus.SetSmooth(false);
    }

	if (!myTile.loadFromFile("images/blocTerre.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myTile.SetSmooth(false);
    }

	if (!myEchelle.loadFromFile("images/blocEchelle.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myEchelle.SetSmooth(false);
    }

	if (!myEndBlock.loadFromFile("images/blocFin.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myEndBlock.SetSmooth(false);
    }

    if (!tileSet1.loadFromFile("map/tileset1.png")) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //tileSet1.SetSmooth(false);
    }

    if (!myInterrupteur.loadFromFile("images/interrupteur.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myInterrupteur.SetSmooth(false);
    }

    if (!myDoor.loadFromFile("images/porteCoulissante.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myDoor.SetSmooth(false);
    }

	if (!myCheckpoint.loadFromFile("images/checkpoint.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myCheckpoint.SetSmooth(false);
    }

    if (!reward.loadFromFile("images/reward.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //reward.SetSmooth(false);
    }

    vector<Bullet> vectorBullet;
	vector<Character> vectorCharacter;
	vector<Object*> vectorObject;




	// ====== Variable importante !! =======

//	int x = 150;
//	int y = 150;
	int controleSaut = false; /* Booléen qui va permettre de ne pas relancer un second saut avant d'avoir relaché la touche */
	float transparence = 0;
	float transparenceInverse = 255;
	Clock clockTempsMap;
	Clock clockFrame;
	bool startGame = false;
	bool changementDeMap = false;

	/*string etatMap = "start";

	// Tableau des différentes Maps
    vector<string> Maps;



    for(int i = 1; i < (nbMap + 1); i++)
    {
        string nomMap = "map/Map";
        nomMap.append(int_to_string(i));
        nomMap.append(".tmx");

        Maps.push_back(nomMap);

        //cout << "la map " << nomMap << " a ete pushe" << endl;
    }*/

	// =====================================
	// =====================================




	// Création et positionnement du joueur au lancement du jeu



	// =========================


	// Création d'une vue qui suivra les déplacements du joueur

	View vue = app.getDefaultView();
	View hud;

	// =========================================================

	// Création des barres de vie et d'énergie du joueur et du rectangle de fondu

    sf::RectangleShape hud1;
    hud1.setSize(sf::Vector2f(150, 140));
    hud1.setFillColor(sf::Color(190, 200, 200));
    hud1.setOutlineColor(sf::Color::Black);
    hud1.setOutlineThickness(1);

    sf::RectangleShape barLife;
    barLife.setSize(sf::Vector2f(50, 10));
    barLife.setFillColor(sf::Color::Red);
    barLife.setOutlineColor(sf::Color::Black);
    barLife.setOutlineThickness(1);

    sf::RectangleShape barPower;
    barPower.setSize(sf::Vector2f(50, 10));
    barPower.setFillColor(sf::Color(0, 150, 255));
    barPower.setOutlineColor(sf::Color::Black);
    barPower.setOutlineThickness(1);

    sf::RectangleShape fondu;
    fondu.setSize(sf::Vector2f(WINDOW_SIZE.x, WINDOW_SIZE.y));

	// ===============================================================
	// Menu

    menu(app, false, changementDeMap, hud, WINDOW_SIZE, startGame, Maps, Map_EnCours, Map_Actuelle);

    createMap(Map_EnCours, &Matrice, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward, vectorObject);

    int NbColonnes = nbColonnesMap(Map_EnCours);
    int NbLignes = nbLignesMap(Map_EnCours);

    int LARGEUR_TILE = largeurTileMap(Map_EnCours);
    int HAUTEUR_TILE = largeurTileMap(Map_EnCours);

    Player player(myPlayer, 0, 0, PLAYER_SPEED, "bleu", "normal");
	PlayerPosition(player, &Matrice, NbColonnes, NbLignes, LARGEUR_TILE, "depart");

	clockTempsMap.restart();

    cout << "Map en cours avant main" << Map_EnCours << endl;
    cout << "Map Actuelle avant main" << Map_Actuelle << endl;

    // Boucle principale
    while (app.isOpen())
    {
		// Remplissage de l'écran (couleur noire par défaut)
        app.clear();

        //vue.setSize(WINDOW_SIZE.x, WINDOW_SIZE.y);
        app.setView(vue);
        hud = app.getDefaultView();


        // On récupère le temps de rafraichissement entre chaque frame pour ajuster la vitesse du jeu
        float frameTime = clockFrame.restart().asSeconds();

        bool actionElement = false;

        // On modifier la valeur du temps de la map

        /*if(clockTempsMap.getElapsedTime().asSeconds() > 0.1f)
        {
            tempsMap += 0.1f;
            clockTempsMap.restart();
        }*/


		/* Gestion de l'affichage d'un certain nombre de tile autour du player, et non toute la map */

		int indexPlayerI = convertToIndex(player.getLeftSide(), LARGEUR_TILE);
		int indexPlayerJ = convertToIndex(player.getBottomSide(), LARGEUR_TILE);

		/* Les nombre en dessous permettent de déterminer la distance ou lon affiche la map autour du héro */

		float visionI = 20, visionJ = 10;

		int idPImoins = indexPlayerI - visionI;
		int idPIplus = indexPlayerI + visionI;
		int idPJmoins = indexPlayerJ - visionJ;
		int idPJplus = indexPlayerJ + visionJ;

		if(idPImoins < 0)
			idPImoins = 0;

		if(idPIplus > NbColonnes)
			idPIplus = NbColonnes;

		if(idPJmoins < 0)
			idPJmoins = 0;

		if(idPJplus > NbLignes)
			idPJplus = NbLignes;

        for(int j=idPJmoins; j<idPJplus; j++)
                for(int i=idPImoins; i<idPIplus; i++)
                    if(Matrice[i][j].spr != 0)
                        app.draw(*Matrice[i][j].spr);


		//=================================================



		/* REGENERATION du POWER */

		player.setPower(player.getPower() + 0.2f);

		if(player.getPower() > 100.0f)
			player.setPower(100.0f);

		if(player.getPower() < 0)
			player.setPower(0);

		if(player.getPower() > 50.0f)
			player.setSurchauffe(false);

		/* ===================== */



		/* == LIFE == */

		if(player.getLife() <= 100)
			player.upLife(0.05f);

		if(player.getLife() > 200.0f)
			player.setLife(200.0f);

		if(player.getLife() < 0)
			player.setLife(0);

		/* ===================== */



		// Dès que la vitesse descend en dessous de 0 alors le joueur n'est plus en saut

		if(player.getSpeedY() < 0)
			player.setEnSaut(false);

		/* ===================== */


		/* GRAVITE : On diminue la vitesse verticale si pas sur Terre */

		if(!player.surTerre()){

			player.setSpeedY(player.getSpeedY() - 30.0f);

			/* Effet de resistance de l'air */
			if((CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 1)
                || (CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 2)
            )
            {
                if(player.getSpeedY() < -400.0f)
                    player.setSpeedY(-400.0f);
            }
            else
            {
               if(player.getSpeedY() < -800.0f)
                    player.setSpeedY(-800.0f);
            }


		}

		/* ===================== */



		/* On enleve la GRAVITE lorsque l'on est au sol */

		if(player.surTerre()){
			player.setSpeedY(0);
		}

		/* ===================== */


		/* CLOCK du freeze Time */

		if(player.getFreeze()){

			if(player.getClockFreeze() > 1.5f){
				player.setFreeze(false);
				player.setSpeedY(0);
			}
		}

		// ======================

		Event event;

        while (app.pollEvent(event))
        {

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Space){

				//player.setEnSaut(false);
				controleSaut = false;
			}

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Down){

				player.setDescendre(false);
			}

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Right){

				player.setDeplacement(false);
				player.setMouvementDroite(false);
			}

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Left){

				player.setDeplacement(false);
				player.setMouvementGauche(false);
			}
			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::LShift){

				player.notShooting();
			}


            switch(event.type)
			{
				case Event::Closed : // Croix de fermeture
					app.close();
					break;

				case Event::KeyPressed : // Appui sur une touche
				{
					switch(event.key.code)
					{
						case Keyboard::Escape : // Touche echap

                            if(player.surTerre())
                            {
                                startGame = false;
                                menu(app, true, changementDeMap, hud, WINDOW_SIZE, startGame, Maps, Map_EnCours, Map_Actuelle);

                                if(changementDeMap)
                                {
                                    clockTempsMap.restart();
                                    player.setScore(0);

                                    deleteMatrice(&Matrice, NbColonnes, NbLignes, vectorObject);

                                    createMap(Map_EnCours, &Matrice, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward, vectorObject);

                                    NbColonnes = nbColonnesMap(Map_EnCours);
                                    NbLignes = nbLignesMap(Map_EnCours);

                                    PlayerPosition(player, &Matrice, NbColonnes, NbLignes, LARGEUR_TILE, "depart");


                                    changementDeMap = false;
                                }
                            }
                            else
                            {
                                cout << "Vous devez etre sur terre pour aller dans le menu. (En cas de probleme, sautez !)" << endl;
                            }
							break;

                        default:
                            break;
					}
				}



				default:
                    break;
			}


        }



        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
            if(!player.getMouvementDroite()){

                player.setMouvementGauche(true);

                if(!player.getFreeze()){
                //	if(!Matrice[mxGauche][myGauche].solid){
                        if(!player.getFreeze())
                            //if(player.getSpeed() > -15.0f)
                                player.deplacementGaucheX();

                //	}

                    player.setDeplacement(true);
                }

                player.setDirectionGauche();
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
            if(!player.getMouvementGauche()){

                player.setMouvementDroite(true);

                if(!player.getFreeze()){
                    //if(!Matrice[mxDroite][myDroite].solid){
                        if(!player.getFreeze())
                            //if(player.getSpeed() < 15.0f)
                                player.deplacementDroiteX();

                    //}

                    player.setDeplacement(true);
                }

                player.setDirectionDroite();
		    }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
        {
            if(!controleSaut && !player.getFreeze() && player.surTerre()){
					player.setSpeedY(650.0f);
					player.setEnSaut(true);
					controleSaut = true;
            }

            if(!controleSaut && !player.getFreeze() && !player.surTerre())
            {
                if(CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 1)
                {
                    player.setSpeedY(850.0f);
                    player.setSpeed(700.0f);
					player.setEnSaut(true);
					controleSaut = true;
                    //cout << "saut gauche" << endl;
                }
                else if(CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 2)
                {
                    player.setSpeedY(850.0f);
                    player.setSpeed(-700.0f);
					player.setEnSaut(true);
					controleSaut = true;
                    //cout << "saut droite" << endl;
                }
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            if(!player.getSurchauffe()){
				player.teleport();
				player.setFreeze(false);
			}
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
        {
            actionElement = true;
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::P))
        {
            etatMap = "end";
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z))
        {
            if(!player.getFreeze())
				player.freezeTime();
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
        {
            if(player.getClockBullet() > 0.2f){
				if(player.getDirection() == "droite"){
					vectorBullet.push_back(Bullet(myBullet, (player.getRightSide() - 10), (player.getTopSide() + 12.0f), (BULLET_SPEED * frameTime), player.getDirection(), player.getEquipe(), "ball"));
				}else if(player.getDirection() == "gauche"){
					vectorBullet.push_back(Bullet(myBullet, (player.getLeftSide() - 20), (player.getTopSide() + 12.0f), (BULLET_SPEED * frameTime), player.getDirection(), player.getEquipe(), "ball"));
				}

				player.resetClockBullet();
			}

            player.shootAnimation();
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        {
            player.setDescendre(true);
        }



		//	===================================================
		//  =============== AFFICHAGE DES TESTS ===============
		//	===================================================

		/*if(CollisionDecorPlafond(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice))
			cout << " COLLISION PLAFOND  " << endl;
		else
			cout << " PAS COLLISION PLAFOND  " << endl;

		if(CollisionDecorSol(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice))
			cout << " COLLISION SOL  " << endl;
		else
			cout << " PAS COLLISION SOL  " << endl;	*/


		/*if(player.surTerre())
			cout << " SUR TERRE  " << endl;
		else
			cout << " PAS SUR TERRE  " << endl;
*/
		//cout << player.getSpeed() << endl;
		/*
			cout << vectorCharacter.size() << endl;
			cout << vectorBullet.size() << endl;
			cout << vectorObject.size() << endl;*/


      // cout << "speed y :" << player.getSpeedY() << endl;



		//	===================================================


	//	===================================================


		/* Friction / Ralentissement de la vitesse latérale */

		if(!player.getDeplacement()){

			if(player.getSpeed() > 1500.0f){
				player.setSpeed(player.getSpeed() - 500.0f);
			}else if(player.getSpeed() < -1500.0f){
				player.setSpeed(player.getSpeed() + 500.0f);
			}

			if(player.getSpeed() > 0){
				if(player.getSpeed() < 150.00f){
					player.setSpeed(0);
				}
				else{
					player.setSpeed(player.getSpeed() - 50.00f);
				}

			}else if(player.getSpeed() < 0){
				if(player.getSpeed() > -150.0f){
					player.setSpeed(0);
				}
				else{
					player.setSpeed(player.getSpeed() + 50.00f);
				}
			}

		}

		/* Lorsque le joueur n'est pas Freeze on effectue les essai de mouvement sur X et Y pour on application la nouvelle position */

		if(!player.getFreeze()){

			EssaiDeplacementX(Matrice, frameTime, player, player.getSpeed(), LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorObject);

			if(EssaiDeplacementY(Matrice, frameTime, player, player.getSpeedY(), LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorObject)){

				// Si true, alors le joueur est en contact avec un bloc de fin de niveau
                cout << "ERREUR" << endl;
                cout << Map_Actuelle << " " << Map_EnCours << endl;
				etatMap = "end";
			}



			player.setPosition();

		}







		//	===========================================================================
		//  =========== Double boucle testant chaque balles si elle est en  ===========
		//	===========	collision avec un ennemi, un player, un mur ou rien ===========
		//	===========================================================================


		for(int unsigned i = 0; i < vectorBullet.size(); i++){

			if(CollisionBulletDecor(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorBullet[i], Matrice)){
					vectorBullet[i].kill();
				}

			if(vectorBullet[i].getDirection() == "droite"){
				vectorBullet[i].deplacementDroiteX();
			}else if(vectorBullet[i].getDirection() == "gauche"){
				vectorBullet[i].deplacementGaucheX();
			}

			vectorBullet[i].drawBullet(app);

			// Collision des balles et des ennemis
			for(int unsigned j = 0; j < vectorCharacter.size(); j++){

				float degatDeal;

				// On test si l'équipe de la balle est la meme que celle du character, si non, on peut tester la collision
				if(vectorBullet[i].getEquipe() != vectorCharacter[j].getEquipe()){
					if(!vectorBullet[i].isKilled()){
						if(CollisionBulletCharacter(vectorBullet[i], vectorCharacter[j])){

							degatDeal = vectorBullet[i].getDegat();
							vectorCharacter[j].downLife(degatDeal);

							vectorBullet[i].kill();
						}
					}
				}

			}

			// Collision des balles et des objet

            for(int unsigned j = 0; j < vectorObject.size(); j++){

                if(vectorObject[j]->getSolid()){

                    if(CollisionObjectBullet(vectorObject[j], vectorBullet[i])){
                        vectorBullet[i].kill();

                        if(vectorObject[j]->getBreakable()){
                           vectorObject[j]->kill();
                        }
                    }
                }
            }

			// Collision des balles et du joueur

			if(vectorBullet[i].getEquipe() != player.getEquipe()){
				if(!vectorBullet[i].isKilled()){
					if(CollisionBulletCharacter(vectorBullet[i], player)){

						float degatDeal = vectorBullet[i].getDegat();
						player.downLife(degatDeal);

						vectorBullet[i].kill();
					}
				}
			}

		}

		//	===========================================================================



		//	===================================================
		//  ============== Boucle sur les objets ==============
		//	===================================================

		for(int unsigned i = 0; i < vectorObject.size(); i++){

			for(int unsigned j = 0; j < vectorCharacter.size(); j++){

				if(CollisionObjectCharacter(vectorObject[i], vectorCharacter[j])){

					float life = vectorObject[i]->getLife();
					vectorCharacter[j].upLife(life);

					vectorObject[i]->kill();
				}

			}

			if(CollisionObjectCharacter(vectorObject[i], player)){

                if(vectorObject[i]->getType() == "lifeBonus"){
                    float life = vectorObject[i]->getLife();
                    player.upLife(life);

                    vectorObject[i]->kill();
                }
                else if(vectorObject[i]->getType() == "interrupteur"){

                    if(actionElement){
                        if(vectorObject[i]->getEstActive() == false){
                            vectorObject[i]->setActive();
                            vectorObject[i]->resetClockInt();
                        }
                    }

                }
                else if(vectorObject[i]->getType() == "tilePique"){

                    if(vectorObject[i]->getDeadly()){
                        player.kill();
                    }

                }
                else if(vectorObject[i]->getType() == "checkpoint"){

                    if(!vectorObject[i]->getActive()){
                        vectorObject[i]->setActive(true);

                        player.setInitialPosition(vectorObject[i]->getX(), vectorObject[i]->getY());

                        for(int unsigned j = 0; j < vectorObject.size(); j++){

                            if(vectorObject[j]->getType() == "checkpoint"){
                                if(j != i)
                                {
                                    if(vectorObject[j]->getActive()){
                                        vectorObject[j]->setActive(false);
                                    }
                                }
                            }
                        }

                    }
                }
                else if(vectorObject[i]->getType() == "blockPique"){

                    if(vectorObject[i]->getDeadly()){
                        player.kill();
                    }

                }
                else if(vectorObject[i]->getType() == "reward"){
                    int val = vectorObject[i]->getValeur();
                    player.setScore(player.getScore() + val);

                    vectorObject[i]->kill();
                }
			}

            //cout << "test 1030 et taille de  : " << vectorObject.size() << endl;


			if((vectorObject[i]->getType() == "interrupteur") && (vectorObject[i]->getEstActive())){

                if(vectorObject[i]->getClockInt() > vectorObject[i]->getDelai()){

                    vectorObject[i]->setNotActive();
                }

			}
			else if(vectorObject[i]->getType() == "door"){

                if(vectorObject[i]->buttonIsActive()){

                    vectorObject[i]->setOpen(true);
                }
                else{

                    if(!CollisionObjectCharacter(vectorObject[i], player))
                        vectorObject[i]->setOpen(false);
                }

			}
			else if(vectorObject[i]->getType() == "launcher"){

                if(!vectorObject[i]->getIsReady()){
                    if(vectorObject[i]->getClock() > vectorObject[i]->getDecallage()){

                        vectorObject[i]->resetClock();
                        vectorObject[i]->setReady(true);

                    }
                }
                else{
                    if(vectorObject[i]->getClock() > vectorObject[i]->getInterval()){

                        vectorObject[i]->resetClock();

                        float x, y;

                        if(vectorObject[i]->getDirection() == "gauche")
                        {
                            x = (vectorObject[i]->getLeftSide()) - 5.0f;
                            y = (vectorObject[i]->getTopSide()) + 15.0f;

                            vectorBullet.push_back(Bullet(myBullet, x, y, (BULLET_SPEED * frameTime), vectorObject[i]->getDirection(), vectorObject[i]->getEquipe(), vectorObject[i]->getAmmoType()));
                        }
                        else if(vectorObject[i]->getDirection() == "droite")
                        {
                            x = (vectorObject[i]->getRightSide()) - 15.0f;
                            y = (vectorObject[i]->getTopSide()) + 15.0f;

                            vectorBullet.push_back(Bullet(myBullet, x, y, (BULLET_SPEED * frameTime), vectorObject[i]->getDirection(), vectorObject[i]->getEquipe(), vectorObject[i]->getAmmoType()));
                        }



                    }

                }

			}
			else if(vectorObject[i]->getType() == "blockPique"){

               // if(EssaiDeplacementY(Matrice, app, player, player.getSpeedY(), LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorObject)){

                if(CollisionObjectDecor(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, i, vectorObject, Matrice))
                {

                    if(vectorObject[i]->getDirection() == "gauche"){

                        vectorObject[i]->setDirection("droite");
                    }
                    else if(vectorObject[i]->getDirection() == "droite"){

                        vectorObject[i]->setDirection("gauche");
                    }
                    else if(vectorObject[i]->getDirection() == "haut"){

                        vectorObject[i]->setDirection("bas");
                    }
                    else if(vectorObject[i]->getDirection() == "bas"){

                        vectorObject[i]->setDirection("haut");
                    }
                }

                if(vectorObject[i]->getDirection() == "gauche"){

                    vectorObject[i]->deplacementGaucheX();
                }
                else if(vectorObject[i]->getDirection() == "droite"){

                    vectorObject[i]->deplacementDroiteX();
                }
                else if(vectorObject[i]->getDirection() == "haut"){

                    vectorObject[i]->deplacementHautY();
                }
                else if(vectorObject[i]->getDirection() == "bas"){

                    vectorObject[i]->deplacementBasY();
                }

			}
			else if(vectorObject[i]->getType() == "reward"){

                if(CollisionObjectDecor(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, i, vectorObject, Matrice))
                {
                    vectorObject[i]->deplacement(true, frameTime);

                }
                else
                {
                    vectorObject[i]->deplacement(false, frameTime);

                }



			}

			vectorObject[i]->drawObject(app);
		}


        /** A AJUSTER */

		vue.setCenter((int)(player.getX() + (player.GetSprite().getLocalBounds().width)/2), (int)(player.getY() + (player.GetSprite().getLocalBounds().height)/2));


        player.drawPlayer(app);

		// == Boucle permettant de supprimer du Vector les balles qui sont "killed" après une collision

		for(int unsigned i = 0; i < vectorBullet.size();){
			if(vectorBullet[i].isKilled())
				vectorBullet.erase(vectorBullet.begin()+i);
			else
				i++;
		}

		// == Boucle permettant de supprimer du Vector les Ennemis qui sont "killed" lorsqu'il n'ont plus de points de vie

/*		// == Ou plutot de faire respawn le Character

		for(int unsigned i = 0; i < vectorCharacter.size();){
			if(vectorCharacter[i].isKilled()){

				vectorCharacter[i].setX(vectorCharacter[i].getInitialX());
				vectorCharacter[i].setY(vectorCharacter[i].getInitialY());
				vectorCharacter[i].setLife(vectorCharacter[i].getInitialLife());
				vectorCharacter[i].setSpeed(vectorCharacter[i].getInitialSpeed());
				vectorCharacter[i].setEnSaut(vectorCharacter[i].enSautInitial());
				vectorCharacter[i].setSurTerre(vectorCharacter[i].surTerreInitial());

				vectorCharacter[i].setPosition();

			//	vectorCharacter.erase(vectorCharacter.begin()+i);
			}else
				i++;
		}*/

		// == Boucle permettant de supprimer du Vector les objets qui sont "killed" lorsqu'ils ont été utilisés

		for(int unsigned i = 0; i < vectorObject.size();){
			if(vectorObject[i]->isKilled())
				vectorObject.erase(vectorObject.begin()+i);
			else
				i++;
		}



		// == Test permettant de voir si le player est Killed, et de le faire respawn en conséquence

		// systeme de CHECKPOINT ici

		if(player.isKilled()){

				player.setX(player.getInitialX());
				player.setY(player.getInitialY());
				player.setLife(player.getInitialLife());
				player.setSpeed(player.getInitialSpeed());
				player.setEnSaut(player.enSautInitial());
				player.setSurTerre(player.surTerreInitial());
				player.revive();

				player.setPosition();

			//	vectorCharacter.erase(vectorCharacter.begin()+i);
		}



        app.setView(hud); // IMPORTANT <<

        // On affiche le block hud1

        hud1.setPosition((hud.getCenter().x - (hud.getSize().x / 2)), (hud.getCenter().y - (hud.getSize().y / 2)));
        app.draw(hud1);

        // Permet d'afficher les FPS en mode debug

		if(debugMode){
			sf::Text fpsMessage;
			int FPS;
			ostringstream oss;

			FPS = 1 / frameTime;
			oss << "FPS : " << FPS;

            fpsMessage.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 110.0f));
            fpsMessage.setColor(Color(255,0,0,255));
            fpsMessage.setString(oss.str());
            fpsMessage.setCharacterSize(14);

			app.draw(fpsMessage);
		}

        // On Affiche le Score

        sf::Text score;
        ostringstream oss2;

        oss2 << "Score : " << player.getScore();

        score.setColor(Color(0,0,0,255));
        score.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 90.0f));
        score.setCharacterSize(14);
        score.setString(oss2.str());

        app.draw(score);

        // On Affiche le temps

        sf::Text tpsMaps;
        ostringstream oss3;

        oss3 << "Temps : " << clockTempsMap.getElapsedTime().asSeconds();

        tpsMaps.setColor(Color(0,0,0,255));
        tpsMaps.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 70.0f));
        tpsMaps.setCharacterSize(14);
        tpsMaps.setString(oss3.str());


        app.draw(tpsMaps);


		// Affichage d'un message "surcharge" si l'energie est basse

		sf::Text txtSurcharge;

		txtSurcharge.setString("Overheating !");
		txtSurcharge.setColor(Color(255,0,0,255));
		txtSurcharge.setCharacterSize(14);
		txtSurcharge.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 50.0f));

		if(player.getSurchauffe())
			app.draw(txtSurcharge);

		// Variations des barres de vies et de power

		barLife.setSize(sf::Vector2f(player.getLife(), 10.0f));
		barPower.setSize(sf::Vector2f(player.getPower(), 10.0f));

		barLife.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 10.0f));
		barPower.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 30.0f));

		if(player.getSurchauffe()){

			barPower.setFillColor(sf::Color(0, 25, 100));
		}
		else{

			barPower.setFillColor(sf::Color(0, 150, 255));
		}

        app.draw(barLife);
		app.draw(barPower);

        //cout << "x now :" << player.getX() << endl;
        //cout << "speed Y :" << player.getSpeedY() << endl;


		if(etatMap == "end"){


			/* Systeme de fondu pour fin de niveau // Le rectangle suit le joueur pour éviter tout problème visuel */

			fondu.setPosition((hud.getCenter().x - (hud.getSize().x / 2)), (hud.getCenter().y - (hud.getSize().y / 2)));
			fondu.setFillColor(sf::Color(0,0,0,transparence));

			app.draw(fondu);

			// La transparence s'effectue a 0.5 par frame ( a modifier si besoin !)

			if(transparence < 255){
				transparence += 1.0f;
			}


			if(transparence >= 255){

                save((Map_Actuelle + 2), player.getScore(), clockTempsMap.getElapsedTime().asSeconds());
                // MapActuelle + 2 car pour le niveau 1 mapActuelle = 0 et que l'on veux save le dernier niveau que l'on
                //a atteint donc fin du 1 = 0 + 2 = 2

                clockTempsMap.restart();
                player.setScore(0);

                deleteMatrice(&Matrice, NbColonnes, NbLignes, vectorObject);

                GoToNextMap(Map_EnCours, Map_Actuelle, Maps);

                createMap(Map_EnCours, &Matrice, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward, vectorObject);

                NbColonnes = nbColonnesMap(Map_EnCours);
                NbLignes = nbLignesMap(Map_EnCours);


				// On repositionne le joueur en fonction des valeurs initiales

				// =========
// IMPORTANT	// Les valeurs "initiales" varieront en fonction des checkpoint et des changement de niveau
				// =========



				// ========================

                PlayerPosition(player, &Matrice, NbColonnes, NbLignes, LARGEUR_TILE, "depart");




				// =================================

				etatMap = "transition"; // TEMPORAIRE
				transparence = 0;

			}

		}

		if(etatMap == "transition"){

			// On réalise un fondu (inverse) pour réafficher le jeu

			fondu.setPosition((hud.getCenter().x - (hud.getSize().x / 2)), (hud.getCenter().y - (hud.getSize().y / 2)));
			fondu.setFillColor(sf::Color(0,0,0,transparenceInverse));

			app.draw(fondu);

			if(transparenceInverse > 0){
				transparenceInverse -= 2.0f;
			}


			if(transparenceInverse <= 0)
			{
			    etatMap = "start";
			    transparenceInverse = 255;
			}

		}

        // Affichage de la fenêtre à l'écran
        app.display();
    }

	deleteMatrice(&Matrice, NbColonnes, NbLignes, vectorObject);

    return EXIT_SUCCESS;


}
void lcd_sd_menu_details_callback(uint8_t nr)
{
    if (nr == 0)
    {
        return;
    }
    for(uint8_t idx=0; idx<LCD_CACHE_COUNT; idx++)
    {
        if (LCD_CACHE_ID(idx) == nr)
        {
            if (LCD_CACHE_TYPE(idx) == 1)
            {
                lcd_lib_draw_string_centerP(53, PSTR("Folder"));
            }else{
                char buffer[64];
                if (LCD_DETAIL_CACHE_ID() != nr)
                {
                    card.getfilename(nr - 1);
                    if (card.errorCode())
                    {
                        card.clearError();
                        return;
                    }
                    LCD_DETAIL_CACHE_ID() = nr;
                    LCD_DETAIL_CACHE_TIME() = 0;
                    for(uint8_t e=0; e<EXTRUDERS; e++)
                        LCD_DETAIL_CACHE_MATERIAL(e) = 0;
                    card.openFile(card.filename, true);
                    if (card.isFileOpen())
                    {
                        for(uint8_t n=0;n<8;n++)
                        {
                            card.fgets(buffer, sizeof(buffer));
                            buffer[sizeof(buffer)-1] = '\0';
                            while (strlen(buffer) > 0 && buffer[strlen(buffer)-1] < ' ') buffer[strlen(buffer)-1] = '\0';
                            if (strncmp_P(buffer, PSTR(";TIME:"), 6) == 0)
                                LCD_DETAIL_CACHE_TIME() = atol(buffer + 6);
                            else if (strncmp_P(buffer, PSTR(";MATERIAL:"), 10) == 0)
                                LCD_DETAIL_CACHE_MATERIAL(0) = atol(buffer + 10);
#if EXTRUDERS > 1
                            else if (strncmp_P(buffer, PSTR(";MATERIAL2:"), 11) == 0)
                                LCD_DETAIL_CACHE_MATERIAL(1) = atol(buffer + 11);
#endif
                        }
                    }
                    if (card.errorCode())
                    {
                        //On a read error reset the file position and try to keep going. (not pretty, but these read errors are annoying as hell)
                        card.clearError();
                        LCD_DETAIL_CACHE_ID() = 255;
                    }
                }
                
                if (LCD_DETAIL_CACHE_TIME() > 0)
                {
                    char* c = buffer;
                    if (led_glow_dir)
                    {
                        strcpy_P(c, PSTR("Time: ")); c += 6;
                        c = int_to_time_string(LCD_DETAIL_CACHE_TIME(), c);
                    }else{
                        strcpy_P(c, PSTR("Material: ")); c += 10;
                        float length = float(LCD_DETAIL_CACHE_MATERIAL(0)) / (M_PI * (material[0].diameter / 2.0) * (material[0].diameter / 2.0));
                        if (length < 10000)
                            c = float_to_string(length / 1000.0, c, PSTR("m"));
                        else
                            c = int_to_string(length / 1000.0, c, PSTR("m"));
#if EXTRUDERS > 1
                        if (LCD_DETAIL_CACHE_MATERIAL(1))
                        {
                            *c++ = '/';
                            float length = float(LCD_DETAIL_CACHE_MATERIAL(1)) / (M_PI * (material[1].diameter / 2.0) * (material[1].diameter / 2.0));
                            if (length < 10000)
                                c = float_to_string(length / 1000.0, c, PSTR("m"));
                            else
                                c = int_to_string(length / 1000.0, c, PSTR("m"));
                        }
#endif
                    }
                    lcd_lib_draw_string(3, 53, buffer);
                }else{
                    lcd_lib_draw_stringP(3, 53, PSTR("No info available"));
                }
            }
        }
    }
}
Пример #27
0
void cRandom_Sound::Editor_Activate(void)
{
    CEGUI::WindowManager& wmgr = CEGUI::WindowManager::getSingleton();

    // filename
    CEGUI::Editbox* editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_filename"));
    Editor_Add(UTF8_("Filename"), UTF8_("Sound filename"), editbox, 200);

    editbox->setText(m_filename.c_str());
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Filename_Text_Changed, this));

    // continuous
    CEGUI::Checkbox* checkbox = static_cast<CEGUI::Checkbox*>(wmgr.createWindow("TaharezLook/Checkbox", "editor_sound_continuous"));
    Editor_Add(UTF8_("Continuous"), UTF8_("Check if the sound should be played continuously instead of randomly"), checkbox, 50);

    checkbox->setSelected(m_continuous);
    checkbox->subscribeEvent(CEGUI::Checkbox::EventCheckStateChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Continuous_Changed, this));

    // delay min
    editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_delay_min"));
    Editor_Add(UTF8_("Delay Minimum"), UTF8_("Minimal delay until played again"), editbox, 90);

    editbox->setValidationString("^[+]?\\d*$");
    editbox->setText(int_to_string(m_delay_min));
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Delay_Min_Text_Changed, this));

    // delay max
    editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_delay_max"));
    Editor_Add(UTF8_("Maximum"), UTF8_("Maximal delay until played again"), editbox, 90, 28, 0);

    editbox->setValidationString("^[+]?\\d*$");
    editbox->setText(int_to_string(m_delay_max));
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Delay_Max_Text_Changed, this));

    // volume min
    editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_volume_min"));
    Editor_Add(UTF8_("Volume Minimum"), UTF8_("Minimal random volume for each play"), editbox, 90);

    editbox->setValidationString("^[+]?\\d*$");
    editbox->setText(int_to_string(static_cast<int>(m_volume_min)));
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Volume_Min_Text_Changed, this));

    // volume max
    editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_volume_max"));
    Editor_Add(UTF8_("Maximum"), UTF8_("Maximal random volume for each play"), editbox, 90, 28, 0);

    editbox->setValidationString("^[+]?\\d*$");
    editbox->setText(int_to_string(static_cast<int>(m_volume_max)));
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Volume_Max_Text_Changed, this));

    // volume reduction begin
    editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_volume_reduction_begin"));
    Editor_Add(UTF8_("Volume Reduction Begin"), UTF8_("Volume reduction begins gradually at this distance"), editbox, 90);

    editbox->setValidationString("^[+]?\\d*$");
    editbox->setText(int_to_string(static_cast<int>(m_volume_reduction_begin)));
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Volume_Reduction_Begin_Text_Changed, this));

    // volume reduction end
    editbox = static_cast<CEGUI::Editbox*>(wmgr.createWindow("TaharezLook/Editbox", "editor_sound_volume_reduction_end"));
    Editor_Add(UTF8_("End"), UTF8_("Volume reduction ends at this distance. Sound is not played beyond this."), editbox, 90, 28, 0);

    editbox->setValidationString("^[+]?\\d*$");
    editbox->setText(int_to_string(static_cast<int>(m_volume_reduction_end)));
    editbox->subscribeEvent(CEGUI::Editbox::EventTextChanged, CEGUI::Event::Subscriber(&cRandom_Sound::Editor_Volume_Reduction_End_Text_Changed, this));

    // init
    Editor_Init();
}
static void tune_item_details_callback(uint8_t nr)
{
    char* c = (char*)lcd_cache;
    if (nr == 2)
        c = int_to_string(feedmultiply, c, PSTR("%"));
    else if (nr == 3)
    {
        c = int_to_string(current_temperature[0], c, PSTR("C"));
        *c++ = '/';
        c = int_to_string(target_temperature[0], c, PSTR("C"));
    }
#if EXTRUDERS > 1
    else if (nr == 4)
    {
        c = int_to_string(current_temperature[1], c, PSTR("C"));
        *c++ = '/';
        c = int_to_string(target_temperature[1], c, PSTR("C"));
    }
#endif
    else if (nr == 3 + EXTRUDERS)
    {
        c = int_to_string(current_temperature_bed, c, PSTR("C"));
        *c++ = '/';
        c = int_to_string(target_temperature_bed, c, PSTR("C"));
    }
    else if (nr == 4 + EXTRUDERS)
        c = int_to_string(int(fanSpeed) * 100 / 255, c, PSTR("%"));
    else if (nr == 5 + EXTRUDERS)
        c = int_to_string(extrudemultiply[0], c, PSTR("%"));
#if EXTRUDERS > 1
    else if (nr == 6 + EXTRUDERS)
        c = int_to_string(extrudemultiply[1], c, PSTR("%"));
#endif
    else if (nr == 7 + EXTRUDERS)
    {
        c = int_to_string(led_brightness_level, c, PSTR("%"));
        if (led_mode == LED_MODE_ALWAYS_ON ||  led_mode == LED_MODE_WHILE_PRINTING || led_mode == LED_MODE_BLINK_ON_DONE)
            analogWrite(LED_PIN, 255 * int(led_brightness_level) / 100);
    }
    else
        return;
    lcd_lib_draw_string(5, 53, (char*)lcd_cache);
}
Пример #29
0
void nb_sock_recv_file(struct aeEventLoop *eventLoop, int sockfd, void *clientData, int mask)
{
	aio_work_node_t *work_node;
	storage_client_t *pClient;
	nb_file_t *file;
	char temp_storage_id;
	
	pClient = (storage_client_t *)clientData;
	file = &pClient->file;
		
	logDebug("nb_sock_recv_file,%s",pClient->file.file_name);

	if(file->need_name == 1)
	{
//		
		pClient->trunk_file_node = grasp_non_occupied_trunk_file(&g_storage_service.trunk_file_pool,\
			pClient->nio_node->non_occupied_trunk_file_head,pClient->file.file_size);
	
		LOCK_IF_ERROR("nb_sock_recv_file",g_storage_service.heart_beat_lock);
		int_to_string(g_storage_service.heart_beat.storage_id,&temp_storage_id,1);
		UNLOCK_IF_ERROR("nb_sock_recv_file",g_storage_service.heart_beat_lock);
		pClient->file.start_offlen = pClient->trunk_file_node->size;
		pClient->trunk_file_node->file_name[4] = temp_storage_id;
		memcpy(pClient->file.file_name+8,pClient->trunk_file_node->file_name,5);

		if(pClient->trunk_file_node->fd == 0)
		{
			if((pClient->trunk_file_node->fd = open(pClient->trunk_file_node->file_name,O_WRONLY|O_CREAT,0664)) == -1)
			{
				logError(	"file: "__FILE__",line: %d,"\
					"nb_sock_recv_file call open file failed,"\
					"errno: %d,error info: %s",\
					__LINE__,errno,strerror(errno));		
				clean_storage_client(pClient);
				return ;
			}
		}
		pClient->file.fd = pClient->trunk_file_node->fd;
//
		storage_nio_read(&file->file_size,sizeof(file->file_size),do_upload_to_storage,NULL,"nb_sock_recv_file");

		return ;
	}
		
	mem_node_t *mem_node;
	if(file->read_size+BUF_MAXSIZE <= file->file_size)
	{
		mem_node = get_freed_mem(&pClient->nio_node->dio_buf_pool);
		if(mem_node == NULL)
			return ;
		
		work_node = mem_node->buf;
		work_node->mem_node = mem_node;

		pClient->cur_aio_node = work_node;

		work_node->arg = pClient;
		work_node->proc = do_recv_file_count;
		work_node->res_queue = pClient->nio_node->res_queue;

		storage_nio_read(&work_node->buf,BUF_MAXSIZE,finish_buf_read,NULL,"nb_sock_recv_file");
		
		return ;
	}
	if(file->read_size != file->file_size)
	{
		mem_node = get_freed_mem(&pClient->nio_node->dio_buf_pool);
		if(mem_node == NULL)
			return ;
		
		work_node = mem_node->buf;
		work_node->mem_node = mem_node;

		pClient->cur_aio_node = work_node;

		work_node->arg = pClient;
		work_node->proc = do_recv_file_count_end;
		work_node->res_queue = pClient->nio_node->res_queue;

		storage_nio_read(&work_node->buf,file->file_size-file->read_size,finish_buf_read,NULL,"nb_sock_recv_file");

		return ;
	}
	return ;
}
Пример #30
0
void print_C_switch(ostream& out, string component, const StateMachine& machine)
{
  out << "// Auto generated C++ code started by "<<__FILE__<<":"<<__LINE__<< endl;
  out << "// " << machine.getIdent() << ": " <<  machine.getShorthand() << endl;
  out << endl;
  out << "#include \"Global.h\"" << endl;
  out << "#include \"" << component << "_Controller.h\"" << endl;
  out << "#include \"" << component << "_State.h\"" << endl;
  out << "#include \"" << component << "_Event.h\"" << endl;
  out << "#include \"Types.h\"" << endl;
  out << "#include \"System.h\"" << endl;
  out << "#include \"Profiler.h\"" << endl;
  out << endl;
  out << "#define HASH_FUN(state, event)  ((int(state)*" << component
      << "_Event_NUM)+int(event))" << endl;
  out << endl;
  out << "TransitionResult " << component << "_Controller::doTransition(" 
      << component << "_Event event, "
      << component << "_State state, "
      << "const Address& addr)" << endl;
           
  out << "{" << endl;
  out << "  " << component << "_State next_state = state;" << endl;
  out << endl;
  out << "  DEBUG_NEWLINE(GENERATED_COMP, MedPrio);" << endl;
  out << "  DEBUG_MSG(GENERATED_COMP, MedPrio,*this);" << endl;
  out << "  DEBUG_EXPR(GENERATED_COMP, MedPrio,g_eventQueue_ptr->getTime());" << endl;
  out << "  DEBUG_EXPR(GENERATED_COMP, MedPrio,state);" << endl;
  out << "  DEBUG_EXPR(GENERATED_COMP, MedPrio,event);" << endl;
  out << "  DEBUG_EXPR(GENERATED_COMP, MedPrio,addr);" << endl;
  out << endl;
  out << "  TransitionResult result = doTransitionWorker(event, state, next_state, addr);" << endl;
  out << endl;
  out << "  if (result == TransitionResult_Valid) {" << endl;
  out << "    DEBUG_EXPR(GENERATED_COMP, MedPrio, next_state);" << endl;
  out << "    DEBUG_NEWLINE(GENERATED_COMP, MedPrio);" << endl;
  out << "    s_profiler.countTransition(state, event);" << endl;
  out << "    if (g_param_ptr->PROTOCOL_DEBUG_TRACE()) {" << endl
      << "      g_system_ptr->getProfiler()->profileTransition(\"" << component << "\", m_id, addr, " << endl
      << "        " << component << "_State_to_string(state), " << endl
      << "        " << component << "_Event_to_string(event), " << endl
      << "        " << component << "_State_to_string(next_state), " << endl
      << "        \"\");" << endl
      << "    }" << endl;
  out << "    " << component << "_setState(addr, next_state);" << endl;
  out << "    " << endl;
  out << "  } else if (result == TransitionResult_ResourceStall) {" << endl;
  out << "    if (g_param_ptr->PROTOCOL_DEBUG_TRACE()) {" << endl
      << "      g_system_ptr->getProfiler()->profileTransition(\"" << component << "\", m_id, addr, " << endl
      << "        " << component << "_State_to_string(state), " << endl
      << "        " << component << "_Event_to_string(event), " << endl
      << "        " << component << "_State_to_string(next_state), " << endl
      << "        \"Resource Stall\");" << endl
      << "    }" << endl;
  out << "  } else if (result == TransitionResult_ProtocolStall) {" << endl;
  out << "    DEBUG_MSG(GENERATED_COMP,HighPrio,\"stalling\");" << endl
      << "    DEBUG_NEWLINE(GENERATED_COMP, MedPrio);" << endl;
  out << "    if (g_param_ptr->PROTOCOL_DEBUG_TRACE()) {" << endl
      << "      g_system_ptr->getProfiler()->profileTransition(\"" << component << "\", m_id, addr, " << endl
      << "        " << component << "_State_to_string(state), " << endl
      << "        " << component << "_Event_to_string(event), " << endl
      << "        " << component << "_State_to_string(next_state), " << endl
      << "        \"Protocol Stall\");" << endl
      << "    }" << endl
      << "  }" << endl;
  out << "  return result;" << endl;
  out << "}" << endl;
  out << endl;
  out << "TransitionResult " << component << "_Controller::doTransitionWorker(" 
      << component << "_Event event, "
      << component << "_State state, "
      << component << "_State& next_state, "
      << "const Address& addr)" << endl;
           
  out << "{" << endl;
  out << "" << endl;

  out << "  switch(HASH_FUN(state, event)) {" << endl;

  Map<string, Vector<string> > code_map; // This map will allow suppress generating duplicate code
  Vector<string> code_vec;

  for(int i=0; i<machine.numTransitions(); i++) {
    const Transition& t = machine.getTransition(i);
    string case_string = component + "_State_" + t.getStatePtr()->getIdent() 
      + ", " + component + "_Event_" + t.getEventPtr()->getIdent();

    string code;

    code += "  {\n";
    // Only set next_state if it changes
    if (t.getStatePtr() != t.getNextStatePtr()) {
      code += "    next_state = " + component + "_State_" + t.getNextStatePtr()->getIdent() + ";\n";
    }

    const Vector<Action*>& action_vec = t.getActions();
    int numActions = action_vec.size();

    // Check for resources
    Vector<string> code_sorter;
    const Map<Var*, int>& res = t.getResources();
    Vector<Var*> res_keys = res.keys();
    for (int i=0; i<res_keys.size(); i++) {
      string temp_code;
      temp_code += "    if (!" + (res_keys[i]->getCode()) + ".areNSlotsAvailable(" 
        + int_to_string(res.lookup(res_keys[i])) + ")) {\n";
      temp_code += "      return TransitionResult_ResourceStall;\n";
      temp_code += "    }\n";
      code_sorter.insertAtBottom(temp_code);
    }

    // Emit the code sequences in a sorted order.  This makes the
    // output deterministic (without this the output order can vary
    // since Map's keys() on a vector of pointers is not deterministic
    code_sorter.sortVector();
    for (int i=0; i<code_sorter.size(); i++) {
      code += code_sorter[i];
    }

    // Figure out if we stall
    bool stall = false;
    for (int i=0; i<numActions; i++) {
      if(action_vec[i]->getIdent() == "z_stall") {
        stall = true;
      }
    }
    
    if (stall) {
      code += "    return TransitionResult_ProtocolStall;\n";
    } else {
      for (int i=0; i<numActions; i++) {
        code += "    " + action_vec[i]->getIdent() + "(addr);\n";
      }
      code += "    return TransitionResult_Valid;\n";
    }
    code += "  }\n";

    
    // Look to see if this transition code is unique.
    if (code_map.exist(code)) {
      code_map.lookup(code).insertAtBottom(case_string);
    } else {
      Vector<string> vec;
      vec.insertAtBottom(case_string);
      code_map.add(code, vec);
      code_vec.insertAtBottom(code);
    }
  }
  
  // Walk through all of the unique code blocks and spit out the
  // corresponding case statement elements
  for (int i=0; i<code_vec.size(); i++) {
    string code = code_vec[i];

    // Iterative over all the multiple transitions that share the same code
    for (int case_num=0; case_num<code_map.lookup(code).size(); case_num++) {
      string case_string = code_map.lookup(code)[case_num];
      out << "  case HASH_FUN(" << case_string << "):" << endl;
    }
    out << code;
  }

  out << "  default:" << endl;
  out << "    WARN_EXPR(m_id);" << endl;              
  out << "    WARN_EXPR(g_eventQueue_ptr->getTime());" << endl;
  out << "    WARN_EXPR(addr);" << endl;
  out << "    WARN_EXPR(event);" << endl;
  out << "    WARN_EXPR(state);" << endl;
  out << "    ERROR_MSG(\"Invalid transition\");" << endl;
  out << "  }" << endl;
  out << "  return TransitionResult_Valid;" << endl;
  out << "}" << endl;
}