float Probe_Bed(float x_pos, float y_pos, int n) { //returns Probed Z average height float ProbeDepth[n]; float ProbeDepthAvg=0; //force bed heater off for probing int save_bed_targ = target_raw_bed; target_raw_bed = 0; WRITE(HEATER_BED_PIN,LOW); if (Z_HOME_DIR==-1) { //int probe_flag =1; float meas = 0; int fails = 0; saved_feedrate = feedrate; saved_feedmultiply = feedmultiply; feedmultiply = 100; //previous_millis_cmd = millis(); //Move to probe position if (x_pos >= 0) destination[X_AXIS]=x_pos; if (y_pos >= 0) destination[Y_AXIS]=y_pos; //destination[Z_AXIS]=current_position[Z_AXIS]; destination[Z_AXIS]=Z_HOME_RETRACT_MM; feedrate = 9000; prepare_move(); enable_endstops(true); SERIAL_ECHO("PRE-PROBE current_position[Z_AXIS]=");SERIAL_ECHOLN(current_position[Z_AXIS]); SERIAL_ECHOLN("Ready to probe..."); //Probe bed n times //*******************************************************************************************Bed Loop************************************* for(int8_t i=0; i < n ; i++) { //int z = 0; //fast probe //plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[Z_AXIS] = 1.1 * Z_MAX_LENGTH * Z_HOME_DIR; feedrate = homing_feedrate[Z_AXIS]; plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder); st_synchronize(); //feedrate = 0.0; SERIAL_ECHO("current_position[Z_AXIS]=");SERIAL_ECHOLN(current_position[Z_AXIS]); if(endstop_z_hit == true) { SERIAL_ECHO("endstops_trigsteps[Z_AXIS]=");SERIAL_ECHOLN(endstops_trigsteps[Z_AXIS]); ProbeDepth[i]= endstops_trigsteps[Z_AXIS] / axis_steps_per_unit[Z_AXIS]; meas = ProbeDepth[i]; SERIAL_ECHO("ProbeDepth[");SERIAL_ECHO(i);SERIAL_ECHO("]=");SERIAL_ECHOLN(ProbeDepth[i]); //************************************************************************************************************* if (i > 0 ) //Second probe has happened so compare results { if (abs(ProbeDepth[i] - ProbeDepth[i - 1]) > .05) { //keep going until readings match to avoid sticky bed SERIAL_ECHO("Probing again: "); SERIAL_ECHO(ProbeDepth[i]); SERIAL_ECHO(" - "); SERIAL_ECHO(ProbeDepth[i - 1]);SERIAL_ECHO(" = "); SERIAL_ECHOLN(abs(ProbeDepth[i] - ProbeDepth[i - 1])); meas = ProbeDepth[i]; i--; i--; //Throw out both that don't match because we don't know which one is accurate if(fails++ > 4) break; } } }else{ SERIAL_ECHOLN("Probe not triggered."); i=n-1; } //************************************************************************************************************************************************** //fast move clear plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], meas, current_position[E_AXIS]); destination[Z_AXIS] = Z_HOME_RETRACT_MM; feedrate = fast_home_feedrate[Z_AXIS]; plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate/60, active_extruder); st_synchronize(); //check z stop isn't still triggered if ( READ(X_MIN_PIN) != X_ENDSTOPS_INVERTING ) { SERIAL_ECHOLN("Poking Stuck Bed:"); destination[Z_AXIS] = -1; prepare_move(); destination[Z_AXIS] = Z_HOME_RETRACT_MM; prepare_move(); st_synchronize(); i--; //Throw out this meaningless measurement } feedrate = 0; } //end probe loop #ifdef ENDSTOPS_ONLY_FOR_HOMING enable_endstops(false); #endif feedrate = saved_feedrate; feedmultiply = saved_feedmultiply; //previous_millis_cmd = millis(); endstops_hit_on_purpose(); } for(int8_t i=0;i<n;i++) { ProbeDepthAvg += ProbeDepth[i]; } ProbeDepthAvg /= n; SERIAL_ECHO("Probed Z="); SERIAL_ECHOLN(ProbeDepthAvg); SERIAL_ECHO("RAW current_position[Z_AXIS]=");SERIAL_ECHOLN(current_position[Z_AXIS]); plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], Z_HOME_RETRACT_MM, current_position[E_AXIS]); current_position[Z_AXIS] = Z_HOME_RETRACT_MM; target_raw_bed = save_bed_targ; return ProbeDepthAvg; }
static int /*ARGSUSED*/ _rmt_open(const char *path, int oflag, int mode) { int i; char buffer[BUFMAGIC]; char host[MAXHOSTLEN]; char device[BUFMAGIC]; char login[BUFMAGIC]; char *sys, *dev, *user; const char *rshpath, *rsh; _DIAGASSERT(path != NULL); sys = host; dev = device; user = login; /* * first, find an open pair of file descriptors */ for (i = 0; i < MAXUNIT; i++) if (READ(i) == -1 && WRITE(i) == -1) break; if (i == MAXUNIT) { errno = EMFILE; return -1; } /* * pull apart system and device, and optional user * don't munge original string * if COMPAT is defined, also handle old (4.2) style person.site notation. */ while (*path != '@' #ifdef COMPAT && *path != '.' #endif && *path != ':') { *sys++ = *path++; } *sys = '\0'; path++; if (*(path - 1) == '@') { (void)strncpy(user, host, sizeof(login) - 1); /* saw user part of user@host */ sys = host; /* start over */ while (*path != ':') { *sys++ = *path++; } *sys = '\0'; path++; } #ifdef COMPAT else if (*(path - 1) == '.') { while (*path != ':') { *user++ = *path++; } *user = '******'; path++; } #endif else *user = '******'; while (*path) { *dev++ = *path++; } *dev = '\0'; #ifdef USE_REXEC /* * Execute the remote command using rexec */ READ(i) = WRITE(i) = _rmt_rexec(host, login); if (READ(i) < 0) return -1; #else /* * setup the pipes for the 'rsh' command and fork */ if (pipe(Ptc[i]) == -1 || pipe(Ctp[i]) == -1) return -1; switch (fork()) { case -1: return -1; case 0: close(0); dup(Ptc[i][0]); close(Ptc[i][0]); close(Ptc[i][1]); close(1); dup(Ctp[i][1]); close(Ctp[i][0]); close(Ctp[i][1]); (void) setuid(getuid()); (void) setgid(getgid()); if ((rshpath = getenv("RCMD_CMD")) == NULL) rshpath = _PATH_RSH; if ((rsh = strrchr(rshpath, '/')) == NULL) rsh = rshpath; else rsh++; if (*login) { execl(rshpath, rsh, host, "-l", login, _PATH_RMT, NULL); } else { execl(rshpath, rsh, host, _PATH_RMT, NULL); } /* * bad problems if we get here */ err(1, "Cannnot exec %s", rshpath); /*FALLTHROUGH*/ default: break; } close(Ptc[i][0]); close(Ctp[i][1]); #endif /* * now attempt to open the tape device */ (void)snprintf(buffer, sizeof(buffer), "O%s\n%d\n", device, oflag); if (command(i, buffer) == -1 || status(i) == -1) return -1; return i; }
/// called every 10ms from clock.c - check all temp sensors that are ready for checking void temp_sensor_tick() { temp_sensor_t i = 0; for (; i < NUM_TEMP_SENSORS; i++) { if (temp_sensors_runtime[i].next_read_time) { temp_sensors_runtime[i].next_read_time--; } else { uint16_t temp = 0; //time to deal with this temp sensor switch(temp_sensors[i].temp_type) { #ifdef TEMP_MAX6675 case TT_MAX6675: #ifdef PRR PRR &= ~MASK(PRSPI); #elif defined PRR0 PRR0 &= ~MASK(PRSPI); #endif SPCR = MASK(MSTR) | MASK(SPE) | MASK(SPR0); // enable TT_MAX6675 WRITE(SS, 0); // ensure 100ns delay - a bit extra is fine delay(1); // read MSB SPDR = 0; for (;(SPSR & MASK(SPIF)) == 0;); temp = SPDR; temp <<= 8; // read LSB SPDR = 0; for (;(SPSR & MASK(SPIF)) == 0;); temp |= SPDR; // disable TT_MAX6675 WRITE(SS, 1); temp_sensors_runtime[i].temp_flags = 0; if ((temp & 0x8002) == 0) { // got "device id" temp_sensors_runtime[i].temp_flags |= PRESENT; if (temp & 4) { // thermocouple open temp_sensors_runtime[i].temp_flags |= TCOPEN; } else { temp = temp >> 3; } } // this number depends on how frequently temp_sensor_tick is called. the MAX6675 can give a reading every 0.22s, so set this to about 250ms temp_sensors_runtime[i].next_read_time = 25; break; #endif /* TEMP_MAX6675 */ #ifdef TEMP_THERMISTOR case TT_THERMISTOR: do { uint8_t j, table_num; //Read current temperature temp = analog_read(temp_sensors[i].temp_pin); // for thermistors the thermistor table number is in the additional field table_num = temp_sensors[i].additional; //Calculate real temperature based on lookup table for (j = 1; j < NUMTEMPS; j++) { if (pgm_read_word(&(temptable[table_num][j][0])) > temp) { // Thermistor table is already in 14.2 fixed point #ifndef EXTRUDER if (DEBUG_PID && (debug_flags & DEBUG_PID)) sersendf_P(PSTR("pin:%d Raw ADC:%d table entry: %d"),temp_sensors[i].temp_pin,temp,j); #endif // Linear interpolating temperature value // y = ((x - x₀)y₁ + (x₁-x)y₀ ) / (x₁ - x₀) // y = temp // x = ADC reading // x₀= temptable[j-1][0] // x₁= temptable[j][0] // y₀= temptable[j-1][1] // y₁= temptable[j][1] // y = // Wikipedia's example linear interpolation formula. temp = ( // ((x - x₀)y₁ ((uint32_t)temp - pgm_read_word(&(temptable[table_num][j-1][0]))) * pgm_read_word(&(temptable[table_num][j][1])) // + + // (x₁-x) (pgm_read_word(&(temptable[table_num][j][0])) - (uint32_t)temp) // y₀ ) * pgm_read_word(&(temptable[table_num][j-1][1]))) // / / // (x₁ - x₀) (pgm_read_word(&(temptable[table_num][j][0])) - pgm_read_word(&(temptable[table_num][j-1][0]))); #ifndef EXTRUDER if (DEBUG_PID && (debug_flags & DEBUG_PID)) sersendf_P(PSTR(" temp:%d.%d"),temp/4,(temp%4)*25); #endif break; } } #ifndef EXTRUDER if (DEBUG_PID && (debug_flags & DEBUG_PID)) sersendf_P(PSTR(" Sensor:%d\n"),i); #endif //Clamp for overflows if (j == NUMTEMPS) temp = temptable[table_num][NUMTEMPS-1][1]; temp_sensors_runtime[i].next_read_time = 0; } while (0); break; #endif /* TEMP_THERMISTOR */ #ifdef TEMP_AD595 case TT_AD595: temp = analog_read(temp_sensors[i].temp_pin); // convert // >>8 instead of >>10 because internal temp is stored as 14.2 fixed point temp = (temp * 500L) >> 8; temp_sensors_runtime[i].next_read_time = 0; break; #endif /* TEMP_AD595 */ #ifdef TEMP_PT100 case TT_PT100: #warning TODO: PT100 code break #endif /* TEMP_PT100 */ #ifdef TEMP_INTERCOM case TT_INTERCOM: temp = read_temperature(temp_sensors[i].temp_pin); temp_sensors_runtime[i].next_read_time = 25; break; #endif /* TEMP_INTERCOM */ #ifdef TEMP_DUMMY case TT_DUMMY: temp = temp_sensors_runtime[i].last_read_temp; if (temp_sensors_runtime[i].target_temp > temp) temp++; else if (temp_sensors_runtime[i].target_temp < temp) temp--; temp_sensors_runtime[i].next_read_time = 0; break; #endif /* TEMP_DUMMY */ default: /* prevent compiler warning */ break; } temp_sensors_runtime[i].last_read_temp = temp; } if (labs((int16_t)(temp_sensors_runtime[i].last_read_temp - temp_sensors_runtime[i].target_temp)) < (TEMP_HYSTERESIS*4)) { if (temp_sensors_runtime[i].temp_residency < (TEMP_RESIDENCY_TIME*100)) temp_sensors_runtime[i].temp_residency++; } else { temp_sensors_runtime[i].temp_residency = 0; } if (temp_sensors[i].heater < NUM_HEATERS) { heater_tick(temp_sensors[i].heater, i, temp_sensors_runtime[i].last_read_temp, temp_sensors_runtime[i].target_temp); } }
void BOARD_ConfigureDdram(unsigned char ddrModel, unsigned char busWidth) { unsigned int i; volatile unsigned int *pDdram = (unsigned int *) AT91C_EBI_DDRAM; unsigned short ddrc_dbw = 0; switch (busWidth) { case 16: ddrc_dbw = AT91C_B16MODE_16_BITS; break; case 32: default: ddrc_dbw = AT91C_B16MODE_32_BITS; break; } AT91C_BASE_PMC->PMC_SCER = (0x1 << AT91C_PMC_DDR); // Step 1: program the memory device type into Memory Device Register // Memory Device Register // Mobile DDRAM type | 16bit MODE // 0x00000013 WRITE(AT91C_BASE_SDDRC, SDDRC_MDR, AT91C_MD_LP_DDR_SDRAM | ddrc_dbw ); // Step 2: program the features of the Mobile DDR into the Configuration Register // Configuration Register // Weak driver strength(1) | Disable DLL reset(0) | SDRAM CAS = 3 | row = 13 | column = 9 // 0x00000138 WRITE(AT91C_BASE_SDDRC, SDDRC_CR, AT91C_DIC_DS | AT91C_DLL_RESET_DISABLED | AT91C_CAS_3 | AT91C_NR_13 | AT91C_NC_DDR9_SDR8 ); // Step 3: program into Low Power Register // Timing 0 Parameter Register // tmrd = 2 | twtr = 1 | trrd = 2 | trrd = 2 | trp = 3 | trc = 8 | twr = 2 | trcd = 3 | tras = 5 // 0x21238235 WRITE(AT91C_BASE_SDDRC, SDDRC_T0PR, AT91C_TMRD_2 | AT91C_TWTR_1 | AT91C_TRRD_2 | AT91C_TRP_3 | AT91C_TRC_8 | AT91C_TWR_2 | AT91C_TRCD_3 | AT91C_TRAS_5); // Timing 1 Parameter Register // txp = 4 | txsrd = 0xC | txsnr = 0xC | trfc = 9 // 0x040D0D09 WRITE(AT91C_BASE_SDDRC, SDDRC_T1PR, AT91C_TXP_4 | AT91C_TXSRD_12 | AT91C_TXSNR_12 | AT91C_TRFC_9 ); // Low-power Register WRITE(AT91C_BASE_SDDRC, SDDRC_LPR, 0x00000000); // Low power register => Low-power is inhibited // all bank refresh during self refresh (PASR = b000) // minimum pause 200us sleep_time(200); // Step 4: perform a NOP command in order to allow to enable clk // NOP command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_NOP_CMD); pDdram[0] = 0x00000000; // Dummy write to access SDRAM : validate preceeding command // Step 5: perform an All Banks Precharge command // Precharge All Banks command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_PRCGALL_CMD); pDdram[0] = 0x00000000; // Dummy write to access SDRAM : validate preceeding command // Step 6: two auto refresh cycles are provided for (i=0 ; i<2 ; i++) { // AutoRefresh command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_RFSH_CMD); pDdram[0] = 0x00000000; // Dummy write to access SDRAM : validate preceeding command } // Step 7: an extended mode register set cycle is issued // Extended Mode Register Set command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_EXT_LMR_CMD); pDdram[0x400000] = 0x00000000; //@0x71000000 (BA[0]=0 BA[1]=1) // Step 8: a mode register set cycle is issued // Mode Register Set command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_LMR_CMD); pDdram[0x400000] = 0x00000000; //@0x71000000 (BA[0]=0 BA[1]=1) // Step 9: Set Normal mode // Set Normal mode : Any access to the DDRSDRAMC is decoded normally WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_NORMAL_CMD); pDdram[0] = 0x00000000; // Step 10: Perform a write access to any DDR-SDRAM address pDdram[0] = 0x00000000; // Step 11: Set Refresh timer // Set Refresh Timer : ((64 x 10^-3)/8192) x 48 x 10^6 ---> 375 for 48 MHz //WRITE(AT91C_BASE_SDDRC, SDDRC_RTR, 375); // Set Refresh Timer : ((64 x 10^-3)/8192) x 100 x 10^6 ---> 781 for 100 MHz WRITE(AT91C_BASE_SDDRC, SDDRC_RTR, 781); // --------- WAIT --------- sleep_time(2000); }
int lg_gsm_read_picture_data (GPPort *port, char *data, int size, int n) { char listphotos[] = "\x04\x0\x08\x0\x0\x0\x40\x0\x0\x0\x0\x0\x0\x0"; char photonumber[22]; char photodesc[142]; //1 * 142 char getphoto[144]; char getphotorespheader[150]; char block[50000]; char oknok[6]; int pos=0; int block_size=50000; int header_size=8; int nb_blocks; int i; int remain; memset (oknok,0,6); memset (photonumber,0,22); memset (photodesc,0,142); memset (getphoto,0,144); memset (getphotorespheader,0,150); memset (block,0,50000); //listphotos[11]=listphotos[13]=n / 256; //listphotos[10]=listphotos[12]=n % 256; listphotos[10]=listphotos[12]=n; //port->timeout=20000; GP_DEBUG("Running lg_gsm_read_picture_data\n"); //syncstart MSGWRITE(port, 0x13, 0x6, 0x0, "", 0); WRITE(port, sync_start, 6); READ(port, oknok, 6); MSGWRITE(port, 0x13, 0x0e, 0x0, "", 0); WRITE(port, listphotos, 0xe); //read 22 READ(port, photonumber, 0x16); //then read 142 READ(port, photodesc, 142); size = (int)photodesc[138] + (int)photodesc[139]*0x100 + (int)photodesc[140]*0x10000+(int)photodesc[141]*0x1000000; GP_DEBUG(" size of picture %i is 0x%x\n", n, size); // max. 1280x960x24bits ? if ( (size >= 0x384000 ) ) { return GP_ERROR; } memcpy(getphoto, &get_photo_cmd[0], 10); memcpy(getphoto +10, &n, 1); //TODO: fix this //memcpy(getphoto +11, 0, 1); memcpy(getphoto +12, &photodesc[6],44); memcpy(getphoto +56, &photodesc[50],88); //send getphoto cmd MSGWRITE(port, 0x13, 0x90, 0x0, "", 0); WRITE(port, getphoto, 0x90); //read READ(port, getphotorespheader, 0x96); nb_blocks=size/block_size+1; //port->timeout=15000; for (i = 1 ; i <= nb_blocks ; i++) { remain = size - pos; if (remain >= block_size - header_size) { READ(port, block, block_size); memcpy(data+pos,&block[header_size],block_size - header_size); pos=pos+block_size-header_size; } else { READ(port,block, remain+header_size); memcpy(data+pos,&block[header_size],remain); pos=pos+remain; } } //port->timeout=5000; //syncstop MSGWRITE(port, 0x13, 0x6, 0x0, "", 0); WRITE(port, sync_stop, 6); READ(port, oknok, 6); GP_DEBUG("Leaving lg_gsm_read_picture_data\n"); return GP_OK; }
/* Warning: This function is called from interrupt context */ void lcd_buttons_update() { #ifdef NEWPANEL uint8_t newbutton=0; if(READ(BTN_EN1)==0) newbutton|=EN_A; if(READ(BTN_EN2)==0) newbutton|=EN_B; #if BTN_ENC > 0 if((blocking_enc<millis()) && (READ(BTN_ENC)==0)) newbutton |= EN_C; #endif buttons = newbutton; #ifdef LCD_HAS_SLOW_BUTTONS buttons |= slow_buttons; #endif #ifdef REPRAPWORLD_KEYPAD // for the reprapworld_keypad uint8_t newbutton_reprapworld_keypad=0; WRITE(SHIFT_LD,LOW); WRITE(SHIFT_LD,HIGH); for(int8_t i=0;i<8;i++) { newbutton_reprapworld_keypad = newbutton_reprapworld_keypad>>1; if(READ(SHIFT_OUT)) newbutton_reprapworld_keypad|=(1<<7); WRITE(SHIFT_CLK,HIGH); WRITE(SHIFT_CLK,LOW); } buttons_reprapworld_keypad=~newbutton_reprapworld_keypad; //invert it, because a pressed switch produces a logical 0 #endif #else //read it from the shift register uint8_t newbutton=0; WRITE(SHIFT_LD,LOW); WRITE(SHIFT_LD,HIGH); unsigned char tmp_buttons=0; for(int8_t i=0;i<8;i++) { newbutton = newbutton>>1; if(READ(SHIFT_OUT)) newbutton|=(1<<7); WRITE(SHIFT_CLK,HIGH); WRITE(SHIFT_CLK,LOW); } buttons=~newbutton; //invert it, because a pressed switch produces a logical 0 #endif//!NEWPANEL //manage encoder rotation uint8_t enc=0; if(buttons&EN_A) enc|=(1<<0); if(buttons&EN_B) enc|=(1<<1); if(enc != lastEncoderBits) { switch(enc) { case encrot0: if(lastEncoderBits==encrot3) encoderDiff++; else if(lastEncoderBits==encrot1) encoderDiff--; break; case encrot1: if(lastEncoderBits==encrot0) encoderDiff++; else if(lastEncoderBits==encrot2) encoderDiff--; break; case encrot2: if(lastEncoderBits==encrot1) encoderDiff++; else if(lastEncoderBits==encrot3) encoderDiff--; break; case encrot3: if(lastEncoderBits==encrot2) encoderDiff++; else if(lastEncoderBits==encrot0) encoderDiff--; break; } } lastEncoderBits = enc; }
//------------------------------------------------------------------------------ /// Changes the mapping of the chip so that the remap area mirrors the /// internal RAM. //------------------------------------------------------------------------------ void BOARD_RemapRam() { WRITE(AT91C_BASE_MATRIX, MATRIX_MRCR, (AT91C_MATRIX_RCA926I | AT91C_MATRIX_RCA926D)); }
/// initialise all I/O - set pins as input or output, turn off unused subsystems, etc void io_init(void) { // disable modules we don't use #ifdef PRR PRR = MASK(PRTWI) | MASK(PRADC) | MASK(PRSPI); #elif defined PRR0 PRR0 = MASK(PRTWI) | MASK(PRADC) | MASK(PRSPI); #if defined(PRUSART3) // don't use USART2 or USART3- leave USART1 for GEN3 and derivatives PRR1 |= MASK(PRUSART3) | MASK(PRUSART2); #endif #if defined(PRUSART2) // don't use USART2 or USART3- leave USART1 for GEN3 and derivatives PRR1 |= MASK(PRUSART2); #endif #endif ACSR = MASK(ACD); // setup I/O pins // X Stepper WRITE(X_STEP_PIN, 0); SET_OUTPUT(X_STEP_PIN); WRITE(X_DIR_PIN, 0); SET_OUTPUT(X_DIR_PIN); #ifdef X_MIN_PIN SET_INPUT(X_MIN_PIN); #ifdef USE_INTERNAL_PULLUPS WRITE(X_MIN_PIN, 1); #else WRITE(X_MIN_PIN, 0); #endif #endif #ifdef X_MAX_PIN SET_INPUT(X_MAX_PIN); #ifdef USE_INTERNAL_PULLUPS WRITE(X_MAX_PIN, 1); #else WRITE(X_MAX_PIN, 0); #endif #endif // Y Stepper WRITE(Y_STEP_PIN, 0); SET_OUTPUT(Y_STEP_PIN); WRITE(Y_DIR_PIN, 0); SET_OUTPUT(Y_DIR_PIN); #ifdef Y_MIN_PIN SET_INPUT(Y_MIN_PIN); #ifdef USE_INTERNAL_PULLUPS WRITE(Y_MIN_PIN, 1); #else WRITE(Y_MIN_PIN, 0); #endif #endif #ifdef Y_MAX_PIN SET_INPUT(Y_MAX_PIN); #ifdef USE_INTERNAL_PULLUPS WRITE(Y_MAX_PIN, 1); #else WRITE(Y_MAX_PIN, 0); #endif #endif // Z Stepper #if defined Z_STEP_PIN && defined Z_DIR_PIN WRITE(Z_STEP_PIN, 0); SET_OUTPUT(Z_STEP_PIN); WRITE(Z_DIR_PIN, 0); SET_OUTPUT(Z_DIR_PIN); #endif #ifdef Z_MIN_PIN SET_INPUT(Z_MIN_PIN); #ifdef USE_INTERNAL_PULLUPS WRITE(Z_MIN_PIN, 1); #else WRITE(Z_MIN_PIN, 0); #endif #endif #ifdef Z_MAX_PIN SET_INPUT(Z_MAX_PIN); #ifdef USE_INTERNAL_PULLUPS WRITE(Z_MAX_PIN, 1); #else WRITE(Z_MAX_PIN, 0); #endif #endif #if defined E_STEP_PIN && defined E_DIR_PIN WRITE(E_STEP_PIN, 0); SET_OUTPUT(E_STEP_PIN); WRITE(E_DIR_PIN, 0); SET_OUTPUT(E_DIR_PIN); #endif // Common Stepper Enable #ifdef STEPPER_ENABLE_PIN #ifdef STEPPER_INVERT_ENABLE WRITE(STEPPER_ENABLE_PIN, 0); #else WRITE(STEPPER_ENABLE_PIN, 1); #endif SET_OUTPUT(STEPPER_ENABLE_PIN); #endif // X Stepper Enable #ifdef X_ENABLE_PIN #ifdef X_INVERT_ENABLE WRITE(X_ENABLE_PIN, 0); #else WRITE(X_ENABLE_PIN, 1); #endif SET_OUTPUT(X_ENABLE_PIN); #endif // Y Stepper Enable #ifdef Y_ENABLE_PIN #ifdef Y_INVERT_ENABLE WRITE(Y_ENABLE_PIN, 0); #else WRITE(Y_ENABLE_PIN, 1); #endif SET_OUTPUT(Y_ENABLE_PIN); #endif // Z Stepper Enable #ifdef Z_ENABLE_PIN #ifdef Z_INVERT_ENABLE WRITE(Z_ENABLE_PIN, 0); #else WRITE(Z_ENABLE_PIN, 1); #endif SET_OUTPUT(Z_ENABLE_PIN); #endif // E Stepper Enable #ifdef E_ENABLE_PIN #ifdef E_INVERT_ENABLE WRITE(E_ENABLE_PIN, 0); #else WRITE(E_ENABLE_PIN, 1); #endif SET_OUTPUT(E_ENABLE_PIN); #endif #ifdef STEPPER_ENABLE_PIN power_off(); #endif #ifdef TEMP_MAX6675 // setup SPI WRITE(SCK, 0); SET_OUTPUT(SCK); WRITE(MOSI, 1); SET_OUTPUT(MOSI); WRITE(MISO, 1); SET_INPUT(MISO); WRITE(SS, 1); SET_OUTPUT(SS); #endif #ifdef TEMP_INTERCOM // Enable the RS485 transceiver SET_OUTPUT(RX_ENABLE_PIN); SET_OUTPUT(TX_ENABLE_PIN); WRITE(RX_ENABLE_PIN,0); disable_transmit(); #endif }
void GenerateVertexShader(int prim, char *buffer, bool useHWTransform) { char *p = buffer; // #define USE_FOR_LOOP #if defined(USING_GLES2) WRITE(p, "#version 100\n"); // GLSL ES 1.0 WRITE(p, "precision highp float;\n"); #elif !defined(FORCE_OPENGL_2_0) WRITE(p, "#version 110\n"); // Remove lowp/mediump in non-mobile implementations WRITE(p, "#define lowp\n"); WRITE(p, "#define mediump\n"); #else // Need to remove lowp/mediump for Mac WRITE(p, "#define lowp\n"); WRITE(p, "#define mediump\n"); #endif const u32 vertType = gstate.vertType; int lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled(); int doTexture = gstate.isTextureMapEnabled() && !gstate.isModeClear(); bool hasColor = (vertType & GE_VTYPE_COL_MASK) != 0 || !useHWTransform; bool hasNormal = (vertType & GE_VTYPE_NRM_MASK) != 0 && useHWTransform; bool enableFog = gstate.isFogEnabled() && !gstate.isModeThrough() && !gstate.isModeClear(); bool throughmode = (vertType & GE_VTYPE_THROUGH_MASK) != 0; bool flipV = gstate_c.flipTexture; bool doTextureProjection = gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX; DoLightComputation doLight[4] = {LIGHT_OFF, LIGHT_OFF, LIGHT_OFF, LIGHT_OFF}; if (useHWTransform) { int shadeLight0 = gstate.getUVGenMode() == GE_TEXMAP_ENVIRONMENT_MAP ? gstate.getUVLS0() : -1; int shadeLight1 = gstate.getUVGenMode() == GE_TEXMAP_ENVIRONMENT_MAP ? gstate.getUVLS1() : -1; for (int i = 0; i < 4; i++) { if (i == shadeLight0 || i == shadeLight1) doLight[i] = LIGHT_SHADE; if (gstate.isLightingEnabled() && gstate.isLightChanEnabled(i)) doLight[i] = LIGHT_FULL; } } if (gstate.getWeightMask() != GE_VTYPE_WEIGHT_NONE) { WRITE(p, "%s", boneWeightAttrDecl[TranslateNumBones(gstate.getNumBoneWeights())]); } if (useHWTransform) WRITE(p, "attribute vec3 a_position;\n"); else WRITE(p, "attribute vec4 a_position;\n"); // need to pass the fog coord in w if (useHWTransform && hasNormal) WRITE(p, "attribute mediump vec3 a_normal;\n"); if (doTexture) { if (!useHWTransform && doTextureProjection) WRITE(p, "attribute vec3 a_texcoord;\n"); else WRITE(p, "attribute vec2 a_texcoord;\n"); } if (hasColor) { WRITE(p, "attribute lowp vec4 a_color0;\n"); if (lmode && !useHWTransform) // only software transform supplies color1 as vertex data WRITE(p, "attribute lowp vec3 a_color1;\n"); } if (gstate.isModeThrough()) { WRITE(p, "uniform mat4 u_proj_through;\n"); } else { WRITE(p, "uniform mat4 u_proj;\n"); // Add all the uniforms we'll need to transform properly. } if (useHWTransform) { // When transforming by hardware, we need a great deal more uniforms... WRITE(p, "uniform mat4 u_world;\n"); WRITE(p, "uniform mat4 u_view;\n"); if (gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX) WRITE(p, "uniform mediump mat4 u_texmtx;\n"); if (gstate.getWeightMask() != GE_VTYPE_WEIGHT_NONE) { int numBones = TranslateNumBones(gstate.getNumBoneWeights()); #ifdef USE_BONE_ARRAY WRITE(p, "uniform mediump mat4 u_bone[%i];\n", numBones); #else for (int i = 0; i < numBones; i++) { WRITE(p, "uniform mat4 u_bone%i;\n", i); } #endif } if (doTexture) { WRITE(p, "uniform vec4 u_uvscaleoffset;\n"); } for (int i = 0; i < 4; i++) { if (doLight[i] != LIGHT_OFF) { // This is needed for shade mapping WRITE(p, "uniform vec3 u_lightpos%i;\n", i); } if (doLight[i] == LIGHT_FULL) { // These are needed for the full thing WRITE(p, "uniform mediump vec3 u_lightdir%i;\n", i); GELightType type = gstate.getLightType(i); if (type != GE_LIGHTTYPE_DIRECTIONAL) WRITE(p, "uniform mediump vec3 u_lightatt%i;\n", i); if (type == GE_LIGHTTYPE_SPOT || type == GE_LIGHTTYPE_UNKNOWN) { WRITE(p, "uniform mediump float u_lightangle%i;\n", i); WRITE(p, "uniform mediump float u_lightspotCoef%i;\n", i); } WRITE(p, "uniform lowp vec3 u_lightambient%i;\n", i); WRITE(p, "uniform lowp vec3 u_lightdiffuse%i;\n", i); if (gstate.isUsingSpecularLight(i)) WRITE(p, "uniform lowp vec3 u_lightspecular%i;\n", i); } } if (gstate.isLightingEnabled()) { WRITE(p, "uniform lowp vec4 u_ambient;\n"); if ((gstate.materialupdate & 2) == 0) WRITE(p, "uniform lowp vec3 u_matdiffuse;\n"); // if ((gstate.materialupdate & 4) == 0) WRITE(p, "uniform lowp vec4 u_matspecular;\n"); // Specular coef is contained in alpha WRITE(p, "uniform lowp vec3 u_matemissive;\n"); } } if (useHWTransform || !hasColor) WRITE(p, "uniform lowp vec4 u_matambientalpha;\n"); // matambient + matalpha if (enableFog) { WRITE(p, "uniform vec2 u_fogcoef;\n"); } WRITE(p, "varying lowp vec4 v_color0;\n"); if (lmode) WRITE(p, "varying lowp vec3 v_color1;\n"); if (doTexture) { if (doTextureProjection) WRITE(p, "varying vec3 v_texcoord;\n"); else WRITE(p, "varying vec2 v_texcoord;\n"); } if (enableFog) WRITE(p, "varying float v_fogdepth;\n"); WRITE(p, "void main() {\n"); if (!useHWTransform) { // Simple pass-through of vertex data to fragment shader if (doTexture) WRITE(p, " v_texcoord = a_texcoord;\n"); if (hasColor) { WRITE(p, " v_color0 = a_color0;\n"); if (lmode) WRITE(p, " v_color1 = a_color1;\n"); } else { WRITE(p, " v_color0 = u_matambientalpha;\n"); if (lmode) WRITE(p, " v_color1 = vec3(0.0);\n"); } if (enableFog) { WRITE(p, " v_fogdepth = a_position.w;\n"); } if (gstate.isModeThrough()) { WRITE(p, " gl_Position = u_proj_through * vec4(a_position.xyz, 1.0);\n"); } else { WRITE(p, " gl_Position = u_proj * vec4(a_position.xyz, 1.0);\n"); } } else { // Step 1: World Transform / Skinning if (gstate.getWeightMask() == GE_VTYPE_WEIGHT_NONE) { // No skinning, just standard T&L. WRITE(p, " vec3 worldpos = (u_world * vec4(a_position.xyz, 1.0)).xyz;\n"); if (hasNormal) WRITE(p, " vec3 worldnormal = normalize((u_world * vec4(a_normal, 0.0)).xyz);\n"); else WRITE(p, " vec3 worldnormal = vec3(0.0, 0.0, 1.0);\n"); } else { int numWeights = TranslateNumBones(gstate.getNumBoneWeights()); static const char *rescale[4] = {"", " * 1.9921875", " * 1.999969482421875", ""}; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f}; const char *factor = rescale[gstate.getWeightMask() >> GE_VTYPE_WEIGHT_SHIFT]; static const char * const boneWeightAttr[8] = { "a_w1.x", "a_w1.y", "a_w1.z", "a_w1.w", "a_w2.x", "a_w2.y", "a_w2.z", "a_w2.w", }; #if defined(USE_FOR_LOOP) && defined(USE_BONE_ARRAY) // To loop through the weights, we unfortunately need to put them in a float array. // GLSL ES sucks - no way to directly initialize an array! switch (numWeights) { case 1: WRITE(p, " float w[1]; w[0] = a_w1;\n"); break; case 2: WRITE(p, " float w[2]; w[0] = a_w1.x; w[1] = a_w1.y;\n"); break; case 3: WRITE(p, " float w[3]; w[0] = a_w1.x; w[1] = a_w1.y; w[2] = a_w1.z;\n"); break; case 4: WRITE(p, " float w[4]; w[0] = a_w1.x; w[1] = a_w1.y; w[2] = a_w1.z; w[3] = a_w1.w;\n"); break; case 5: WRITE(p, " float w[5]; w[0] = a_w1.x; w[1] = a_w1.y; w[2] = a_w1.z; w[3] = a_w1.w; w[4] = a_w2;\n"); break; case 6: WRITE(p, " float w[6]; w[0] = a_w1.x; w[1] = a_w1.y; w[2] = a_w1.z; w[3] = a_w1.w; w[4] = a_w2.x; w[5] = a_w2.y;\n"); break; case 7: WRITE(p, " float w[7]; w[0] = a_w1.x; w[1] = a_w1.y; w[2] = a_w1.z; w[3] = a_w1.w; w[4] = a_w2.x; w[5] = a_w2.y; w[6] = a_w2.z;\n"); break; case 8: WRITE(p, " float w[8]; w[0] = a_w1.x; w[1] = a_w1.y; w[2] = a_w1.z; w[3] = a_w1.w; w[4] = a_w2.x; w[5] = a_w2.y; w[6] = a_w2.z; w[7] = a_w2.w;\n"); break; } WRITE(p, " mat4 skinMatrix = w[0] * u_bone[0];\n"); if (numWeights > 1) { WRITE(p, " for (int i = 1; i < %i; i++) {\n", numWeights); WRITE(p, " skinMatrix += w[i] * u_bone[i];\n"); WRITE(p, " }\n"); } #else #ifdef USE_BONE_ARRAY if (numWeights == 1) WRITE(p, " mat4 skinMatrix = a_w1 * u_bone[0]"); else WRITE(p, " mat4 skinMatrix = a_w1.x * u_bone[0]"); for (int i = 1; i < numWeights; i++) { const char *weightAttr = boneWeightAttr[i]; // workaround for "cant do .x of scalar" issue if (numWeights == 1 && i == 0) weightAttr = "a_w1"; if (numWeights == 5 && i == 4) weightAttr = "a_w2"; WRITE(p, " + %s * u_bone[%i]", weightAttr, i); } #else // Uncomment this to screw up bone shaders to check the vertex shader software fallback // WRITE(p, "THIS SHOULD ERROR! #error"); if (numWeights == 1) WRITE(p, " mat4 skinMatrix = a_w1 * u_bone0"); else WRITE(p, " mat4 skinMatrix = a_w1.x * u_bone0"); for (int i = 1; i < numWeights; i++) { const char *weightAttr = boneWeightAttr[i]; // workaround for "cant do .x of scalar" issue if (numWeights == 1 && i == 0) weightAttr = "a_w1"; if (numWeights == 5 && i == 4) weightAttr = "a_w2"; WRITE(p, " + %s * u_bone%i", weightAttr, i); } #endif #endif WRITE(p, ";\n"); // Trying to simplify this results in bugs in LBP... WRITE(p, " vec3 skinnedpos = (skinMatrix * vec4(a_position, 1.0)).xyz %s;\n", factor); WRITE(p, " vec3 worldpos = (u_world * vec4(skinnedpos, 1.0)).xyz;\n"); if (hasNormal) { WRITE(p, " vec3 skinnednormal = (skinMatrix * vec4(a_normal, 0.0)).xyz %s;\n", factor); WRITE(p, " vec3 worldnormal = normalize((u_world * vec4(skinnednormal, 0.0)).xyz);\n"); } else { WRITE(p, " vec3 worldnormal = (u_world * (skinMatrix * vec4(0.0, 0.0, 1.0, 0.0))).xyz;\n"); } } WRITE(p, " vec4 viewPos = u_view * vec4(worldpos, 1.0);\n"); // Final view and projection transforms. WRITE(p, " gl_Position = u_proj * viewPos;\n"); // TODO: Declare variables for dots for shade mapping if needed. const char *ambientStr = (gstate.materialupdate & 1) ? (hasColor ? "a_color0" : "u_matambientalpha") : "u_matambientalpha"; const char *diffuseStr = (gstate.materialupdate & 2) ? (hasColor ? "a_color0.rgb" : "u_matambientalpha.rgb") : "u_matdiffuse"; const char *specularStr = (gstate.materialupdate & 4) ? (hasColor ? "a_color0.rgb" : "u_matambientalpha.rgb") : "u_matspecular.rgb"; bool diffuseIsZero = true; bool specularIsZero = true; bool distanceNeeded = false; if (gstate.isLightingEnabled()) { WRITE(p, " lowp vec4 lightSum0 = u_ambient * %s + vec4(u_matemissive, 0.0);\n", ambientStr); for (int i = 0; i < 4; i++) { if (doLight[i] != LIGHT_FULL) continue; diffuseIsZero = false; if (gstate.isUsingSpecularLight(i)) specularIsZero = false; GELightType type = gstate.getLightType(i); if (type != GE_LIGHTTYPE_DIRECTIONAL) distanceNeeded = true; } if (!specularIsZero) { WRITE(p, " lowp vec3 lightSum1 = vec3(0.0);\n"); } if (!diffuseIsZero) { WRITE(p, " vec3 toLight;\n"); WRITE(p, " lowp vec3 diffuse;\n"); } if (distanceNeeded) { WRITE(p, " float distance;\n"); WRITE(p, " lowp float lightScale;\n"); } } // Calculate lights if needed. If shade mapping is enabled, lights may need to be // at least partially calculated. for (int i = 0; i < 4; i++) { if (doLight[i] != LIGHT_FULL) continue; GELightType type = gstate.getLightType(i); if (type == GE_LIGHTTYPE_DIRECTIONAL) { // We prenormalize light positions for directional lights. WRITE(p, " toLight = u_lightpos%i;\n", i); } else { WRITE(p, " toLight = u_lightpos%i - worldpos;\n", i); WRITE(p, " distance = length(toLight);\n"); WRITE(p, " toLight /= distance;\n"); } bool doSpecular = gstate.isUsingSpecularLight(i); bool poweredDiffuse = gstate.isUsingPoweredDiffuseLight(i); if (poweredDiffuse) { WRITE(p, " mediump float dot%i = pow(dot(toLight, worldnormal), u_matspecular.a);\n", i); } else { WRITE(p, " mediump float dot%i = dot(toLight, worldnormal);\n", i); } const char *timesLightScale = " * lightScale"; // Attenuation switch (type) { case GE_LIGHTTYPE_DIRECTIONAL: timesLightScale = ""; break; case GE_LIGHTTYPE_POINT: WRITE(p, " lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0);\n", i); break; case GE_LIGHTTYPE_SPOT: case GE_LIGHTTYPE_UNKNOWN: WRITE(p, " lowp float angle%i = dot(normalize(u_lightdir%i), toLight);\n", i, i); WRITE(p, " if (angle%i >= u_lightangle%i) {\n", i, i); WRITE(p, " lightScale = clamp(1.0 / dot(u_lightatt%i, vec3(1.0, distance, distance*distance)), 0.0, 1.0) * pow(angle%i, u_lightspotCoef%i);\n", i, i, i); WRITE(p, " } else {\n"); WRITE(p, " lightScale = 0.0;\n"); WRITE(p, " }\n"); break; default: // ILLEGAL break; } WRITE(p, " diffuse = (u_lightdiffuse%i * %s) * max(dot%i, 0.0);\n", i, diffuseStr, i); if (doSpecular) { WRITE(p, " dot%i = dot(normalize(toLight + vec3(0.0, 0.0, 1.0)), worldnormal);\n", i); WRITE(p, " if (dot%i > 0.0)\n", i); WRITE(p, " lightSum1 += u_lightspecular%i * %s * (pow(dot%i, u_matspecular.a) %s);\n", i, specularStr, i, timesLightScale); } WRITE(p, " lightSum0.rgb += (u_lightambient%i * %s.rgb + diffuse)%s;\n", i, ambientStr, timesLightScale); } if (gstate.isLightingEnabled()) { // Sum up ambient, emissive here. if (lmode) { WRITE(p, " v_color0 = clamp(lightSum0, 0.0, 1.0);\n"); // v_color1 only exists when lmode = 1. if (specularIsZero) { WRITE(p, " v_color1 = vec3(0.0);\n"); } else { WRITE(p, " v_color1 = clamp(lightSum1, 0.0, 1.0);\n"); } } else { if (specularIsZero) { WRITE(p, " v_color0 = clamp(lightSum0, 0.0, 1.0);\n"); } else { WRITE(p, " v_color0 = clamp(clamp(lightSum0, 0.0, 1.0) + vec4(lightSum1, 0.0), 0.0, 1.0);\n"); } } } else { // Lighting doesn't affect color. if (hasColor) { WRITE(p, " v_color0 = a_color0;\n"); } else { WRITE(p, " v_color0 = u_matambientalpha;\n"); } if (lmode) WRITE(p, " v_color1 = vec3(0.0);\n"); } // Step 3: UV generation if (doTexture) { bool prescale = g_Config.bPrescaleUV && !throughmode && gstate.getTextureFunction() == 0; switch (gstate.getUVGenMode()) { case GE_TEXMAP_TEXTURE_COORDS: // Scale-offset. Easy. case GE_TEXMAP_UNKNOWN: // Not sure what this is, but Riviera uses it. Treating as coords works. if (prescale) { WRITE(p, " v_texcoord = a_texcoord;\n"); } else { WRITE(p, " v_texcoord = a_texcoord * u_uvscaleoffset.xy + u_uvscaleoffset.zw;\n"); } break; case GE_TEXMAP_TEXTURE_MATRIX: // Projection mapping. { std::string temp_tc; switch (gstate.getUVProjMode()) { case GE_PROJMAP_POSITION: // Use model space XYZ as source temp_tc = "vec4(a_position.xyz, 1.0)"; break; case GE_PROJMAP_UV: // Use unscaled UV as source { static const char *rescaleuv[4] = {"", " * 1.9921875", " * 1.999969482421875", ""}; // 2*127.5f/128.f, 2*32767.5f/32768.f, 1.0f}; const char *factor = rescaleuv[(vertType & GE_VTYPE_TC_MASK) >> GE_VTYPE_TC_SHIFT]; temp_tc = StringFromFormat("vec4(a_texcoord.xy %s, 0.0, 1.0)", factor); } break; case GE_PROJMAP_NORMALIZED_NORMAL: // Use normalized transformed normal as source if (hasNormal) temp_tc = "vec4(normalize(a_normal), 1.0)"; else temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)"; break; case GE_PROJMAP_NORMAL: // Use non-normalized transformed normal as source if (hasNormal) temp_tc = "vec4(a_normal, 1.0)"; else temp_tc = "vec4(0.0, 0.0, 1.0, 1.0)"; break; } WRITE(p, " v_texcoord = (u_texmtx * %s).xyz * vec3(u_uvscaleoffset.xy, 1.0);\n", temp_tc.c_str()); } // Transform by texture matrix. XYZ as we are doing projection mapping. break; case GE_TEXMAP_ENVIRONMENT_MAP: // Shade mapping - use dots from light sources. WRITE(p, " v_texcoord = u_uvscaleoffset.xy * vec2(1.0 + dot(normalize(u_lightpos%i), worldnormal), 1.0 - dot(normalize(u_lightpos%i), worldnormal)) * 0.5;\n", gstate.getUVLS0(), gstate.getUVLS1()); break; default: // ILLEGAL break; } if (flipV) WRITE(p, " v_texcoord.y = 1.0 - v_texcoord.y;\n"); } // Compute fogdepth if (enableFog) WRITE(p, " v_fogdepth = (viewPos.z + u_fogcoef.x) * u_fogcoef.y;\n"); } WRITE(p, "}\n"); }
static void test_ext_or_handshake(void *arg) { or_connection_t *conn=NULL; char b[256]; (void) arg; MOCK(connection_write_to_buf_impl_, connection_write_to_buf_impl_replacement); /* Use same authenticators as for test_ext_or_cookie_auth_testvec */ ext_or_auth_cookie = tor_malloc_zero(32); memcpy(ext_or_auth_cookie, "Gliding wrapt in a brown mantle," , 32); ext_or_auth_cookie_is_set = 1; init_connection_lists(); conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET); tt_int_op(0, OP_EQ, connection_ext_or_start_auth(conn)); /* The server starts by telling us about the one supported authtype. */ CONTAINS("\x01\x00", 2); /* Say the client hasn't responded yet. */ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); /* Let's say the client replies badly. */ WRITE("\x99", 1); tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("", 0); tt_assert(TO_CONN(conn)->marked_for_close); close_closeable_connections(); conn = NULL; /* Okay, try again. */ conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET); tt_int_op(0, OP_EQ, connection_ext_or_start_auth(conn)); CONTAINS("\x01\x00", 2); /* Let's say the client replies sensibly this time. "Yes, AUTHTYPE_COOKIE * sounds delicious. Let's have some of that!" */ WRITE("\x01", 1); /* Let's say that the client also sends part of a nonce. */ WRITE("But when I look ", 16); tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("", 0); tt_int_op(TO_CONN(conn)->state, OP_EQ, EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE); /* Pump it again. Nothing should happen. */ tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); /* send the rest of the nonce. */ WRITE("ahead up the whi", 16); MOCK(crypto_rand, crypto_rand_return_tse_str); tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); UNMOCK(crypto_rand); /* We should get the right reply from the server. */ CONTAINS("\xec\x80\xed\x6e\x54\x6d\x3b\x36\xfd\xfc\x22\xfe\x13\x15\x41\x6b" "\x02\x9f\x1a\xde\x76\x10\xd9\x10\x87\x8b\x62\xee\xb7\x40\x38\x21" "te road There is always another ", 64); /* Send the wrong response. */ WRITE("not with a bang but a whimper...", 32); MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem); tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("\x00", 1); tt_assert(TO_CONN(conn)->marked_for_close); /* XXXX Hold-open-until-flushed. */ close_closeable_connections(); conn = NULL; UNMOCK(control_event_bootstrap_problem); MOCK(connection_start_reading, note_read_started); MOCK(connection_stop_reading, note_read_stopped); MOCK(connection_tls_start_handshake, handshake_start); /* Okay, this time let's succeed. */ conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET); do_ext_or_handshake(conn); /* Now let's run through some messages. */ /* First let's send some junk and make sure it's ignored. */ WRITE("\xff\xf0\x00\x03""ABC", 7); tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("", 0); /* Now let's send a USERADDR command. */ WRITE("\x00\x01\x00\x0c""1.2.3.4:5678", 16); tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); tt_int_op(TO_CONN(conn)->port, OP_EQ, 5678); tt_int_op(tor_addr_to_ipv4h(&TO_CONN(conn)->addr), OP_EQ, 0x01020304); /* Now let's send a TRANSPORT command. */ WRITE("\x00\x02\x00\x07""rfc1149", 11); tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); tt_ptr_op(NULL, OP_NE, conn->ext_or_transport); tt_str_op("rfc1149", OP_EQ, conn->ext_or_transport); tt_int_op(is_reading,OP_EQ,1); tt_int_op(TO_CONN(conn)->state, OP_EQ, EXT_OR_CONN_STATE_OPEN); /* DONE */ WRITE("\x00\x00\x00\x00", 4); tt_int_op(0, OP_EQ, connection_ext_or_process_inbuf(conn)); tt_int_op(TO_CONN(conn)->state, OP_EQ, EXT_OR_CONN_STATE_FLUSHING); tt_int_op(is_reading,OP_EQ,0); CONTAINS("\x10\x00\x00\x00", 4); tt_int_op(handshake_start_called,OP_EQ,0); tt_int_op(0, OP_EQ, connection_ext_or_finished_flushing(conn)); tt_int_op(is_reading,OP_EQ,1); tt_int_op(handshake_start_called,OP_EQ,1); tt_int_op(TO_CONN(conn)->type, OP_EQ, CONN_TYPE_OR); tt_int_op(TO_CONN(conn)->state, OP_EQ, 0); close_closeable_connections(); conn = NULL; /* Okay, this time let's succeed the handshake but fail the USERADDR command. */ conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET); do_ext_or_handshake(conn); /* USERADDR command with an extra NUL byte */ WRITE("\x00\x01\x00\x0d""1.2.3.4:5678\x00", 17); MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem); tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("", 0); tt_assert(TO_CONN(conn)->marked_for_close); close_closeable_connections(); conn = NULL; UNMOCK(control_event_bootstrap_problem); /* Now fail the TRANSPORT command. */ conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET); do_ext_or_handshake(conn); /* TRANSPORT command with an extra NUL byte */ WRITE("\x00\x02\x00\x08""rfc1149\x00", 12); MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem); tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("", 0); tt_assert(TO_CONN(conn)->marked_for_close); close_closeable_connections(); conn = NULL; UNMOCK(control_event_bootstrap_problem); /* Now fail the TRANSPORT command. */ conn = or_connection_new(CONN_TYPE_EXT_OR, AF_INET); do_ext_or_handshake(conn); /* TRANSPORT command with transport name with symbols (not a C-identifier) */ WRITE("\x00\x02\x00\x07""rf*1149", 11); MOCK(control_event_bootstrap_problem, ignore_bootstrap_problem); tt_int_op(-1, OP_EQ, connection_ext_or_process_inbuf(conn)); CONTAINS("", 0); tt_assert(TO_CONN(conn)->marked_for_close); close_closeable_connections(); conn = NULL; UNMOCK(control_event_bootstrap_problem); done: UNMOCK(connection_write_to_buf_impl_); UNMOCK(crypto_rand); if (conn) connection_free_(TO_CONN(conn)); #undef CONTAINS #undef WRITE }
int main(int argc, char *argv[]) { START(argc, argv, "pmem_map_raw"); if (argc != 2) FATAL("usage: %s file", argv[0]); int fd; void *addr; fd = OPEN(argv[1], O_RDWR); struct stat stbuf; FSTAT(fd, &stbuf); char pat[CHECK_BYTES]; char buf[CHECK_BYTES]; addr = pmem_map(fd); if (addr == NULL) { OUT("!pmem_map"); goto err; } /* write some pattern to the file */ memset(pat, 0x5A, CHECK_BYTES); WRITE(fd, pat, CHECK_BYTES); if (memcmp(pat, addr, CHECK_BYTES)) OUT("%s: first %d bytes do not match", argv[1], CHECK_BYTES); /* fill up mapped region with new pattern */ memset(pat, 0xA5, CHECK_BYTES); memcpy(addr, pat, CHECK_BYTES); MUNMAP(addr, stbuf.st_size); LSEEK(fd, (off_t)0, SEEK_SET); if (READ(fd, buf, CHECK_BYTES) == CHECK_BYTES) { if (memcmp(pat, buf, CHECK_BYTES)) OUT("%s: first %d bytes do not match", argv[1], CHECK_BYTES); } CLOSE(fd); /* re-open the file with read-only access */ fd = OPEN(argv[1], O_RDONLY); addr = pmem_map(fd); if (addr != NULL) { MUNMAP(addr, stbuf.st_size); OUT("expected pmem_map failure"); } err: CLOSE(fd); DONE(NULL); }
// Uses integer instructions available since OpenGL 3.0. Suitable for ES 3.0 as well. void GenerateDepalShader300(char *buffer, GEBufferFormat pixelFormat) { char *p = buffer; #ifdef USING_GLES2 WRITE(p, "#version 300 es\n"); WRITE(p, "precision mediump float;\n"); #else WRITE(p, "#version 330\n"); #endif WRITE(p, "in vec2 v_texcoord0;\n"); WRITE(p, "out vec4 fragColor0;\n"); WRITE(p, "uniform sampler2D tex;\n"); WRITE(p, "uniform sampler2D pal;\n"); WRITE(p, "void main() {\n"); WRITE(p, " vec4 color = texture(tex, v_texcoord0);\n"); int mask = gstate.getClutIndexMask(); int shift = gstate.getClutIndexShift(); int offset = gstate.getClutIndexStartPos(); const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); // Unfortunately sampling turned our texture into floating point. To avoid this, might be able // to declare them as isampler2D objects, but these require integer textures, which needs more work. // Anyhow, we simply work around this by converting back to integer. Hopefully there will be no loss of precision. // Use the mask to skip reading some components. int shiftedMask = mask << shift; switch (pixelFormat) { case GE_FORMAT_8888: if (shiftedMask & 0xFF) WRITE(p, " int r = int(color.r * 255.99);\n"); else WRITE(p, " int r = 0;\n"); if (shiftedMask & 0xFF00) WRITE(p, " int g = int(color.g * 255.99);\n"); else WRITE(p, " int g = 0;\n"); if (shiftedMask & 0xFF0000) WRITE(p, " int b = int(color.b * 255.99);\n"); else WRITE(p, " int b = 0;\n"); if (shiftedMask & 0xFF000000) WRITE(p, " int a = int(color.a * 255.99);\n"); else WRITE(p, " int a = 0;\n"); WRITE(p, " int index = (a << 24) | (b << 16) | (g << 8) | (r);\n"); break; case GE_FORMAT_4444: if (shiftedMask & 0xF) WRITE(p, " int r = int(color.r * 15.99);\n"); else WRITE(p, " int r = 0;\n"); if (shiftedMask & 0xF0) WRITE(p, " int g = int(color.g * 15.99);\n"); else WRITE(p, " int g = 0;\n"); if (shiftedMask & 0xF00) WRITE(p, " int b = int(color.b * 15.99);\n"); else WRITE(p, " int b = 0;\n"); if (shiftedMask & 0xF000) WRITE(p, " int a = int(color.a * 15.99);\n"); else WRITE(p, " int a = 0;\n"); WRITE(p, " int index = (a << 12) | (b << 8) | (g << 4) | (r);\n"); break; case GE_FORMAT_565: if (shiftedMask & 0x1F) WRITE(p, " int r = int(color.r * 31.99);\n"); else WRITE(p, " int r = 0;\n"); if (shiftedMask & 0x7E0) WRITE(p, " int g = int(color.g * 63.99);\n"); else WRITE(p, " int g = 0;\n"); if (shiftedMask & 0xF800) WRITE(p, " int b = int(color.b * 31.99);\n"); else WRITE(p, " int b = 0;\n"); WRITE(p, " int index = (b << 11) | (g << 5) | (r);\n"); break; case GE_FORMAT_5551: if (shiftedMask & 0x1F) WRITE(p, " int r = int(color.r * 31.99);\n"); else WRITE(p, " int r = 0;\n"); if (shiftedMask & 0x3E0) WRITE(p, " int g = int(color.g * 31.99);\n"); else WRITE(p, " int g = 0;\n"); if (shiftedMask & 0x7C00) WRITE(p, " int b = int(color.b * 31.99);\n"); else WRITE(p, " int b = 0;\n"); if (shiftedMask & 0x8000) WRITE(p, " int a = int(color.a);\n"); else WRITE(p, " int a = 0;\n"); WRITE(p, " int index = (a << 15) | (b << 10) | (g << 5) | (r);\n"); break; default: break; } float texturePixels = 256; if (clutFormat != GE_CMODE_32BIT_ABGR8888) texturePixels = 512; if (shift) { WRITE(p, " index = ((index >> %i) & 0x%02x)", shift, mask); } else { WRITE(p, " index = (index & 0x%02x)", mask); } if (offset) { WRITE(p, " | %i;\n", offset); // '|' matches what we have in gstate.h } else { WRITE(p, ";\n"); } WRITE(p, " fragColor0 = texture(pal, vec2((float(index) + 0.5) * (1.0 / %f), 0.0));\n", texturePixels); WRITE(p, "}\n"); }
// FP only, to suit GL(ES) 2.0 void GenerateDepalShaderFloat(char *buffer, GEBufferFormat pixelFormat, ShaderLanguage lang) { char *p = buffer; const char *modFunc = lang == HLSL_DX9 ? "fmod" : "mod"; char lookupMethod[128] = "index.r"; char offset[128] = ""; const GEPaletteFormat clutFormat = gstate.getClutPaletteFormat(); const u32 clutBase = gstate.getClutIndexStartPos(); const int shift = gstate.getClutIndexShift(); const int mask = gstate.getClutIndexMask(); float index_multiplier = 1.0f; // pixelformat is the format of the texture we are sampling. bool formatOK = true; switch (pixelFormat) { case GE_FORMAT_8888: if ((mask & (mask + 1)) == 0) { // If the value has all bits contiguous (bitmask check above), we can mod by it + 1. const char *rgba = "rrrrrrrrggggggggbbbbbbbbaaaaaaaa"; const u8 rgba_shift = shift & 7; if (rgba_shift == 0 && mask == 0xFF) { sprintf(lookupMethod, "index.%c", rgba[shift]); } else { sprintf(lookupMethod, "%s(index.%c * %f, %d.0)", modFunc, rgba[shift], 255.99f / (1 << rgba_shift), mask + 1); index_multiplier = 1.0f / 256.0f; // Format was OK if there weren't bits from another component. formatOK = mask <= 255 - (1 << rgba_shift); } } else { formatOK = false; } break; case GE_FORMAT_4444: if ((mask & (mask + 1)) == 0 && shift < 16) { const char *rgba = "rrrrggggbbbbaaaa"; const u8 rgba_shift = shift & 3; if (rgba_shift == 0 && mask == 0xF) { sprintf(lookupMethod, "index.%c", rgba[shift]); index_multiplier = 15.0f / 256.0f; } else { // Let's divide and mod to get the right bits. A common case is shift=0, mask=01. sprintf(lookupMethod, "%s(index.%c * %f, %d.0)", modFunc, rgba[shift], 15.99f / (1 << rgba_shift), mask + 1); index_multiplier = 1.0f / 256.0f; formatOK = mask <= 15 - (1 << rgba_shift); } } else { formatOK = false; } break; case GE_FORMAT_565: if ((mask & (mask + 1)) == 0 && shift < 16) { const u8 shifts[16] = { 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4 }; const int multipliers[16] = { 31, 31, 31, 31, 31, 63, 63, 63, 63, 63, 63, 31, 31, 31, 31, 31 }; const char *rgba = "rrrrrggggggbbbbb"; const u8 rgba_shift = shifts[shift]; if (rgba_shift == 0 && mask == multipliers[shift]) { sprintf(lookupMethod, "index.%c", rgba[shift]); index_multiplier = multipliers[shift] / 256.0f; } else { // We just need to divide the right component by the right value, and then mod against the mask. // A common case is shift=1, mask=0f. sprintf(lookupMethod, "%s(index.%c * %f, %d.0)", modFunc, rgba[shift], ((float)multipliers[shift] + 0.99f) / (1 << rgba_shift), mask + 1); index_multiplier = 1.0f / 256.0f; formatOK = mask <= multipliers[shift] - (1 << rgba_shift); } } else { formatOK = false; } break; case GE_FORMAT_5551: if ((mask & (mask + 1)) == 0 && shift < 16) { const char *rgba = "rrrrrgggggbbbbba"; const u8 rgba_shift = shift % 5; if (rgba_shift == 0 && mask == 0x1F) { sprintf(lookupMethod, "index.%c", rgba[shift]); index_multiplier = 31.0f / 256.0f; } else if (shift == 15 && mask == 1) { sprintf(lookupMethod, "index.%c", rgba[shift]); index_multiplier = 1.0f / 256.0f; } else { // A isn't possible here. sprintf(lookupMethod, "%s(index.%c * %f, %d.0)", modFunc, rgba[shift], 31.99f / (1 << rgba_shift), mask + 1); index_multiplier = 1.0f / 256.0f; formatOK = mask <= 31 - (1 << rgba_shift); } } else { formatOK = false; } break; default: break; } float texturePixels = 256.f; if (clutFormat != GE_CMODE_32BIT_ABGR8888) { texturePixels = 512.f; index_multiplier *= 0.5f; } // Adjust index_multiplier, similar to the use of 15.99 instead of 16 in the ES 3 path. // index_multiplier -= 0.01f / texturePixels; if (!formatOK) { ERROR_LOG_REPORT_ONCE(depal, G3D, "%i depal unsupported: shift=%i mask=%02x offset=%d", pixelFormat, shift, mask, clutBase); } // Offset by half a texel (plus clutBase) to turn NEAREST filtering into FLOOR. float texel_offset = ((float)clutBase + 0.5f) / texturePixels; sprintf(offset, " + %f", texel_offset); if (lang == GLSL_140) { #ifdef USING_GLES2 WRITE(p, "#version 100\n"); WRITE(p, "precision mediump float;\n"); #else WRITE(p, "#version 110\n"); #endif WRITE(p, "varying vec2 v_texcoord0;\n"); WRITE(p, "uniform sampler2D tex;\n"); WRITE(p, "uniform sampler2D pal;\n"); WRITE(p, "void main() {\n"); WRITE(p, " vec4 index = texture2D(tex, v_texcoord0);\n"); WRITE(p, " float coord = (%s * %f)%s;\n", lookupMethod, index_multiplier, offset); WRITE(p, " gl_FragColor = texture2D(pal, vec2(coord, 0.0));\n"); WRITE(p, "}\n"); } else if (lang == HLSL_DX9) { WRITE(p, "sampler tex: register(s0);\n"); WRITE(p, "sampler pal: register(s1);\n"); WRITE(p, "float4 main(float2 v_texcoord0 : TEXCOORD0) : COLOR0 {\n"); WRITE(p, " float4 index = tex2D(tex, v_texcoord0);\n"); WRITE(p, " float coord = (%s * %f)%s;\n", lookupMethod, index_multiplier, offset); WRITE(p, " return tex2D(pal, float2(coord, 0.0)).bgra;\n"); WRITE(p, "}\n"); } }
/*-----------------------------------------------------------------------------------*/ static void skip_frame(void) { WRITE(0x0102, PPDATA | 0x0040); }
// Missing: Z depth range void GenerateFragmentShader(char *buffer) { char *p = buffer; // In GLSL ES 3.0, you use "in" variables instead of varying. bool glslES30 = false; const char *varying = "varying"; const char *fragColor0 = "gl_FragColor"; const char *texture = "texture2D"; bool highpFog = false; #if defined(USING_GLES2) // Let's wait until we have a real use for this. // ES doesn't support dual source alpha :( if (gl_extensions.GLES3) { WRITE(p, "#version 300 es\n"); // GLSL ES 1.0 fragColor0 = "fragColor0"; texture = "texture"; glslES30 = true; } else { WRITE(p, "#version 100\n"); // GLSL ES 1.0 } WRITE(p, "precision lowp float;\n"); // PowerVR needs highp to do the fog in MHU correctly. // Others don't, and some can't handle highp in the fragment shader. highpFog = gl_extensions.gpuVendor == GPU_VENDOR_POWERVR; #elif !defined(FORCE_OPENGL_2_0) if (gl_extensions.VersionGEThan(3, 3, 0)) { fragColor0 = "fragColor0"; texture = "texture"; glslES30 = true; WRITE(p, "#version 330\n"); } else if (gl_extensions.VersionGEThan(3, 0, 0)) { fragColor0 = "fragColor0"; WRITE(p, "#version 130\n"); // Remove lowp/mediump in non-mobile non-glsl 3 implementations WRITE(p, "#define lowp\n"); WRITE(p, "#define mediump\n"); WRITE(p, "#define highp\n"); } else { WRITE(p, "#version 110\n"); // Remove lowp/mediump in non-mobile non-glsl 3 implementations WRITE(p, "#define lowp\n"); WRITE(p, "#define mediump\n"); WRITE(p, "#define highp\n"); } #else // Need to remove lowp/mediump for Mac WRITE(p, "#define lowp\n"); WRITE(p, "#define mediump\n"); WRITE(p, "#define highp\n"); #endif if (glslES30) { varying = "in"; } bool lmode = gstate.isUsingSecondaryColor() && gstate.isLightingEnabled(); bool doTexture = gstate.isTextureMapEnabled() && !gstate.isModeClear(); bool enableFog = gstate.isFogEnabled() && !gstate.isModeThrough() && !gstate.isModeClear(); bool enableAlphaTest = gstate.isAlphaTestEnabled() && !IsAlphaTestTriviallyTrue() && !gstate.isModeClear() && !g_Config.bDisableAlphaTest; bool enableColorTest = gstate.isColorTestEnabled() && !IsColorTestTriviallyTrue() && !gstate.isModeClear(); bool enableColorDoubling = gstate.isColorDoublingEnabled(); // This isn't really correct, but it's a hack to get doubled blend modes to work more correctly. bool enableAlphaDoubling = CanDoubleSrcBlendMode(); bool doTextureProjection = gstate.getUVGenMode() == GE_TEXMAP_TEXTURE_MATRIX; bool doTextureAlpha = gstate.isTextureAlphaUsed(); ReplaceAlphaType stencilToAlpha = ReplaceAlphaWithStencil(); if (gstate_c.textureFullAlpha && gstate.getTextureFunction() != GE_TEXFUNC_REPLACE) doTextureAlpha = false; if (doTexture) WRITE(p, "uniform sampler2D tex;\n"); if (enableAlphaTest || enableColorTest) { WRITE(p, "uniform vec4 u_alphacolorref;\n"); } if (stencilToAlpha && ReplaceAlphaWithStencilType() == STENCIL_VALUE_UNIFORM) { WRITE(p, "uniform float u_stencilReplaceValue;\n"); } if (gstate.isTextureMapEnabled() && gstate.getTextureFunction() == GE_TEXFUNC_BLEND) WRITE(p, "uniform vec3 u_texenv;\n"); WRITE(p, "%s vec4 v_color0;\n", varying); if (lmode) WRITE(p, "%s vec3 v_color1;\n", varying); if (enableFog) { WRITE(p, "uniform vec3 u_fogcolor;\n"); WRITE(p, "%s %s float v_fogdepth;\n", varying, highpFog ? "highp" : "mediump"); } if (doTexture) { if (doTextureProjection) WRITE(p, "%s mediump vec3 v_texcoord;\n", varying); else WRITE(p, "%s mediump vec2 v_texcoord;\n", varying); } if (enableAlphaTest) { if (gl_extensions.gpuVendor == GPU_VENDOR_POWERVR) WRITE(p, "float roundTo255thf(in mediump float x) { mediump float y = x + (0.5/255.0); return y - fract(y * 255.0) * (1.0 / 255.0); }\n"); else WRITE(p, "float roundAndScaleTo255f(in float x) { return floor(x * 255.0 + 0.5); }\n"); } if (enableColorTest) { if (gl_extensions.gpuVendor == GPU_VENDOR_POWERVR) WRITE(p, "vec3 roundTo255thv(in vec3 x) { vec3 y = x + (0.5/255.0); return y - fract(y * 255.0) * (1.0 / 255.0); }\n"); else WRITE(p, "vec3 roundAndScaleTo255v(in vec3 x) { return floor(x * 255.0 + 0.5); }\n"); } if (stencilToAlpha == REPLACE_ALPHA_DUALSOURCE) { WRITE(p, "out vec4 fragColor0;\n"); WRITE(p, "out vec4 fragColor1;\n"); } else if (gl_extensions.VersionGEThan(3, 0, 0)) { WRITE(p, "out vec4 fragColor0;\n"); } WRITE(p, "void main() {\n"); if (gstate.isModeClear()) { // Clear mode does not allow any fancy shading. WRITE(p, " vec4 v = v_color0;\n"); } else { const char *secondary = ""; // Secondary color for specular on top of texture if (lmode) { WRITE(p, " vec4 s = vec4(v_color1, 0.0);\n"); secondary = " + s"; } else { secondary = ""; } if (gstate.isTextureMapEnabled()) { if (doTextureProjection) { WRITE(p, " vec4 t = %sProj(tex, v_texcoord);\n", texture); } else { WRITE(p, " vec4 t = %s(tex, v_texcoord);\n", texture); } WRITE(p, " vec4 p = v_color0;\n"); if (doTextureAlpha) { // texfmt == RGBA switch (gstate.getTextureFunction()) { case GE_TEXFUNC_MODULATE: WRITE(p, " vec4 v = p * t%s;\n", secondary); break; case GE_TEXFUNC_DECAL: WRITE(p, " vec4 v = vec4(mix(p.rgb, t.rgb, t.a), p.a)%s;\n", secondary); break; case GE_TEXFUNC_BLEND: WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a * t.a)%s;\n", secondary); break; case GE_TEXFUNC_REPLACE: WRITE(p, " vec4 v = t%s;\n", secondary); break; case GE_TEXFUNC_ADD: case GE_TEXFUNC_UNKNOWN1: case GE_TEXFUNC_UNKNOWN2: case GE_TEXFUNC_UNKNOWN3: WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a * t.a)%s;\n", secondary); break; default: WRITE(p, " vec4 v = p;\n"); break; } } else { // texfmt == RGB switch (gstate.getTextureFunction()) { case GE_TEXFUNC_MODULATE: WRITE(p, " vec4 v = vec4(t.rgb * p.rgb, p.a)%s;\n", secondary); break; case GE_TEXFUNC_DECAL: WRITE(p, " vec4 v = vec4(t.rgb, p.a)%s;\n", secondary); break; case GE_TEXFUNC_BLEND: WRITE(p, " vec4 v = vec4(mix(p.rgb, u_texenv.rgb, t.rgb), p.a)%s;\n", secondary); break; case GE_TEXFUNC_REPLACE: WRITE(p, " vec4 v = vec4(t.rgb, p.a)%s;\n", secondary); break; case GE_TEXFUNC_ADD: case GE_TEXFUNC_UNKNOWN1: case GE_TEXFUNC_UNKNOWN2: case GE_TEXFUNC_UNKNOWN3: WRITE(p, " vec4 v = vec4(p.rgb + t.rgb, p.a)%s;\n", secondary); break; default: WRITE(p, " vec4 v = p;\n"); break; } } } else { // No texture mapping WRITE(p, " vec4 v = v_color0 %s;\n", secondary); } if (enableAlphaTest) { GEComparison alphaTestFunc = gstate.getAlphaTestFunction(); const char *alphaTestFuncs[] = { "#", "#", " != ", " == ", " >= ", " > ", " <= ", " < " }; // never/always don't make sense if (alphaTestFuncs[alphaTestFunc][0] != '#') { if (gl_extensions.gpuVendor == GPU_VENDOR_POWERVR) { // Work around bad PVR driver problem where equality check + discard just doesn't work. if (alphaTestFunc != 3) WRITE(p, " if (roundTo255thf(v.a) %s u_alphacolorref.a) discard;\n", alphaTestFuncs[alphaTestFunc]); } else { WRITE(p, " if (roundAndScaleTo255f(v.a) %s u_alphacolorref.a) discard;\n", alphaTestFuncs[alphaTestFunc]); } } } // TODO: Before or after the color test? if (enableColorDoubling && enableAlphaDoubling) { WRITE(p, " v = v * 2.0;\n"); } else if (enableColorDoubling) { WRITE(p, " v.rgb = v.rgb * 2.0;\n"); } else if (enableAlphaDoubling) { WRITE(p, " v.a = v.a * 2.0;\n"); } if (enableColorTest) { GEComparison colorTestFunc = gstate.getColorTestFunction(); const char *colorTestFuncs[] = { "#", "#", " != ", " == " }; // never/always don't make sense WARN_LOG_REPORT_ONCE(colortest, G3D, "Color test function : %s", colorTestFuncs[colorTestFunc]); u32 colorTestMask = gstate.getColorTestMask(); if (colorTestFuncs[colorTestFunc][0] != '#') { if (gl_extensions.gpuVendor == GPU_VENDOR_POWERVR) WRITE(p, " if (roundTo255thv(v.rgb) %s u_alphacolorref.rgb) discard;\n", colorTestFuncs[colorTestFunc]); else WRITE(p, " if (roundAndScaleTo255v(v.rgb) %s u_alphacolorref.rgb) discard;\n", colorTestFuncs[colorTestFunc]); } } if (enableFog) { WRITE(p, " float fogCoef = clamp(v_fogdepth, 0.0, 1.0);\n"); WRITE(p, " v = mix(vec4(u_fogcolor, v.a), v, fogCoef);\n"); // WRITE(p, " v.x = v_depth;\n"); } } switch (stencilToAlpha) { case REPLACE_ALPHA_DUALSOURCE: WRITE(p, " fragColor0 = vec4(v.rgb, 0.0);\n"); WRITE(p, " fragColor1 = vec4(0.0, 0.0, 0.0, v.a);\n"); break; case REPLACE_ALPHA_YES: WRITE(p, " %s = vec4(v.rgb, 0.0);\n", fragColor0); break; case REPLACE_ALPHA_NO: WRITE(p, " %s = v;\n", fragColor0); break; } if (stencilToAlpha != REPLACE_ALPHA_NO) { switch (ReplaceAlphaWithStencilType()) { case STENCIL_VALUE_UNIFORM: WRITE(p, " %s.a = u_stencilReplaceValue;\n", fragColor0); break; case STENCIL_VALUE_ZERO: WRITE(p, " %s.a = 0.0;\n", fragColor0); break; case STENCIL_VALUE_ONE: WRITE(p, " %s.a = 1.0;\n", fragColor0); break; case STENCIL_VALUE_UNKNOWN: // Maybe we should even mask away alpha using glColorMask and not change it at all? We do get here // if the stencil mode is KEEP for example. WRITE(p, " %s.a = 0.0;\n", fragColor0); break; case STENCIL_VALUE_KEEP: // Do nothing. We'll mask out the alpha using color mask. break; } } #ifdef DEBUG_SHADER if (doTexture) { WRITE(p, " %s = texture2D(tex, v_texcoord.xy);\n", fragColor0); WRITE(p, " %s += vec4(0.3,0,0.3,0.3);\n", fragColor0); } else { WRITE(p, " %s = vec4(1,0,1,1);\n", fragColor0); } #endif WRITE(p, "}\n"); }
SINT32 MGEFRecord::WriteRecord(FileWriter &writer) { if(OBME.IsLoaded()) { //EDDX and EDID are switched internally for consistency //So EDDX is written as if it was the EDID chunk, and vice versa //Hence the mismatched type in record_write_subrecord if(OBME->EDDX.IsLoaded()) OBME->WRITEAS(EDDX,EDID); if(OBME->OBME.IsLoaded()) OBME->WRITE(OBME); WRITEAS(EDID,EDDX); WRITE(FULL); WRITE(DESC); WRITE(ICON); MODL.Write(writer); DATA.value.numCounters = (UINT16)ESCE.value.size(); //Just to ensure that the proper value is written WRITE(DATA); if(OBME->DATX.IsLoaded()) OBME->WRITE(DATX); WRITE(ESCE); } else { WRITE(EDID); WRITE(FULL); WRITE(DESC); WRITE(ICON); MODL.Write(writer); DATA.value.numCounters = (UINT16)ESCE.value.size(); //Just to ensure that the proper value is written WRITE(DATA); WRITE(ESCE); } return -1; }
void temp_sensor_tick() { uint8_t i = 0; for (; i < NUM_TEMP_SENSORS; i++) { if (temp_sensors_runtime[i].next_read_time) { temp_sensors_runtime[i].next_read_time--; } else { uint16_t temp = 0; //time to deal with this temp sensor switch(temp_sensors[i].temp_type) { #ifdef TEMP_MAX6675 case TT_MAX6675: #ifdef PRR PRR &= ~MASK(PRSPI); #elif defined PRR0 PRR0 &= ~MASK(PRSPI); #endif SPCR = MASK(MSTR) | MASK(SPE) | MASK(SPR0); // enable TT_MAX6675 WRITE(SS, 0); // ensure 100ns delay - a bit extra is fine delay(1); // read MSB SPDR = 0; for (;(SPSR & MASK(SPIF)) == 0;); temp = SPDR; temp <<= 8; // read LSB SPDR = 0; for (;(SPSR & MASK(SPIF)) == 0;); temp |= SPDR; // disable TT_MAX6675 WRITE(SS, 1); temp_sensors_runtime[i].temp_flags = 0; if ((temp & 0x8002) == 0) { // got "device id" temp_sensors_runtime[i].temp_flags |= PRESENT; if (temp & 4) { // thermocouple open temp_sensors_runtime[i].temp_flags |= TCOPEN; } else { temp = temp >> 3; } } // this number depends on how frequently temp_sensor_tick is called. the MAX6675 can give a reading every 0.22s, so set this to about 250ms temp_sensors_runtime[i].next_read_time = 25; break; #endif /* TEMP_MAX6675 */ #ifdef TEMP_THERMISTOR case TT_THERMISTOR: do { uint8_t j; //Read current temperature temp = analog_read(temp_sensors[i].temp_pin); //Calculate real temperature based on lookup table for (j = 1; j < NUMTEMPS; j++) { if (pgm_read_word(&(temptable[j][0])) > temp) { // multiply by 4 because internal temp is stored as 14.2 fixed point temp = pgm_read_word(&(temptable[j][1])) * 4 + (pgm_read_word(&(temptable[j][0])) - temp) * 4 * (pgm_read_word(&(temptable[j-1][1])) - pgm_read_word(&(temptable[j][1]))) / (pgm_read_word(&(temptable[j][0])) - pgm_read_word(&(temptable[j-1][0]))); break; } } //Clamp for overflows if (j == NUMTEMPS) temp = temptable[NUMTEMPS-1][1] * 4; temp_sensors_runtime[i].next_read_time = 0; } while (0); break; #endif /* TEMP_THERMISTOR */ #ifdef TEMP_AD595 case TT_AD595: temp = analog_read(temp_pin); // convert // >>8 instead of >>10 because internal temp is stored as 14.2 fixed point temp = (temp * 500L) >> 8; temp_sensors_runtime[i].next_read_time = 0; break; #endif /* TEMP_AD595 */ #ifdef TEMP_PT100 case TT_PT100: #warning TODO: PT100 code break #endif /* TEMP_PT100 */ #ifdef GEN3 case TT_INTERCOM: temp = get_read_cmd() << 2; start_send(); temp_sensors_runtime[i].next_read_time = 0; break; #endif /* GEN3 */ } temp_sensors_runtime[i].last_read_temp = temp; if (labs(temp - temp_sensors_runtime[i].target_temp) < TEMP_HYSTERESIS) { if (temp_sensors_runtime[i].temp_residency < TEMP_RESIDENCY_TIME) temp_sensors_runtime[i].temp_residency++; } else { temp_sensors_runtime[i].temp_residency = 0; } if (temp_sensors[i].heater_index < NUM_HEATERS) { heater_tick(temp_sensors[i].heater_index, temp_sensors_runtime[i].last_read_temp, temp_sensors_runtime[i].target_temp); } } }
static int rawFileWrite(io_func *io, off_t location, size_t size, void *buffer) { RawFile *rawFile; Volume *volume; Extent *extent; size_t blockSize; off_t fileLoc; off_t locationInBlock; size_t possible; rawFile = (RawFile *)io->data; volume = rawFile->volume; blockSize = volume->volumeHeader->blockSize; if (rawFile->forkData->logicalSize < (location + size)) { ASSERT(allocate(rawFile, location + size), "allocate"); } extent = rawFile->extents; fileLoc = 0; locationInBlock = location; while (TRUE) { fileLoc += extent->blockCount * blockSize; if (fileLoc <= location) { locationInBlock -= extent->blockCount * blockSize; extent = extent->next; if (extent == NULL) { break; } } else { break; } } while (size > 0) { if (extent == NULL) { return FALSE; } possible = extent->blockCount * blockSize - locationInBlock; if (size > possible) { ASSERT(WRITE(volume->image, extent->startBlock * blockSize + locationInBlock, possible, buffer), "WRITE"); size -= possible; buffer = (void *)(((size_t)buffer) + possible); extent = extent->next; } else { ASSERT(WRITE(volume->image, extent->startBlock * blockSize + locationInBlock, size, buffer), "WRITE"); break; } locationInBlock = 0; } return TRUE; }
//------------------------------------------------------------------------------ /// Changes the mapping of the chip so that the remap area mirrors the /// internal ROM or the EBI CS0. //------------------------------------------------------------------------------ void BOARD_RemapRom() { WRITE(AT91C_BASE_MATRIX, MATRIX_MRCR, 0); }
int allocate(RawFile *rawFile, off_t size) { unsigned char *zeros; Volume *volume; HFSPlusForkData *forkData; uint32_t blocksNeeded; uint32_t blocksToAllocate; Extent *extent; Extent *lastExtent; uint32_t curBlock; volume = rawFile->volume; forkData = rawFile->forkData; extent = rawFile->extents; blocksNeeded = ((uint64_t)size / (uint64_t)volume->volumeHeader->blockSize) + (((size % volume->volumeHeader->blockSize) == 0) ? 0 : 1); if (blocksNeeded > forkData->totalBlocks) { zeros = (unsigned char *)malloc(volume->volumeHeader->blockSize); memset(zeros, 0, volume->volumeHeader->blockSize); blocksToAllocate = blocksNeeded - forkData->totalBlocks; if (blocksToAllocate > volume->volumeHeader->freeBlocks) { return FALSE; } lastExtent = NULL; while (extent != NULL) { lastExtent = extent; extent = extent->next; } if (lastExtent == NULL) { rawFile->extents = (Extent *)malloc(sizeof(Extent)); lastExtent = rawFile->extents; lastExtent->blockCount = 0; lastExtent->next = NULL; curBlock = volume->volumeHeader->nextAllocation; } else { curBlock = lastExtent->startBlock + lastExtent->blockCount; } while (blocksToAllocate > 0) { if (isBlockUsed(volume, curBlock)) { if (lastExtent->blockCount > 0) { lastExtent->next = (Extent *)malloc(sizeof(Extent)); lastExtent = lastExtent->next; lastExtent->blockCount = 0; lastExtent->next = NULL; } curBlock = volume->volumeHeader->nextAllocation; volume->volumeHeader->nextAllocation++; if (volume->volumeHeader->nextAllocation >= volume->volumeHeader->totalBlocks) { volume->volumeHeader->nextAllocation = 0; } } else { if (lastExtent->blockCount == 0) { lastExtent->startBlock = curBlock; } /* zero out allocated block */ ASSERT(WRITE(volume->image, curBlock * volume->volumeHeader->blockSize, volume->volumeHeader->blockSize, zeros), "WRITE"); setBlockUsed(volume, curBlock, TRUE); volume->volumeHeader->freeBlocks--; blocksToAllocate--; curBlock++; lastExtent->blockCount++; if (curBlock >= volume->volumeHeader->totalBlocks) { curBlock = volume->volumeHeader->nextAllocation; } } } free(zeros); } else if (blocksNeeded < forkData->totalBlocks) { blocksToAllocate = blocksNeeded; lastExtent = NULL; while (blocksToAllocate > 0) { if (blocksToAllocate > extent->blockCount) { blocksToAllocate -= extent->blockCount; lastExtent = extent; extent = extent->next; } else { break; } } if (blocksToAllocate == 0 && lastExtent != NULL) { // snip the extent list here, since we don't need the rest lastExtent->next = NULL; } else if (blocksNeeded == 0) { rawFile->extents = NULL; } do { for (curBlock = (extent->startBlock + blocksToAllocate); curBlock < (extent->startBlock + extent->blockCount); curBlock++) { setBlockUsed(volume, curBlock, FALSE); volume->volumeHeader->freeBlocks++; } lastExtent = extent; extent = extent->next; if (blocksToAllocate == 0) { free(lastExtent); } else { lastExtent->next = NULL; lastExtent->blockCount = blocksToAllocate; } blocksToAllocate = 0; } while (extent != NULL); } writeExtents(rawFile); forkData->logicalSize = size; forkData->totalBlocks = blocksNeeded; updateVolume(rawFile->volume); if (rawFile->catalogRecord != NULL) { updateCatalog(rawFile->volume, rawFile->catalogRecord); } return TRUE; }
//------------------------------------------------------------------------------ /// Initialize and configure the SDRAM //------------------------------------------------------------------------------ void BOARD_ConfigureSdram(unsigned char busWidth) { static const Pin pinsSdram[] = {PINS_SDRAM}; volatile unsigned int *pSdram = (unsigned int *) AT91C_EBI_SDRAM; unsigned short sdrc_dbw = 0; switch (busWidth) { case 16: sdrc_dbw = AT91C_B16MODE_16_BITS; break; case 32: default: sdrc_dbw = AT91C_B16MODE_32_BITS; break; } // Enable corresponding PIOs PIO_Configure(pinsSdram, 1); WRITE(AT91C_BASE_SDDRC, SDDRC_MDR , AT91C_MD_SDR_SDRAM | sdrc_dbw); // SDRAM type 3.3V + 32bit MODE WRITE(AT91C_BASE_SDDRC, SDDRC_CR , AT91C_NC_DDR10_SDR9 | AT91C_NR_13 | AT91C_CAS_3); // row = 13, column = 9 SDRAM CAS = 3 WRITE(AT91C_BASE_SDDRC, SDDRC_LPR , 0x00000000); // Low power register => Low-power is inhibited // No define sleep_time(50000); // --------- WAIT --------- WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_NOP_CMD); // NOP command pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_NOP_CMD); // NOP command pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_NOP_CMD); // NOP command pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_PRCGALL_CMD); // Precharge All Banks command pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command sleep_time(50000); // --------- WAIT --------- WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_RFSH_CMD); // AutoRefresh command pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command sleep_time(50000); // --------- WAIT --------- WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_RFSH_CMD); // AutoRefresh command pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command sleep_time(50000); // --------- WAIT --------- WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_LMR_CMD); // Set MR JEDEC compliant : Load mode Register command pSdram[19] = 0x5a5a5b5b; // Perform LMR burst=1, lat=2 WRITE(AT91C_BASE_SDDRC, SDDRC_MR, AT91C_MODE_NORMAL_CMD); // Set Normal mode : Any access to the DDRSDRAMC is decoded normally pSdram[0] = 0x00000000; // Dummy read to access SDRAM : validate preceeding command WRITE(AT91C_BASE_SDDRC, SDDRC_RTR, 781); // Set Refresh Timer (ex: ((64 x 10^-3)/8192) x 100 x 10^6 ) => 781 for 100 MHz sleep_time(50000); // --------- WAIT --------- }
static void master(void) { unsigned i; write_xpm_header(); /* clear response fields */ for (i = 0; i < SLAVES; i++) { shm_master_mpb->slave[i].row.cmd = CMD_STOP; } /* send start packets */ for (i = 0; i < SLAVES; i++) { shm_master_mpb->slave[i].packet.cmd = CMD_START; dma(&(shm_slave_mpb[i]->packet), &(shm_master_mpb->slave[i].packet), sizeof(struct packet_t)); } /* wait for acknowledgement */ for (i = 0; i < SLAVES; i++) { while (shm_master_mpb->slave[i].row.cmd != CMD_START) { /* spin until start reponse */ } } /* clear response fields */ for (i = 0; i < SLAVES; i++) { shm_master_mpb->slave[i].row.cmd = CMD_NULL; } int row[SLAVES]; int received_row; /* send first packets to slaves */ for (i = 0; i < SLAVES && i < ROWS; i++) { row[i] = i*(ROWS/SLAVES); shm_master_mpb->slave[i].packet.cmd = row[i]; shm_master_mpb->slave[i].packet.yval = YSTART + row[i]*YSTEP_SIZE; shm_master_mpb->slave[i].packet.xstart = XSTART; shm_master_mpb->slave[i].packet.xend = XEND; shm_master_mpb->slave[i].packet.xstep = XSTEP_SIZE; dma(&(shm_slave_mpb[i]->packet), &(shm_master_mpb->slave[i].packet), sizeof(struct packet_t)); row[i]++; } /* receive rows and send next packets */ for (received_row = 0; received_row < ROWS; ) { for (i = 0; i < SLAVES; i++) { if (shm_master_mpb->slave[i].row.cmd != CMD_NULL) { received_row++; static char buf[10]; itoa(buf, shm_master_mpb->slave[i].row.cmd); WRITE(buf, 10); /* write out data */ WRITE(" 68c\n\"", 6); WRITE((char *)shm_master_mpb->slave[i].row.data, COLS); WRITE("\",\n.\nw\n", 7); /* clear response field */ shm_master_mpb->slave[i].row.cmd = CMD_NULL; /* send next packet */ if (row[i] < (i+1)*(ROWS/SLAVES)) { shm_master_mpb->slave[i].packet.cmd = row[i]; shm_master_mpb->slave[i].packet.yval = YSTART + row[i]*YSTEP_SIZE; shm_master_mpb->slave[i].packet.xstart = XSTART; shm_master_mpb->slave[i].packet.xend = XEND; shm_master_mpb->slave[i].packet.xstep = XSTEP_SIZE; dma(&(shm_slave_mpb[i]->packet), &(shm_master_mpb->slave[i].packet), sizeof(struct packet_t)); row[i]++; } } } } /* send stop packets */ for (i = 0; i < SLAVES; i++) { shm_master_mpb->slave[i].packet.cmd = CMD_STOP; dma(&(shm_slave_mpb[i]->packet), &(shm_master_mpb->slave[i].packet), sizeof(struct packet_t)); } }
static void closeHFSPlusCompressed(io_func* io) { HFSPlusCompressed* data = (HFSPlusCompressed*) io->data; if(data->io) CLOSE(data->io); if(data->dirty) { int oldSize = data->decmpfsSize; if(data->blocks) free(data->blocks); data->decmpfs->magic = CMPFS_MAGIC; data->decmpfs->flags = 0x4; data->decmpfsSize = sizeof(HFSPlusDecmpfs); uint32_t numBlocks = (data->decmpfs->size + 0xFFFF) / 0x10000; uint32_t blocksSize = sizeof(HFSPlusCmpfRsrcBlockHead) + (numBlocks * sizeof(HFSPlusCmpfRsrcBlock)); data->blocks = (HFSPlusCmpfRsrcBlockHead*) malloc(sizeof(HFSPlusCmpfRsrcBlockHead) + (numBlocks * sizeof(HFSPlusCmpfRsrcBlock))); data->blocks->numBlocks = numBlocks; data->blocks->dataSize = blocksSize - sizeof(uint32_t); // without the front dataSize in BlockHead. data->rsrcHead.headerSize = 0x100; data->rsrcHead.dataSize = blocksSize; data->rsrcHead.totalSize = data->rsrcHead.headerSize + data->rsrcHead.dataSize; data->rsrcHead.flags = 0x32; uint8_t* buffer = (uint8_t*) malloc((0x10000 * 1.1) + 12); uint32_t curFileOffset = data->blocks->dataSize; uint32_t i; for(i = 0; i < numBlocks; i++) { data->blocks->blocks[i].offset = curFileOffset; uLongf actualSize = (0x10000 * 1.1) + 12; compress(buffer, &actualSize, data->cached + (0x10000 * i), (data->decmpfs->size - (0x10000 * i)) > 0x10000 ? 0x10000 : (data->decmpfs->size - (0x10000 * i))); data->blocks->blocks[i].size = actualSize; // check if we can fit the whole thing into an inline extended attribute // a little fudge factor here since sizeof(HFSPlusAttrKey) is bigger than it ought to be, since only 127 characters are strictly allowed if(numBlocks <= 1 && (actualSize + sizeof(HFSPlusDecmpfs) + sizeof(HFSPlusAttrKey)) <= 0x1000) { int newSize = (sizeof(HFSPlusDecmpfs) + actualSize + 1) & ~1; if (oldSize < newSize) { printf("growing "); data->decmpfs = realloc(data->decmpfs, newSize); memset(data->decmpfs->data + actualSize, 0, newSize - actualSize - sizeof(HFSPlusDecmpfs)); } data->decmpfs->flags = 0x3; memcpy(data->decmpfs->data, buffer, actualSize); data->decmpfsSize = newSize; printf("inline data\n"); break; } else { if(i == 0) { data->io = openRawFile(data->file->fileID, &data->file->resourceFork, (HFSPlusCatalogRecord*)data->file, data->volume); if(!data->io) { hfs_panic("error opening resource fork"); } } WRITE(data->io, data->rsrcHead.headerSize + sizeof(uint32_t) + data->blocks->blocks[i].offset, data->blocks->blocks[i].size, buffer); curFileOffset += data->blocks->blocks[i].size; data->blocks->dataSize += data->blocks->blocks[i].size; data->rsrcHead.dataSize += data->blocks->blocks[i].size; data->rsrcHead.totalSize += data->blocks->blocks[i].size; } } free(buffer); if(data->decmpfs->flags == 0x4) { flipRsrcHead(&data->rsrcHead); WRITE(data->io, 0, sizeof(HFSPlusCmpfRsrcHead), &data->rsrcHead); flipRsrcHead(&data->rsrcHead); for(i = 0; i < data->blocks->numBlocks; i++) { flipRsrcBlock(&data->blocks->blocks[i]); } flipRsrcBlockHead(data->blocks); WRITE(data->io, data->rsrcHead.headerSize, blocksSize, data->blocks); flipRsrcBlockHead(data->blocks); for(i = 0; i < data->blocks->numBlocks; i++) { flipRsrcBlock(&data->blocks->blocks[i]); } HFSPlusCmpfEnd end; memset(&end, 0, sizeof(HFSPlusCmpfEnd)); end.unk1 = 0x1C; end.unk2 = 0x32; end.unk3 = 0x0; end.magic = CMPFS_MAGIC; end.flags = 0xA; end.size = 0xFFFF01; end.unk4 = 0x0; flipHFSPlusCmpfEnd(&end); WRITE(data->io, data->rsrcHead.totalSize, sizeof(HFSPlusCmpfEnd), &end); flipHFSPlusCmpfEnd(&end); CLOSE(data->io); } flipHFSPlusDecmpfs(data->decmpfs); setAttribute(data->volume, data->file->fileID, "com.apple.decmpfs", (uint8_t*)(data->decmpfs), data->decmpfsSize); flipHFSPlusDecmpfs(data->decmpfs); } if(data->cached) free(data->cached); if(data->blocks) free(data->blocks); free(data->decmpfs); free(data); free(io); }
int do_scheduled_stream(int status, FdEventHandlerPtr event) { StreamRequestPtr request = (StreamRequestPtr)&event->data; int rc, done, i; struct iovec iov[6]; int chunk_header_len; char chunk_header[10]; int len12 = request->len + request->len2; int len123 = request->len + request->len2 + ((request->operation & IO_BUF3) ? request->u.b.len3 : 0); if(status) { done = request->handler(status, event, request); return done; } i = 0; if(request->offset < 0) { assert((request->operation & (IO_MASK | IO_BUF3 | IO_BUF_LOCATION)) == IO_WRITE); if(request->operation & IO_CHUNKED) { chunk_header_len = chunkHeaderLen(len123); } else { chunk_header_len = 0; } if(request->offset < -chunk_header_len) { assert(request->offset >= -(request->u.h.hlen + chunk_header_len)); iov[i].iov_base = request->u.h.header; iov[i].iov_len = -request->offset - chunk_header_len; i++; } if(chunk_header_len > 0) { chunkHeader(chunk_header, 10, len123); if(request->offset < -chunk_header_len) { iov[i].iov_base = chunk_header; iov[i].iov_len = chunk_header_len; } else { iov[i].iov_base = chunk_header + chunk_header_len + request->offset; iov[i].iov_len = -request->offset; } i++; } } if(request->len > 0) { if(request->buf == NULL && (request->operation & IO_BUF_LOCATION)) { assert(*request->u.l.buf_location == NULL); request->buf = *request->u.l.buf_location = get_chunk(); if(request->buf == NULL) { done = request->handler(-ENOMEM, event, request); return done; } } if(request->offset <= 0) { iov[i].iov_base = request->buf; iov[i].iov_len = request->len; i++; } else if(request->offset < request->len) { iov[i].iov_base = request->buf + request->offset; iov[i].iov_len = request->len - request->offset; i++; } } if(request->len2 > 0) { if(request->offset <= request->len) { iov[i].iov_base = request->buf2; iov[i].iov_len = request->len2; i++; } else if(request->offset < request->len + request->len2) { iov[i].iov_base = request->buf2 + request->offset - request->len; iov[i].iov_len = request->len2 - request->offset + request->len; i++; } } if((request->operation & IO_BUF3) && request->u.b.len3 > 0) { if(request->offset <= len12) { iov[i].iov_base = request->u.b.buf3; iov[i].iov_len = request->u.b.len3; i++; } else if(request->offset < len12 + request->u.b.len3) { iov[i].iov_base = request->u.b.buf3 + request->offset - len12; iov[i].iov_len = request->u.b.len3 - request->offset + len12; i++; } } if((request->operation & IO_CHUNKED)) { int l; const char *trailer; if(request->operation & IO_END) { if(len123 == 0) { trailer = endChunkTrailer + 2; l = 5; } else { trailer = endChunkTrailer; l = 7; } } else { trailer = endChunkTrailer; l = 2; } if(request->offset <= len123) { iov[i].iov_base = (char*)trailer; iov[i].iov_len = l; i++; } else if(request->offset < len123 + l) { iov[i].iov_base = (char*)endChunkTrailer + request->offset - len123; iov[i].iov_len = l - request->offset + len123; i++; } } assert(i > 0); if((request->operation & IO_MASK) == IO_WRITE) { if(i > 1) rc = WRITEV(request->fd, iov, i); else rc = WRITE(request->fd, iov[0].iov_base, iov[0].iov_len); } else { if(i > 1) rc = READV(request->fd, iov, i); else rc = READ(request->fd, iov[0].iov_base, iov[0].iov_len); } if(rc > 0) { request->offset += rc; if(request->offset < 0) return 0; done = request->handler(0, event, request); return done; } else if(rc == 0 || errno == EPIPE) { done = request->handler(1, event, request); } else if(errno == EAGAIN || errno == EINTR) { return 0; } else if(errno == EFAULT || errno == EBADF) { abort(); } else { done = request->handler(-errno, event, request); } assert(done); return done; }
LTERM_LOG(ltermSendData,40,("count=%d\n", count)); LTERM_LOGUNICODE(ltermSendData,41,(buf, count)); if ((count == 1) && (*buf < 0x80)) { /* Optimized code to transmit single ASCII character */ ch = (char) *buf; if (lts->ptyMode) #ifndef USE_NSPR_IO success = (write(lts->pty.ptyFD, &ch, 1) == 1); #else assert(0); #endif else success = (WRITE(lts->ltermProcess.processIN, &ch, 1) == 1); if (!success) { #if defined(DEBUG_LTERM) && !defined(USE_NSPR_IO) int errcode = errno; perror("ltermSendData"); #else int errcode = 0; #endif LTERM_ERROR("ltermSendData: Error %d in writing to child STDIN\n", errcode); return -1; } return 0; }
SINT32 NOTERecord::WriteRecord(FileWriter &writer) { WRITE(EDID); WRITE(OBND); WRITE(FULL); MODL.Write(writer); WRITE(ICON); WRITE(MICO); WRITE(YNAM); WRITE(ZNAM); WRITE(DATA); WRITE(ONAM); WRITE(XNAM); if(IsVoice()) WRITEAS(TNAMAlt,TNAM); else WRITE(TNAM); WRITE(SNAM); return -1; }
/** Initialize SPI for SD card reading. */ void sd_init(void) { SET_OUTPUT(SD_CARD_SELECT_PIN); WRITE(SD_CARD_SELECT_PIN, 1); }
int DBF::create ( const char *file, DBfield field[], int numfield ) { if ( _fd >= 0 ) close() ; if ( numfield > MAX_FIELDS ) { _errNo = DB_STRUC_ERR ; return DB_FAILURE ; } #if defined(UNIX) int FD = CREAT(strlwr(makeFileExt(file,".dbf"))) ; #else int FD = CREAT(file) ; #endif if ( FD < 0 ) { _errNo = DB_CREATE_ERR ; return DB_FAILURE ; } int i ; int RS = 1 ; for ( i = 0 ; i < numfield ; i++ ) { RS += field[i].length ; } time_t T = time(NULL) ; tm *t = localtime(&T) ; HEADER h ; _updYear = t->tm_year + 1900; _updMonth = t->tm_mon + 1; _updDay = t->tm_mday; memset(&h,0,sizeof(h)) ; h.signature = DBF_SIGNATURE ; h.date[0] = t->tm_year ; // since 1900 h.date[1] = _updMonth; h.date[2] = _updDay; h.headSize = sizeof(HEADER) + numfield * sizeof(FIELD) + 1 ; h.recSize = RS ; if ( WRITE(FD,&h,sizeof(h)) != sizeof(h) ) { CLOSE(FD) ; _errNo = DB_CREATE_ERR ; return DB_FAILURE ; } char *F ; int sz ; F = new char[sz=numfield*sizeof(FIELD)+1] ; if ( F == NULL ) { CLOSE(FD) ; _errNo = DB_NO_MEMORY ; return DB_FAILURE ; } memset(F,0,sz) ; FIELD *f = (FIELD*)F ; for ( i = 0 ; i < numfield ; i++, f++ ) { strcpy(f->name,field[i].name) ; strupr(f->name) ; f->type = field[i].type ; f->length = field[i].length ; f->decimal = field[i].decimal ; } f->name[0] = 0x0d ; i = WRITE(FD,F,sz) ; delete[] F ; if ( i != sz ) { CLOSE(FD) ; _errNo = DB_CREATE_ERR ; return DB_FAILURE ; } FLUSH(FD) ; _fd = FD ; return initial(&h) ; }
static void gammaReadRGBASpan8888( const GLcontext *ctx, GLuint n, GLint x, GLint y, GLubyte rgba[][4]) { gammaContextPtr gmesa = GAMMA_CONTEXT(ctx); gammaScreenPtr gammascrn = gmesa->gammaScreen; uint32_t dwords1, dwords2, i = 0; char *src = (char *)rgba[0]; GLuint read = n * gammascrn->cpp; /* Number of bytes we are expecting */ uint32_t data; FLUSH_DMA_BUFFER(gmesa); CHECK_DMA_BUFFER(gmesa, 16); WRITE(gmesa->buf, LBReadMode, gmesa->LBReadMode & ~(LBReadSrcEnable | LBReadDstEnable)); WRITE(gmesa->buf, ColorDDAMode, ColorDDAEnable); WRITE(gmesa->buf, LBWriteMode, LBWriteModeDisable); WRITE(gmesa->buf, FBReadMode, (gmesa->FBReadMode & ~FBReadSrcEnable) | FBReadDstEnable | FBDataTypeColor); WRITE(gmesa->buf, FilterMode, 0x200); /* Pass FBColorData */ WRITE(gmesa->buf, FBWriteMode, FBW_UploadColorData | FBWriteModeDisable); WRITE(gmesa->buf, StartXSub, (x+n)<<16); WRITE(gmesa->buf, StartXDom, x<<16); WRITE(gmesa->buf, StartY, y<<16); WRITE(gmesa->buf, GLINTCount, 1); WRITE(gmesa->buf, dXDom, 0<<16); WRITE(gmesa->buf, dXSub, 0<<16); WRITE(gmesa->buf, dY, 1<<16); WRITE(gmesa->buf, Render, PrimitiveTrapezoid); FLUSH_DMA_BUFFER(gmesa); moredata: dwords1 = *(volatile uint32_t*)(void *)(((uint8_t*)gammascrn->regions[0].map) + (GlintOutFIFOWords)); dwords2 = *(volatile uint32_t*)(void *)(((uint8_t*)gammascrn->regions[2].map) + (GlintOutFIFOWords)); if (dwords1) { memcpy(src, (char*)gammascrn->regions[1].map + 0x1000, dwords1 << 2); src += dwords1 << 2; read -= dwords1 << 2; } if (dwords2) { memcpy(src, (char*)gammascrn->regions[3].map + 0x1000, dwords2 << 2); src += dwords2 << 2; read -= dwords2 << 2; } if (read) goto moredata; done: CHECK_DMA_BUFFER(gmesa, 6); WRITE(gmesa->buf, ColorDDAMode, gmesa->ColorDDAMode); WRITE(gmesa->buf, LBWriteMode, LBWriteModeEnable); WRITE(gmesa->buf, LBReadMode, gmesa->LBReadMode); WRITE(gmesa->buf, FBReadMode, gmesa->FBReadMode); WRITE(gmesa->buf, FBWriteMode, FBWriteModeEnable); WRITE(gmesa->buf, FilterMode, 0x400); }
void probe_init() { SET_INPUT(PROBE_PIN); WRITE(PROBE_PIN,HIGH); }