void GameGraphic::callback(GameEvent gameEvent, const TetrisBoard& tetrisBoard) { for (auto& row : rows_) { row->handleEvent(gameEvent, tetrisBoard); } rows_.remove_if([&](const DrawRowPtr& row) { if (!row->isAlive()) { freeRows_.push_front(row); return true; } return false; }); switch (gameEvent) { case GameEvent::GAME_OVER: break; case GameEvent::BLOCK_COLLISION: break; case GameEvent::RESTARTED: break; case GameEvent::EXTERNAL_ROWS_ADDED: { int rows = tetrisBoard.getNbrExternalRowsAdded(); for (int row = 0; row < rows; ++row) { addDrawRowBottom(tetrisBoard, rows - row - 1); } int highestRow = tetrisBoard.getBoardVector().size() / tetrisBoard.getColumns(); assert(rows_.size() - highestRow >= 0); // Something is wrong. Should not be posssible. for (int i = 0; i < (int) rows_.size() - highestRow; ++i) { // Remove unneeded empty rows at the top. rows_.pop_back(); } } break; case GameEvent::NEXT_BLOCK_UPDATED: nextBlock_.update(Block(tetrisBoard.getNextBlockType(), 0, 0)); break; case GameEvent::CURRENT_BLOCK_UPDATED: // Fall through! case GameEvent::PLAYER_MOVES_BLOCK_ROTATE: // Fall through! case GameEvent::PLAYER_MOVES_BLOCK_LEFT: // Fall through! case GameEvent::PLAYER_MOVES_BLOCK_RIGHT: currentBlock_.update(tetrisBoard.getBlock()); break; case GameEvent::PLAYER_MOVES_BLOCK_DOWN_GROUND: blockDownGround_ = true; latestBlockDownGround_ = tetrisBoard.getBlock(); break; case GameEvent::PLAYER_MOVES_BLOCK_DOWN: if (blockDownGround_) { currentBlock_.updateDown(tetrisBoard.getBlock()); blockDownGround_ = false; } // Fall through! case GameEvent::GRAVITY_MOVES_BLOCK: currentBlock_.update(tetrisBoard.getBlock()); break; case GameEvent::ROW_TO_BE_REMOVED: textClearedRows_.update("Rows " + std::to_string(tetrisBoard.getRemovedRows())); break; case GameEvent::ONE_ROW_REMOVED: addDrawRowAtTheTop(tetrisBoard, 1); break; case GameEvent::TWO_ROW_REMOVED: addDrawRowAtTheTop(tetrisBoard, 2); break; case GameEvent::THREE_ROW_REMOVED: addDrawRowAtTheTop(tetrisBoard, 3); break; case GameEvent::FOUR_ROW_REMOVED: addDrawRowAtTheTop(tetrisBoard, 4); break; } }
void CachedQuarkletProblem<PROBLEM>::add_level (const Index& lambda, //InfiniteVector<double, Index>& w, Vector<double>& w, const int j, const double factor, const int J, const CompressionStrategy strategy, const int jmax, const int pmax, const double a, const double b) const { // cout << "bin in addlevel drin" << endl; // cout << lambda << endl; // cout << j << endl; // WaveletBasis mybasis(basis()); const int minplevel = std::max(0, lambda.p() + 1 - (int) pow(2,(J-b*abs(j-lambda.j())/a))); const int maxplevel = std::min(lambda.p() - 1 + (int) pow(2,(J-b*abs(j-lambda.j())/a)), pmax); const int lambda_num = number(lambda, jmax); //cout << lambda << ": " << lambda_num << endl; // search for column 'lambda' typedef std::list<Index> IntersectingList; typename ColumnCache::iterator col_lb(entries_cache.lower_bound(lambda_num)); typename ColumnCache::iterator col_it(col_lb); if (col_lb == entries_cache.end() || entries_cache.key_comp()(lambda_num,col_lb->first)) { // insert a new column typedef typename ColumnCache::value_type value_type; col_it = entries_cache.insert(col_lb, value_type(lambda_num, Column())); } Column& col(col_it->second); // check wether the level has already been calculated typename Column::iterator lb(col.lower_bound(j)); typename Column::iterator it(lb); if (lb == col.end() || col.key_comp()(j, lb->first)) { // no entries have ever been computed for this column and this level // cout << "keine Einträge berechnet" << endl; // insert a new level typedef typename Column::value_type value_type; it = col.insert(lb, value_type(j, Block())); Block& block(it->second); IntersectingList nus; //DKR strategy // cout << lambda << endl; // cout << j << endl; // cout << J << endl; //cout << minplevel << endl; //cout << maxplevel << endl; for(int p = minplevel; p<=maxplevel; ++p){ // cout << "Hallo" << endl; intersecting_wavelets(basis(), lambda, std::max(j, basis().j0()), j == (basis().j0()-1), nus, p); // do the rest of the job const double d1 = problem->D(lambda); // cout << d1 << endl; for (typename IntersectingList::const_iterator it2(nus.begin()), itend2(nus.end()); it2 != itend2; ++it2) { const double entry = problem->a(*it2, lambda); // cout << *it2 << ", " << entry << endl; typedef typename Block::value_type value_type_block; if (entry != 0.) { // cout << "ja3" << endl; block.insert(block.end(), value_type_block(number(*it2,jmax), entry)); //w.add_coefficient(*it2, (entry / (d1 * problem->D(*it2))) * factor); // cout << *it2 << ": " << (*it2).number() << endl; // cout << number(*it2,jmax) << endl; // cout << w.size() << endl; w[number(*it2,jmax)] += (entry / (d1*problem->D(*it2))) * factor; //cout << "ja5" << endl; } // cout << "ja1" << endl; } // cout << "ja2" << endl; } } else { //cout << "Einträge schon berechnet" << endl; // level already exists --> extract level from cache //cout << "Iterator: " << it->first << endl; Block& block(it->second); const double d1 = problem->D(lambda); //cout << "Länge w: " << w.size() << endl; for (typename Block::const_iterator it2(block.begin()), itend2(block.end()); it2 != itend2; ++it2) { // w.add_coefficient(*(problem->basis().get_wavelet(it2->first)), // (it2->second / (d1 * problem->D( *(problem->basis().get_wavelet(it2->first)) ))) * factor); //cout << it2->second << endl; //cout << it2->first << endl; w[it2->first] += (it2->second / (d1*problem->D(*(problem->basis().get_wavelet(it2->first))))) * factor; } }// end else }
Block DistinctSortedBlockInputStream::readImpl() { /// Execute until end of stream or until /// a block with some new records will be gotten. for (;;) { /// Stop reading if we already reached the limit. if (limit_hint && data.getTotalRowCount() >= limit_hint) return Block(); Block block = children.back()->read(); if (!block) return Block(); const ColumnRawPtrs column_ptrs(getKeyColumns(block)); if (column_ptrs.empty()) return block; const ColumnRawPtrs clearing_hint_columns(getClearingColumns(block, column_ptrs)); if (data.type == ClearableSetVariants::Type::EMPTY) data.init(ClearableSetVariants::chooseMethod(column_ptrs, key_sizes)); const size_t rows = block.rows(); IColumn::Filter filter(rows); bool has_new_data = false; switch (data.type) { case ClearableSetVariants::Type::EMPTY: break; #define M(NAME) \ case ClearableSetVariants::Type::NAME: \ has_new_data = buildFilter(*data.NAME, column_ptrs, clearing_hint_columns, filter, rows, data); \ break; APPLY_FOR_SET_VARIANTS(M) #undef M } /// Just go to the next block if there isn't any new record in the current one. if (!has_new_data) continue; if (!checkLimits()) { switch (overflow_mode) { case OverflowMode::THROW: throw Exception("DISTINCT-Set size limit exceeded." " Rows: " + toString(data.getTotalRowCount()) + ", limit: " + toString(max_rows) + ". Bytes: " + toString(data.getTotalByteCount()) + ", limit: " + toString(max_bytes) + ".", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED); case OverflowMode::BREAK: return Block(); default: throw Exception("Logical error: unknown overflow mode", ErrorCodes::LOGICAL_ERROR); } } prev_block.block = block; prev_block.clearing_hint_columns = std::move(clearing_hint_columns); size_t all_columns = block.columns(); for (size_t i = 0; i < all_columns; ++i) block.safeGetByPosition(i).column = block.safeGetByPosition(i).column->filter(filter, -1); return block; } }
Block DistinctBlockInputStream::readImpl() { /// Execute until end of stream or until /// a block with some new records will be gotten. while (1) { /// Stop reading if we already reach the limit. if (limit_hint && data.getTotalRowCount() >= limit_hint) return Block(); Block block = children[0]->read(); if (!block) return Block(); const ConstColumnPlainPtrs column_ptrs(getKeyColumns(block)); if (column_ptrs.empty()) return block; if (data.empty()) data.init(SetVariants::chooseMethod(column_ptrs, key_sizes)); const size_t old_set_size = data.getTotalRowCount(); const size_t rows = block.rows(); IColumn::Filter filter(rows); switch (data.type) { case SetVariants::Type::EMPTY: break; #define M(NAME) \ case SetVariants::Type::NAME: \ buildFilter(*data.NAME, column_ptrs, filter, rows, data); \ break; APPLY_FOR_SET_VARIANTS(M) #undef M } /// Just go to the next block if there isn't any new record in the current one. if (data.getTotalRowCount() == old_set_size) continue; if (!checkLimits()) { if (overflow_mode == OverflowMode::THROW) throw Exception("DISTINCT-Set size limit exceeded." " Rows: " + toString(data.getTotalRowCount()) + ", limit: " + toString(max_rows) + ". Bytes: " + toString(data.getTotalByteCount()) + ", limit: " + toString(max_bytes) + ".", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED); if (overflow_mode == OverflowMode::BREAK) return Block(); throw Exception("Logical error: unknown overflow mode", ErrorCodes::LOGICAL_ERROR); } size_t all_columns = block.columns(); for (size_t i = 0; i < all_columns; ++i) block.safeGetByPosition(i).column = block.safeGetByPosition(i).column->filter(filter, -1); return block; } }
// Ouvre l'ecran d'aide. Passer -1 pour la section par défaut (ou derniere,) // Ou un nombre de l'enumération BUTTON_NUMBERS pour l'aide contextuelle. void Window_help(int section, const char *sub_section) { short clicked_button; short nb_lines; T_Scroller_button * scroller; if (section!=-1) { Current_help_section = 4 + section; Help_position = 0; } nb_lines=Help_section[Current_help_section].Length; if (section!=-1 && sub_section!=NULL) { int index=0; for (index=0; index<nb_lines; index++) if (Help_section[Current_help_section].Help_table[index].Line_type == 'T' && !strcmp(Help_section[Current_help_section].Help_table[index].Text, sub_section)) { Help_position = index; break; } } Open_window(310,175,"Help / About..."); // dessiner de la fenêtre où va défiler le texte Window_display_frame_in(8,17,274,132); Block(Window_pos_X+(Menu_factor_X*9), Window_pos_Y+(Menu_factor_Y*18), Menu_factor_X*272,Menu_factor_Y*130,MC_Black); Window_set_normal_button(266,153,35,14,"Exit",0,1,KEY_ESC); // 1 scroller=Window_set_scroller_button(290,18,130,nb_lines, 16,Help_position); // 2 Window_set_normal_button( 9,154, 6*8,14,"About" ,1,1,SDLK_a); // 3 Window_set_normal_button( 9+6*8+4,154, 8*8,14,"License",1,1,SDLK_l); // 4 Window_set_normal_button( 9+6*8+4+8*8+4,154, 5*8,14,"Help",1,1,SDLK_h); // 5 Window_set_normal_button(9+6*8+4+8*8+4+5*8+4,154, 8*8,14,"Credits",1,1,SDLK_c); // 6 Window_set_special_button(9,18,272,130); // 7 Display_help(); Update_rect(Window_pos_X,Window_pos_Y,310*Menu_factor_X,175*Menu_factor_Y); Display_cursor(); do { clicked_button=Window_clicked_button(); switch (clicked_button) { case -1: case 0: case 1: break; case 7: // Zone de texte { int line = ((Mouse_Y-Window_pos_Y)/Menu_factor_Y - 18)/8; Wait_end_of_click(); if (line == ((Mouse_Y-Window_pos_Y)/Menu_factor_Y - 18)/8) { if (Help_position+line<nb_lines) { switch (Help_section[Current_help_section].Help_table[Help_position+line].Line_type) { case 'K': Window_set_shortcut(Help_section[Current_help_section].Help_table[Help_position+line].Line_parameter); break; // Ici on peut gérer un cas 'lien hypertexte' default: break; } Hide_cursor(); Display_help(); Display_cursor(); } } break; } default: Hide_cursor(); if (clicked_button>2) { Current_help_section=clicked_button-3; Help_position=0; nb_lines=Help_section[Current_help_section].Length; scroller->Position=0; scroller->Nb_elements=nb_lines; Compute_slider_cursor_length(scroller); Window_draw_slider(scroller); } else Help_position=Window_attribute2; Display_help(); Display_cursor(); } // Gestion des touches de déplacement dans la liste switch (Key) { case SDLK_UP : // Haut if (Help_position>0) Help_position--; Scroll_help(scroller); Key=0; break; case SDLK_DOWN : // Bas if (Help_position<nb_lines-16) Help_position++; Scroll_help(scroller); Key=0; break; case SDLK_PAGEUP : // PageUp if (Help_position>15) Help_position-=15; else Help_position=0; Scroll_help(scroller); Key=0; break; case (KEY_MOUSEWHEELUP) : // WheelUp if (Help_position>3) Help_position-=3; else Help_position=0; Scroll_help(scroller); Key=0; break; case SDLK_PAGEDOWN : // PageDown if (nb_lines>16) { if (Help_position<nb_lines-16-15) Help_position+=15; else Help_position=nb_lines-16; Scroll_help(scroller); Key=0; } break; case (KEY_MOUSEWHEELDOWN) : // Wheeldown if (nb_lines>16) { if (Help_position<nb_lines-16-3) Help_position+=3; else Help_position=nb_lines-16; Scroll_help(scroller); Key=0; } break; case SDLK_HOME : // Home Help_position=0; Scroll_help(scroller); Key=0; break; case SDLK_END : // End if (nb_lines>16) { Help_position=nb_lines-16; Scroll_help(scroller); Key=0; } break; } if (Is_shortcut(Key,0x100+BUTTON_HELP)) clicked_button=1; } while ((clicked_button!=1) && (Key!=SDLK_RETURN)); Key=0; Close_window(); Unselect_button(BUTTON_HELP); Display_cursor(); }
void Button_Stats(void) { short clicked_button; char buffer[37]; dword color_usage[256]; unsigned long long freeRam; qword mem_size = 0; int y; #if defined (__MINT__) _DISKINFO drvInfo; unsigned long STRAM=0,TTRAM=0; char helpBuf[64]={0}; #endif Open_window(310,174,"Statistics"); // Dessin de la fenetre ou va s'afficher le texte Window_display_frame_in(8,17,294,132); Block(Window_pos_X+(Menu_factor_X*9), Window_pos_Y+(Menu_factor_Y*18), Menu_factor_X*292,Menu_factor_Y*130,MC_Black); Window_set_normal_button(120,153,70,14,"OK",0,1,KEY_ESC); // 1 y=19; // row for first line Print_in_window(10,y,"Program version:",STATS_TITLE_COLOR,MC_Black); sprintf(buffer,"%s.%s",Program_version, SVN_revision); Print_in_window(146,y,buffer,STATS_DATA_COLOR,MC_Black); y+=16; Print_in_window(10,y,"Build options:",STATS_TITLE_COLOR,MC_Black); Print_in_window(146,y,TrueType_is_supported()?"TTF fonts":"no TTF fonts",STATS_DATA_COLOR,MC_Black); y+=8; Print_in_window(10,y,"Lua version:",STATS_TITLE_COLOR,MC_Black); Print_in_window_limited(146,y,Lua_version(),10,STATS_DATA_COLOR,MC_Black); y+=16; Print_in_window(10,y,"Free memory: ",STATS_TITLE_COLOR,MC_Black); y+=8; #if defined (__MINT__) // Display free TT/ST RAM freeRam=0; Atari_Memory_free(&STRAM,&TTRAM); freeRam=STRAM+TTRAM; buffer[0]='\0'; if(STRAM > (100*1024*1024)) sprintf(helpBuf,"ST:%u Mb ",(unsigned int)(STRAM/(1024*1024))); else if(freeRam > 100*1024) sprintf(helpBuf,"ST:%u Kb ",(unsigned int)(STRAM/1024)); else sprintf(helpBuf,"ST:%u b ",(unsigned int)STRAM); strncat(buffer,helpBuf,sizeof(char)*37); if(TTRAM > (100ULL*1024*1024*1024)) sprintf(helpBuf,"TT:%u Gb",(unsigned int)(TTRAM/(1024*1024*1024))); else if(TTRAM > (100*1024*1024)) sprintf(helpBuf,"TT:%u Mb",(unsigned int)(TTRAM/(1024*1024))); else if(freeRam > 100*1024) sprintf(helpBuf,"TT:%u Kb",(unsigned int)(TTRAM/1024)); else sprintf(helpBuf,"TT:%u b",(unsigned int)TTRAM); strncat(buffer,helpBuf,sizeof(char)*37); if(freeRam > (100ULL*1024*1024*1024)) sprintf(helpBuf,"(%u Gb)",(unsigned int)(freeRam/(1024*1024*1024))); else if(freeRam > (100*1024*1024)) sprintf(helpBuf,"(%u Mb)",(unsigned int)(freeRam/(1024*1024))); else if(freeRam > 100*1024) sprintf(helpBuf,"(%u Kb)",(unsigned int)(freeRam/1024)); else sprintf(helpBuf,"(%u b)",(unsigned int)freeRam); strncat(buffer,helpBuf,sizeof(char)*37); Print_in_window(18,y,buffer,STATS_DATA_COLOR,MC_Black); #else // Display free RAM (generic) freeRam = Memory_free(); if(freeRam > (100ULL*1024*1024*1024)) sprintf(buffer,"%u Gigabytes",(unsigned int)(freeRam/(1024*1024*1024))); else if(freeRam > (100*1024*1024)) sprintf(buffer,"%u Megabytes",(unsigned int)(freeRam/(1024*1024))); else if(freeRam > 100*1024) sprintf(buffer,"%u Kilobytes",(unsigned int)(freeRam/1024)); else sprintf(buffer,"%u bytes",(unsigned int)freeRam); Print_in_window(114,y,buffer,STATS_DATA_COLOR,MC_Black); #endif y+=8; // Used memory Print_in_window(10,y,"Used memory pages: ",STATS_TITLE_COLOR,MC_Black); if(Stats_pages_memory > (100LL*1024*1024*1024)) sprintf(buffer,"%ld (%lld Gb)",Stats_pages_number, Stats_pages_memory/(1024*1024*1024)); else if(Stats_pages_memory > (100*1024*1024)) sprintf(buffer,"%ld (%lld Mb)",Stats_pages_number, Stats_pages_memory/(1024*1024)); else sprintf(buffer,"%ld (%lld Kb)",Stats_pages_number, Stats_pages_memory/1024); Print_in_window(162,y,buffer,STATS_DATA_COLOR,MC_Black); y+=8; #if defined(__WIN32__) { ULARGE_INTEGER tailleU; GetDiskFreeSpaceEx(Main_selector.Directory,&tailleU,NULL,NULL); mem_size = tailleU.QuadPart; } #elif defined(__linux__) || defined(__macosx__) || defined(__FreeBSD__) || defined(__SYLLABLE__) || defined(__AROS__) { struct statfs disk_info; statfs(Main_selector.Directory,&disk_info); mem_size=(qword) disk_info.f_bfree * (qword) disk_info.f_bsize; } #elif defined(__HAIKU__) mem_size = haiku_get_free_space(Main_selector.Directory); #elif defined (__MINT__) mem_size=0; Dfree(&drvInfo,0); //number of free clusters*sectors per cluster*bytes per sector; // reports current drive mem_size=drvInfo.b_free*drvInfo.b_clsiz*drvInfo.b_secsiz; #else #define NODISKSPACESUPPORT // Free disk space is only for shows. Other platforms can display 0. #warning "Missing code for your platform !!! Check and correct please :)" mem_size=0; #endif // Display free space if (mem_size != 0) { #if defined(__AROS__) char *colon = strchr(Main_selector.Directory, ':'); int len = strlen(Main_selector.Directory); if (colon) { len = (long)colon - (long)Main_selector.Directory; } if (len > 8) len = 8; sprintf(buffer,"Free space on %.*s:",len,Main_selector.Directory); #else sprintf(buffer,"Free space on %c:",Main_selector.Directory[0]); #endif Print_in_window(10,y,buffer,STATS_TITLE_COLOR,MC_Black); if(mem_size > (100ULL*1024*1024*1024)) sprintf(buffer,"%u Gigabytes",(unsigned int)(mem_size/(1024*1024*1024))); else if(mem_size > (100*1024*1024)) sprintf(buffer,"%u Megabytes",(unsigned int)(mem_size/(1024*1024))); else if(mem_size > (100*1024)) sprintf(buffer,"%u Kilobytes",(unsigned int)(mem_size/1024)); else sprintf(buffer,"%u bytes",(unsigned int)mem_size); #if defined(__AROS__) Print_in_window(192,y,buffer,STATS_DATA_COLOR,MC_Black); #else Print_in_window(146,y,buffer,STATS_DATA_COLOR,MC_Black); #endif } else { #ifndef NODISKSPACESUPPORT Print_in_window(10,y,"Disk full!",STATS_TITLE_COLOR,MC_Black); #endif #undef NODISKSPACESUPPORT } y+=16; // Affichage des informations sur l'image Print_in_window(10,y,"Picture info.:",STATS_TITLE_COLOR,MC_Black); y+=8; // Affichage des dimensions de l'image Print_in_window(18,y,"Dimensions :",STATS_TITLE_COLOR,MC_Black); sprintf(buffer,"%dx%d",Main_image_width,Main_image_height); Print_in_window(122,y,buffer,STATS_DATA_COLOR,MC_Black); y+=8; // Affichage du nombre de couleur utilisé Print_in_window(18,y,"Colors used:",STATS_TITLE_COLOR,MC_Black); memset(color_usage,0,sizeof(color_usage)); sprintf(buffer,"%d",Count_used_colors(color_usage)); Print_in_window(122,y,buffer,STATS_DATA_COLOR,MC_Black); y+=16; // Affichage des dimensions de l'écran Print_in_window(10,y,"Resolution:",STATS_TITLE_COLOR,MC_Black); sprintf(buffer,"%dx%d",Screen_width,Screen_height); Print_in_window(106,y,buffer,STATS_DATA_COLOR,MC_Black); Update_rect(Window_pos_X,Window_pos_Y,Menu_factor_X*310,Menu_factor_Y*174); Display_cursor(); do { clicked_button=Window_clicked_button(); if (Is_shortcut(Key,0x200+BUTTON_HELP)) clicked_button=1; } while ( (clicked_button!=1) && (Key!=SDLK_RETURN) ); if(Key==SDLK_RETURN)Key=0; Close_window(); Unselect_button(BUTTON_HELP); Display_cursor(); }
bool CFeature::UpdatePosition() { if (udef != NULL) { // we are a wreck of a dead unit if (!reachedFinalPos) { // def->floating is unreliable (true for land unit wrecks), // just assume wrecks always sink even if their "owner" was // a floating object (as is the case for ships anyway) const float realGroundHeight = ground->GetHeightReal(pos.x, pos.z); const bool reachedGround = ((pos.y - realGroundHeight) <= 0.1f); // NOTE: apply more drag if we were a tank or bot? // (would require passing extra data to Initialize()) deathSpeed *= ((reachedGround)? 0.95f: 0.9999f); if (deathSpeed.SqLength2D() > 0.01f) { UnBlock(); qf->RemoveFeature(this); // update our forward speed (and quadfield // position) if it is still greater than 0 Move3D(deathSpeed, true); qf->AddFeature(this); Block(); } else { deathSpeed.x = 0.0f; deathSpeed.z = 0.0f; } if (!reachedGround) { if (pos.y > 0.0f) { // quadratic acceleration if not in water deathSpeed.y += mapInfo->map.gravity; } else { // constant downward speed otherwise deathSpeed.y = mapInfo->map.gravity; } Move1D(deathSpeed.y, 1, true); } else { deathSpeed.y = 0.0f; // last Update() may have sunk us into // ground if pos.y was only marginally // larger than ground height, correct Move1D(realGroundHeight, 1, false); } reachedFinalPos = (deathSpeed == ZeroVector); if (!pos.IsInBounds()) { pos.ClampInBounds(); // ensure that no more forward-speed updates are done // (prevents wrecks floating in mid-air at edge of map // due to gravity no longer being applied either) deathSpeed = ZeroVector; } eventHandler.FeatureMoved(this); CalculateTransform(); } } else { if (pos.y > finalHeight) { // feature is falling (note: gravity is negative) if (def->drawType >= DRAWTYPE_TREE) { treeDrawer->DeleteTree(pos); } if (pos.y > 0.0f) { speed.y += mapInfo->map.gravity; } else { speed.y = mapInfo->map.gravity; } Move1D(speed.y, 1, true); if (def->drawType >= DRAWTYPE_TREE) { treeDrawer->AddTree(def->drawType - 1, pos, 1.0f); } transMatrix[13] += speed.y; } else if (pos.y < finalHeight) { // if ground is restored, make sure feature does not get buried if (def->drawType >= DRAWTYPE_TREE) { treeDrawer->DeleteTree(pos); } const float dy = finalHeight - pos.y; speed.y = 0.0f; transMatrix[13] += dy; Move1D(dy, 1, true); if (def->drawType >= DRAWTYPE_TREE) { treeDrawer->AddTree(def->drawType - 1, pos, 1.0f); } } reachedFinalPos = (pos.y == finalHeight); } isUnderWater = ((pos.y + height) < 0.0f); return reachedFinalPos; }
bool CFeature::UpdatePosition() { bool finishedUpdate = true; if (!createdFromUnit.empty()) { // we are a wreck of a dead unit if (!reachedFinalPos) { bool haveForwardSpeed = false; bool haveVerticalSpeed = false; bool inBounds = false; // NOTE: apply more drag if we were a tank or bot? // (would require passing extra data to Initialize()) deathSpeed *= 0.95f; if (deathSpeed.SqLength2D() > 0.01f) { UnBlock(); qf->RemoveFeature(this); // update our forward speed (and quadfield // position) if it's still greater than 0 pos += deathSpeed; midPos += deathSpeed; haveForwardSpeed = true; qf->AddFeature(this); Block(); } // def->floating is unreliable (true for land unit wrecks), // just assume wrecks always sink even if their "owner" was // a floating object (as is the case for ships anyway) float realGroundHeight = ground->GetHeight2(pos.x, pos.z); bool reachedGround = (pos.y <= realGroundHeight); if (!reachedGround) { if (pos.y > 0.0f) { // quadratic acceleration if not in water deathSpeed.y += mapInfo->map.gravity; } else { // constant downward speed otherwise deathSpeed.y = mapInfo->map.gravity; } pos.y += deathSpeed.y; midPos.y += deathSpeed.y; haveVerticalSpeed = true; } else { // last Update() may have sunk us into // ground if pos.y was only marginally // larger than ground height, correct pos.y = realGroundHeight; midPos.y = pos.y + model->relMidPos.y; deathSpeed.y = 0.0f; } inBounds = pos.CheckInBounds(); reachedFinalPos = (!haveForwardSpeed && !haveVerticalSpeed); // reachedFinalPos = ((!haveForwardSpeed && !haveVerticalSpeed) || !inBounds); if (!inBounds) { // ensure that no more forward-speed updates are done // (prevents wrecks floating in mid-air at edge of map // due to gravity no longer being applied either) deathSpeed = ZeroVector; } featureDrawer->UpdateDrawPos(this); CalculateTransform(); } if (!reachedFinalPos) finishedUpdate = false; }else{ if (pos.y > finalHeight) { //! feature is falling if (def->drawType >= DRAWTYPE_TREE) treeDrawer->DeleteTree(pos); if (pos.y > 0.0f) { speed.y += mapInfo->map.gravity; //! gravity is negative } else { //! fall slower in water speed.y += mapInfo->map.gravity * 0.5; } pos.y += speed.y; midPos.y += speed.y; transMatrix[13] += speed.y; if (def->drawType >= DRAWTYPE_TREE) treeDrawer->AddTree(def->drawType - 1, pos, 1.0f); } else if (pos.y < finalHeight) { //! if ground is restored, make sure feature does not get buried if (def->drawType >= DRAWTYPE_TREE) treeDrawer->DeleteTree(pos); float diff = finalHeight - pos.y; pos.y = finalHeight; midPos.y += diff; transMatrix[13] += diff; speed.y = 0.0f; if (def->drawType >= DRAWTYPE_TREE) treeDrawer->AddTree(def->drawType - 1, pos, 1.0f); } if (pos.y != finalHeight) finishedUpdate = false; } isUnderWater = ((pos.y + height) < 0.0f); return finishedUpdate; }
void match::domatch(std::vector<SamePoint>& resultData) { const int nBlockSize = 512; int scale = 1; int nx1, ny1, nx2, ny2, nband1, nband2; uchar *pBuf = NULL; m_pImage->Open(_bstr_t(m_szPathNameL), modeRead); m_pImage->GetCols(&nx1); m_pImage->GetRows(&ny1); m_pImage->GetBandNum(&nband1); m_pImage->Close(); m_pImage->Open(_bstr_t(m_szPathNameR), modeRead); m_pImage->GetCols(&nx2); m_pImage->GetRows(&ny2); m_pImage->GetBandNum(&nband2); m_pImage->Close(); int mincr = /*max(max(max(nx1, ny1), nx2),ny2)*/(nx1+nx2+ny1+ny2)/4; while(mincr/scale >1024) { scale *= 2; } int nxsize1 = nx1/scale; int nysize1 = ny1/scale; int nxsize2 = nx2/scale; int nysize2 = ny2/scale; m_pImage->Open(_bstr_t(m_szPathNameL), modeRead); pBuf = new uchar[nxsize1*nysize1*nband1]; m_pImage->ReadImg(0, 0, nx1, ny1, pBuf, nxsize1, nysize1, nband1, 0, 0, nxsize1, nysize1, -1, 0); m_pImage->Close(); m_pImage->CreateImg(_bstr_t("templ.tif"), modeCreate, nxsize1, nysize1, Pixel_Byte, nband1, BIL, 0, 0, 1); m_pImage->WriteImg(0, 0, nxsize1, nysize1, pBuf, nxsize1, nysize1, nband1, 0, 0, nxsize1, nysize1, -1, 0); m_pImage->Close(); delete [] pBuf; m_pImage->Open(_bstr_t(m_szPathNameR), modeRead); pBuf = new uchar[nxsize2*nysize2*nband2]; m_pImage->ReadImg(0, 0, nx2, ny2, pBuf, nxsize2, nysize2, nband2, 0, 0, nxsize2, nysize2, -1, 0); m_pImage->Close(); m_pImage->CreateImg(_bstr_t("tempr.tif"), modeCreate, nxsize2, nysize2, Pixel_Byte, nband2, BIL, 0, 0, 1); m_pImage->WriteImg(0, 0, nxsize2, nysize2, pBuf, nxsize2, nysize2, nband2, 0, 0, nxsize2, nysize2, -1, 0); m_pImage->Close(); delete []pBuf; pBuf = NULL; sl.fetchFeatures("templ.tif"); sr.fetchFeatures("tempr.tif"); /*sl.fetchFeatures(m_szPathNameL); sr.fetchFeatures(m_szPathNameR);*/ Keypoint** nbrs; kd_node* kd_root; int nsize = sl.m_listKeyPoint.size(); int nsize2 = sr.m_listKeyPoint.size(); Keypoint* feat1 = (Keypoint*)malloc(nsize*sizeof(Keypoint)); std::list<Keypoint>::iterator temIte = sl.m_listKeyPoint.begin(); int i = 0; while(temIte != sl.m_listKeyPoint.end()) { feat1[i] = *temIte; ++i; ++temIte; } sl.m_listKeyPoint.clear(); Keypoint* feat2 = (Keypoint*)malloc(nsize2*sizeof(Keypoint)); temIte = sr.m_listKeyPoint.begin(); i = 0; while(temIte != sr.m_listKeyPoint.end()) { feat2[i] = *temIte; ++i; ++temIte; } sr.m_listKeyPoint.clear(); kd_root = kdtree_build(feat2, nsize2); int k = 0; double d0, d1; Keypoint* feat; int matchnum = 0; std::vector<SamePoint> sp; for (i = 0; i < nsize; ++i) { feat = feat1+i; k = kdtree_bbf_knn(kd_root, feat, 2, &nbrs, KDTREE_BBF_MAX_NN_CHKS); if (k == 2) { d0 = descr_dist_sq(feat, nbrs[0]); d1 = descr_dist_sq(feat, nbrs[1]); if (d0 < d1*NN_SQ_DIST_RATIO_THR) { sp.push_back(SamePoint(feat->dx, feat->dy, nbrs[0]->dx, nbrs[0]->dy)); ++matchnum; } } free(nbrs); } kdtree_release(kd_root); free(feat1); free(feat2); feat1 = NULL; feat2 = NULL; std::vector<double> matParameters; MatParamEstimator mpEstimator(5); int numForEstimate = 3; mpEstimator.leastSquaresEstimate(sp, matParameters); double usedData = Ransac<SamePoint, double>::compute(matParameters, &mpEstimator, sp, numForEstimate, resultData); sp.swap(std::vector<SamePoint>()); resultData.swap(std::vector<SamePoint>()); Pt lLeftTop(0, 0); Pt lRightBottom(nx1, ny1); double a = matParameters[0]; double b = matParameters[1]; double c = matParameters[2]*scale; double d = matParameters[3]; double e = matParameters[4]; double f = matParameters[5]*scale; std::list<Block> listDataBlock; for (int y = 0; y < ny1;) { if (y+nBlockSize < ny1) { for (int x = 0; x < nx1;) { if (x+nBlockSize < nx1) { Rec rect(a*x+b*y+c, a*(x+nBlockSize)+b*y+c, d*x+e*y+f, d*x+e*(y+nBlockSize)+f); if (rect.Intersects(Rec(0, nx2, 0, ny2))) { listDataBlock.push_back(Block(NULL, x, y, nBlockSize, nBlockSize)); } x += nBlockSize; } else { Rec rect(a*x+b*y+c, a*nx1+b*y+c, d*x+e*y+f, d*x+e*(y+nBlockSize)+f); if (rect.Intersects(Rec(0, nx2, 0, ny2))) { listDataBlock.push_back(Block(NULL, x, y, nx1-x, nBlockSize)); } x = nx1; } } y += nBlockSize; } else { for (int x = 0; x < nx1;) { if (x+nBlockSize < nx1) { Rec rect(a*x+b*y+c, a*(x+nBlockSize)+b*y+c, d*x+e*y+f, d*x+e*ny1+f); if (rect.Intersects(Rec(0, nx2, 0, ny2))) { listDataBlock.push_back(Block(NULL, x, y, nBlockSize, ny1-y)); } x += nBlockSize; } else { Rec rect(a*x+b*y+c, a*nx1+b*y+c, d*x+e*y+f, d*x+e*ny1+f); if (rect.Intersects(Rec(0, nx2, 0, ny2))) { listDataBlock.push_back(Block(NULL, x, y, nx1-x, ny1-y)); } x = nx1; } } y = ny1; } } int nBlockNumx = (nx2+nBlockSize-1)/nBlockSize; int nBlockNumy = (ny2+nBlockSize-1)/nBlockSize; int nBlockNum = nBlockNumx*nBlockNumy; std::vector<RBTree> vecKDTree(nBlockNum); std::list<Block>::iterator blockIte = listDataBlock.begin(); m_pImage->Open(_bstr_t(m_szPathNameL), modeRead); m_pImage2->Open(_bstr_t(m_szPathNameR), modeRead); int countblock = 0; std::list<SamePoint> listSP; std::vector<Keypoint> feature; std::vector<Keypoint> feature2; while(blockIte != listDataBlock.end()) { pBuf = new uchar[blockIte->nXSize*blockIte->nYSize*nband1]; m_pImage->ReadImg(blockIte->nXOrigin, blockIte->nYOrigin, blockIte->nXOrigin+blockIte->nXSize, blockIte->nYOrigin+blockIte->nYSize, pBuf, blockIte->nXSize, blockIte->nYSize, nband1, 0, 0, blockIte->nXSize, blockIte->nYSize, -1, 0); pixel_t* p = new pixel_t[blockIte->nXSize*blockIte->nYSize]; for (int y = 0; y < blockIte->nYSize; ++y) { for (int x = 0, m = 0; x < blockIte->nXSize*nband1; x += nband1, ++m) { double sum = 0; for (int n = 0; n < nband1; ++n) { sum += pBuf[y*blockIte->nXSize*nband1+x+n]; } p[y*blockIte->nXSize+m] = sum/(nband1*225.0); } } delete []pBuf; pBuf = NULL; sift(p, feature, blockIte->nXSize, blockIte->nYSize); p = NULL; std::vector<Keypoint>::iterator feaIte = feature.begin(); int count = 0; while(feaIte != feature.end()) { std::cout<<countblock<<"/"<<listDataBlock.size()<<":"<<count<<"/"<<feature.size()<<":"<<listSP.size()<<std::endl; ++count; feaIte->dx += blockIte->nXOrigin; feaIte->dy += blockIte->nYOrigin; int calx = int(feaIte->dx*a+feaIte->dy*b+c); int caly = int(feaIte->dx*d+feaIte->dy*e+f); int idx = calx/nBlockSize; int idy = caly/nBlockSize; if (idx >= nBlockNumx || idy >= nBlockNumy) { ++feaIte; continue; } int nBlockIndex = idy*nBlockNumx+idx; if (vecKDTree[nBlockIndex].num != 0 && vecKDTree[nBlockIndex].num < 50) { ++feaIte; continue; } if (vecKDTree[nBlockIndex].node == NULL) { int xo = idx*nBlockSize; int yo = idy*nBlockSize; int xsize = nBlockSize; int ysize = nBlockSize; if (idx == nBlockNumx-1) { xsize = nx2%nBlockSize; if (xsize == 0) { xsize = nBlockSize; } } if (idy == nBlockNumy-1) { ysize = ny2%nBlockSize; if (ysize == 0) { ysize = nBlockSize; } } pBuf = new uchar[xsize*ysize*nband2]; m_pImage2->ReadImg(xo, yo, xo+xsize, yo+ysize, pBuf, xsize, ysize, nband2, 0, 0, xsize, ysize, -1, 0); p = new pixel_t[xsize*ysize]; for(int y = 0; y < ysize; ++y) { for (int x = 0, m = 0; x < xsize*nband2; x += nband2, ++m) { double sum = 0; for (int n = 0; n < nband2; ++n) { sum += pBuf[y*xsize*nband2+x+n]; } p[y*xsize+m] = sum/(nband2*255.0); } } delete []pBuf; pBuf = NULL; sift(p, feature2, xsize, ysize); p = NULL; int nf2 = feature2.size(); vecKDTree[nBlockIndex].num = nf2; if (nf2 < 50) { ++feaIte; continue; } feat2 = (Keypoint*)malloc(nf2*sizeof(Keypoint)); std::vector<Keypoint>::iterator kIte2 = feature2.begin(); i = 0; while(kIte2 != feature2.end()) { kIte2->dx += xo; kIte2->dy += yo; feat2[i] = *kIte2; ++i; ++kIte2; } feature2.swap(std::vector<Keypoint>()); kd_root = kdtree_build(feat2, nf2); vecKDTree[nBlockIndex].node = kd_root; vecKDTree[nBlockIndex].feature = feat2; } k = kdtree_bbf_knn(vecKDTree[nBlockIndex].node, &(*feaIte), 2, &nbrs, KDTREE_BBF_MAX_NN_CHKS); if (k == 2) { d0 = descr_dist_sq(&(*feaIte), nbrs[0]); d1 = descr_dist_sq(&(*feaIte), nbrs[1]); if (d0 < d1*NN_SQ_DIST_RATIO_THR) { listSP.push_back(SamePoint(feaIte->dx, feaIte->dy, nbrs[0]->dx, nbrs[0]->dy)); } } free(nbrs); ++feaIte; } feature.swap(std::vector<Keypoint>()); std::vector<RBTree>::iterator kdIte = vecKDTree.begin(); while(kdIte != vecKDTree.end()) { if (kdIte->node != NULL) { free(kdIte->node); kdIte->node = NULL; free(kdIte->feature); kdIte->feature = NULL; } ++kdIte; } ++countblock; ++blockIte; } m_pImage->Close(); m_pImage2->Close(); std::vector<SamePoint> vecsp(std::make_move_iterator(std::begin(listSP)), std::make_move_iterator(std::end(listSP))); listSP.clear(); sp.swap(vecsp); mpEstimator.leastSquaresEstimate(sp, matParameters); if (sp.size() < 500) { usedData = Ransac<SamePoint, double>::compute(matParameters, &mpEstimator, sp, numForEstimate, resultData); } else { usedData = Ransac<SamePoint, double>::compute(matParameters, &mpEstimator, sp, numForEstimate, 0.5, 0.8, resultData); } std::cout<<usedData<<":"<<resultData.size()<<std::endl; sp.swap(std::vector<SamePoint>()); resultData.swap(std::vector<SamePoint>()); a = matParameters[0]; b = matParameters[1]; c = matParameters[2]; d = matParameters[3]; e = matParameters[4]; f = matParameters[5]; //mosaic Pt calrLeftTop; Pt calrRightBottom; calrLeftTop.x = lLeftTop.x*a+lLeftTop.y*b+c; calrLeftTop.y = lLeftTop.x*d+lLeftTop.y*e+f; calrRightBottom.x = lRightBottom.x*a+lRightBottom.y*b+c; calrRightBottom.y = lRightBottom.x*d+lRightBottom.y*e+f; Rec calRight(calrLeftTop.x, calrRightBottom.x, calrLeftTop.y, calrRightBottom.y); calRight.extend(); Rec Right(0, nx2, 0, ny2); Rec resultRec = Right.Union(calRight); Rec resultRectR = calRight.Intersected(Right); resultRectR.extend(); Pt callLeftTop; Pt callRightBottom; callLeftTop.y = (d/a*resultRectR.left-resultRectR.top+f-c*d/a)/(b*d/a-e); callLeftTop.x = (resultRectR.left-b*callLeftTop.y-c)/a; callRightBottom.y = (d/a*resultRectR.right-resultRectR.bottom+f-c*d/a)/(b*d/a-e); callRightBottom.x = (resultRectR.right-b*callRightBottom.y-c)/a; Rec resultRectL(callLeftTop.x, callRightBottom.x, callLeftTop.y, callRightBottom.y); resultRectL.extend(); m_pImage->CreateImg(_bstr_t("result.tif"), modeCreate, (int)resultRec.Width(), (int)resultRec.Height(), Pixel_Byte, nband1, BIL, 0, 0, 1); IImage* pImage = NULL; IImage* pImage2 = NULL; ::CoCreateInstance(CLSID_ImageDriver, NULL, CLSCTX_ALL, IID_IImage, (void**)&pImage); ::CoCreateInstance(CLSID_ImageDriver, NULL, CLSCTX_ALL, IID_IImage, (void**)&pImage2); pImage->Open(_bstr_t(m_szPathNameR), modeRead); pBuf = new uchar[nx2*nBlockSize*nband2]; for (int i = 0; i < ny2;) { if (i + nBlockSize < ny2) { pImage->ReadImg(0, i, nx2, i+nBlockSize, pBuf, nx2, nBlockSize, nband2, 0, 0, nx2, nBlockSize, -1, 0); m_pImage->WriteImg(int(0-resultRec.left), int(i-resultRec.top), int(nx2-resultRec.left), int(i+nBlockSize-resultRec.top), pBuf, nx2, nBlockSize, nband2, 0, 0, nx2, nBlockSize, -1, 0); i += nBlockSize; } else { pImage->ReadImg(0, i, nx2, ny2, pBuf, nx2, nBlockSize, nband2, 0, 0, nx2, ny2-i, -1, 0); m_pImage->WriteImg(int(0-resultRec.left), int(i-resultRec.top), int(nx2-resultRec.left), int(ny2-resultRec.top), pBuf, nx2, nBlockSize, nband2, 0, 0, nx2, ny2-i, -1, 0); i = ny2; } } pImage->Close(); delete []pBuf; pImage->Open(_bstr_t(m_szPathNameL), modeRead); pBuf = new uchar[nx1*nBlockSize*nband1]; for (int i = 0; i < calRight.Height();) { if (i+nBlockSize < calRight.Height()) { pImage->ReadImg(0, i, nx1, i+nBlockSize, pBuf, nx1, nBlockSize, nband1, 0, 0, nx1, nBlockSize, -1, 0); m_pImage->WriteImg(int(calRight.left-resultRec.left), int(calRight.top+i-resultRec.top), int(calRight.right-resultRec.left), int(calRight.top+i+nBlockSize-resultRec.top), pBuf, nx1, nBlockSize, nband1, 0, 0, nx1, nBlockSize, -1, 0); i += nBlockSize; } else { pImage->ReadImg(0, i, nx1, ny1, pBuf, nx1, nBlockSize, nband1, 0, 0, nx1, ny1-i, -1, 0); m_pImage->WriteImg(int(calRight.left-resultRec.left), int(calRight.top+i-resultRec.top), int(calRight.right-resultRec.left), int(calRight.bottom-resultRec.top), pBuf, nx1, nBlockSize, nband1, 0, 0, nx1, ny1-i, -1, 0); i = (int)calRight.Height(); } } pImage->Close(); delete []pBuf; pBuf = NULL; m_pImage->Close(); pImage->Open(_bstr_t(m_szPathNameL), modeRead); pImage2->Open(_bstr_t(m_szPathNameR), modeRead); m_pImage->Open(_bstr_t("result.tif"), modeReadWrite); pBuf = new uchar[nband1*(int)resultRectR.Width()*(int)resultRectR.Height()]; m_pImage->ReadImg(int(resultRectR.left-resultRec.left), int(resultRectR.top-resultRec.top), int(resultRectR.right-resultRec.left), int(resultRectR.bottom-resultRec.top), pBuf, (int)resultRectR.Width(), (int)resultRectR.Height(), nband1, 0, 0, (int)resultRectR.Width(), (int)resultRectR.Height(), -1, 0); uchar* pBufl = new uchar[nband1*(int)resultRectL.Width()*(int)resultRectL.Height()]; pImage->ReadImg((int)resultRectL.left, (int)resultRectL.top, (int)resultRectL.right, (int)resultRectL.bottom, pBufl, (int)resultRectL.Width(), (int) resultRectL.Height(), nband1, 0, 0, (int)resultRectL.Width(), (int)resultRectL.Height(), -1, 0); uchar* pBufr = new uchar[nband2*(int)resultRectR.Width()*(int)resultRectR.Height()]; pImage2->ReadImg((int)resultRectR.left, (int)resultRectR.top, (int)resultRectR.right, (int)resultRectR.bottom, pBufr, (int)resultRectR.Width(), (int)resultRectR.Height(), nband2, 0, 0, (int)resultRectR.Width(), (int)resultRectR.Height(), -1, 0); double lx, ly; for (int y = 0; y < (int)resultRectR.Height(); ++y) { for (int x = 0; x < (int)resultRectR.Width()*nband1; x += nband1) { ly = (d/a*(x+resultRectR.left)-(y+resultRectR.top)+f-c*d/a)/(b*d/a-e); lx = ((x+resultRectR.left)-b*ly-c)/a; if (ly < resultRectL.top || lx < resultRectL.left) { continue; } if (pBufl[(int)(ly-resultRectL.top)*(int)resultRectL.Width()*nband1+(int)(lx-resultRectL.left)] < 20 && pBufl[(int)(ly-resultRectL.top)*(int)resultRectL.Width()*nband1+(int)(lx-resultRectL.left)+1] < 20 && pBufl[(int)(ly-resultRectL.top)*(int)resultRectL.Width()*nband1+(int)(lx-resultRectL.left)+2] < 20) { for (int n = 0; n < nband2; ++n) { pBuf[y*(int)resultRectR.Width()*nband1+x+n] = pBufr[y*(int)resultRectR.Width()*nband2+x+n]; } } else if (pBufr[y*(int)resultRectR.Width()*nband1+x] < 20 && pBufr[y*(int)resultRectR.Width()*nband1+x+1]<20 && pBufr[y*(int)resultRectR.Width()*nband1+x+2]<20) { for (int n = 0; n < nband1; ++n) { pBuf[y*(int)resultRectR.Width()*nband1+x+n] = pBufl[(int)(ly-resultRectL.top)*(int)resultRectL.Width()*nband1+(int)(lx-resultRectL.left)+n]; } } else { for (int n = 0; n < nband1; ++n) { pBuf[y*(int)resultRectR.Width()*nband1+x+n] = (pBufl[(int)(ly-resultRectL.top)*(int)resultRectL.Width()*nband1+(int)(lx-resultRectL.left)+n] + pBufr[y*(int)resultRectR.Width()*nband2+x+n])/2; } } } } delete []pBufl; pBufl = NULL; delete []pBufr; pBufr = NULL; m_pImage->WriteImg(int(resultRectR.left-resultRec.left), int(resultRectR.top-resultRec.top), int(resultRectR.right-resultRec.left), int(resultRectR.bottom-resultRec.top), pBuf, (int)resultRectR.Width(), (int)resultRectR.Height(), nband1, 0, 0, (int)resultRectR.Width(), (int)resultRectR.Height(), -1, 0); delete []pBuf; pBuf = NULL; m_pImage->Close(); }
void Multiplexer::OnMultiplexerHeader( size_t peer, uint32_t seq, Connection& s, net::Buffer&& buffer) { die_unless(d_->ongoing_requests_[peer] > 0); d_->ongoing_requests_[peer]--; // received invalid Buffer: the connection has closed? if (!buffer.IsValid()) return; net::BufferReader br(buffer); StreamMultiplexerHeader header = StreamMultiplexerHeader::Parse(br); LOG << "OnMultiplexerHeader() header" << " magic=" << unsigned(header.magic) << " size=" << header.size << " num_items=" << header.num_items << " first_item=" << header.first_item << " typecode_verify=" << header.typecode_verify << " stream_id=" << header.stream_id; // received stream id StreamId id = header.stream_id; size_t local_worker = header.receiver_local_worker; // round of allocation size to next power of two size_t alloc_size = header.size; if (alloc_size < THRILL_DEFAULT_ALIGN) alloc_size = THRILL_DEFAULT_ALIGN; alloc_size = tlx::round_up_to_power_of_two(alloc_size); if (header.magic == MagicByte::CatStreamBlock) { CatStreamDataPtr stream = GetOrCreateCatStreamData( id, local_worker, /* dia_id (unknown at this time) */ 0); stream->rx_net_bytes_ += buffer.size(); if (header.IsEnd()) { sLOG << "end of stream on" << s << "in CatStream" << id << "from worker" << header.sender_worker; stream->OnStreamBlock( header.sender_worker, header.seq, Block()); } else { sLOG << "stream header from" << s << "on CatStream" << id << "from worker" << header.sender_worker << "for local_worker" << local_worker << "seq" << header.seq << "size" << header.size; PinnedByteBlockPtr bytes = block_pool_.AllocateByteBlock( alloc_size, local_worker); sLOG << "new PinnedByteBlockPtr bytes=" << *bytes; d_->ongoing_requests_[peer]++; dispatcher_.AsyncRead( s, seq + 1, header.size, std::move(bytes), [this, peer, header, stream]( Connection& s, PinnedByteBlockPtr&& bytes) { OnCatStreamBlock(peer, s, header, stream, std::move(bytes)); }); } } else if (header.magic == MagicByte::MixStreamBlock) { MixStreamDataPtr stream = GetOrCreateMixStreamData( id, local_worker, /* dia_id (unknown at this time) */ 0); stream->rx_net_bytes_ += buffer.size(); if (header.IsEnd()) { sLOG << "end of stream on" << s << "in MixStream" << id << "from worker" << header.sender_worker; stream->OnStreamBlock(header.sender_worker, header.seq, Block()); } else { sLOG << "stream header from" << s << "on MixStream" << id << "from worker" << header.sender_worker << "for local_worker" << local_worker << "seq" << header.seq << "size" << header.size; PinnedByteBlockPtr bytes = block_pool_.AllocateByteBlock( alloc_size, local_worker); d_->ongoing_requests_[peer]++; dispatcher_.AsyncRead( s, seq + 1, header.size, std::move(bytes), [this, peer, header, stream]( Connection& s, PinnedByteBlockPtr&& bytes) mutable { OnMixStreamBlock(peer, s, header, stream, std::move(bytes)); }); } } else { die("Invalid magic byte in MultiplexerHeader"); } AsyncReadMultiplexerHeader(peer, s); }
void CFeature::Initialize(const float3& _pos, const FeatureDef* _def, short int _heading, int facing, int _team, int _allyteam, std::string fromUnit, const float3& speed, int _smokeTime) { pos = _pos; def = _def; defName = def->myName; heading = _heading; buildFacing = facing; team = _team; allyteam = _allyteam; emitSmokeTime = _smokeTime; createdFromUnit = fromUnit; ChangeTeam(team); // maybe should not be here, but it prevents crashes caused by team = -1 pos.CheckInBounds(); health = def->maxHealth; blocking = def->blocking; xsize = ((facing & 1) == 0) ? def->xsize : def->zsize; zsize = ((facing & 1) == 1) ? def->xsize : def->zsize; mass = def->mass; noSelect = def->noSelect; if (def->drawType == DRAWTYPE_MODEL) { model = LoadModel(def); if (!model) { logOutput.Print("Features: Couldn't load model for " + defName); SetRadius(0.0f); midPos = pos; } else { height = model->height; SetRadius(model->radius); midPos = pos + model->relMidPos; collisionVolume = new CollisionVolume(def->collisionVolume, model->radius); } } else if (def->drawType >= DRAWTYPE_TREE) { SetRadius(TREE_RADIUS); midPos = pos + (UpVector * TREE_RADIUS); height = 2 * TREE_RADIUS; // LoadFeaturesFromMap() doesn't set a scale for trees collisionVolume = new CollisionVolume(def->collisionVolume, TREE_RADIUS); } else { // geothermal (no collision volume) SetRadius(0.0f); midPos = pos; } featureHandler->AddFeature(this); qf->AddFeature(this); CalculateTransform(); if (blocking) { Block(); } if (def->floating) { finalHeight = ground->GetHeight(pos.x, pos.z); } else { finalHeight = ground->GetHeight2(pos.x, pos.z); } if (def->drawType >= DRAWTYPE_TREE) { treeDrawer->AddTree(def->drawType - 1, pos, 1); } if (speed != ZeroVector) { deathSpeed = speed; } }
Block FallingGravel::getPlacedBlock() const { return Block(Blocks::builtin::Gravel::descriptor()); }
Block FallingSand::getPlacedBlock() const { return Block(Blocks::builtin::Sand::descriptor()); }
void GameGraphic::initStaticBackground(BoardBatch& staticBoardBatch, float lowX, float lowY, Player& player) { const float squareSize = TetrisData::getInstance().getTetrisSquareSize(); const float borderSize = TetrisData::getInstance().getTetrisBorderSize(); const TetrisBoard& tetrisBoard = player.getTetrisBoard(); const int columns = tetrisBoard.getColumns(); const int rows = tetrisBoard.getRows(); const float middleDistance = 5; const float rightDistance = 5; const float infoSize = squareSize * 5; const float boardWidth = squareSize * columns; width_ = squareSize * columns + infoSize + borderSize * 2 + middleDistance + rightDistance; height_ = squareSize * (rows - 2) + borderSize * 2; // Draw the player area. float x = lowX + borderSize; float y = lowY * 0.5f + borderSize; staticBoardBatch.addRectangle( x, y, boardWidth + infoSize + middleDistance + rightDistance, squareSize * (rows - 2), TetrisData::getInstance().getPlayerAreaColor()); // Draw the outer square. x = lowX + borderSize; y = lowY + borderSize; staticBoardBatch.addRectangle( x, y, squareSize * columns, squareSize * (rows - 2), TetrisData::getInstance().getOuterSquareColor()); // Draw the inner squares. for (int row = 0; row < rows - 2; ++row) { for (int column = 0; column < columns; ++column) { x = lowX + borderSize + squareSize * column + squareSize * 0.1f; y = lowY + borderSize + squareSize * row + squareSize * 0.1f; staticBoardBatch.addRectangle( x, y, squareSize * 0.8f, squareSize * 0.8f, TetrisData::getInstance().getInnerSquareColor()); } } // Draw the block start area. x = lowX + borderSize; y = lowY + borderSize + squareSize * (rows - 4); staticBoardBatch.addRectangle( x, y, squareSize * columns, squareSize * 2, TetrisData::getInstance().getStartAreaColor()); // Draw the preview block area. x = lowX + borderSize + boardWidth + middleDistance; y = lowY + borderSize + squareSize * (rows - 4) - (squareSize * 5 + middleDistance); staticBoardBatch.addRectangle( x, y, infoSize, infoSize, TetrisData::getInstance().getStartAreaColor()); nextBlock_ = DrawBlock(Block(tetrisBoard.getNextBlockType(), 0, 0), tetrisBoard.getRows(), squareSize, x + squareSize * 2.5f, y + squareSize * 2.5f, true); mw::Font font = TetrisData::getInstance().getDefaultFont(30); name_ = DrawText(player.getName(), font, x, y + squareSize * 5, 8.f); level_ = player.getLevel(); textLevel_ = DrawText("Level " + std::to_string(level_), font, x, y - 20, 8.f); points_ = player.getPoints(); textPoints_ = DrawText("Points " + std::to_string(points_), font, x, y - 20 - 12, 8.f); clearedRows_ = player.getClearedRows(); textClearedRows_ = DrawText("Rows " + std::to_string(clearedRows_), font, x, y - 20 - 12 * 2, 8.f); const mw::Color borderColor = TetrisData::getInstance().getBorderColor(); // Add border. // Left-up corner. x = lowX; y = lowY + height_ - borderSize; staticBoardBatch.addSquare( x, y, borderSize, borderColor); // Right-up corner. x = lowX + width_ - borderSize; y = lowY + height_ - borderSize; staticBoardBatch.addSquare( x, y, borderSize, borderColor); // Left-down corner. x = lowX; y = lowY; staticBoardBatch.addSquare( x, y, borderSize, borderColor); // Right-down corner. x = lowX + width_ - borderSize; y = lowY; staticBoardBatch.addSquare( x, y, borderSize, borderColor); // Up. x = lowX + borderSize; y = lowY + height_ - borderSize; staticBoardBatch.addRectangle( x, y, width_ - 2 * borderSize, borderSize, borderColor); // Down. x = lowX + borderSize; y = lowY; staticBoardBatch.addRectangle( x, y, width_ - 2 * borderSize, borderSize, borderColor); // Left. x = lowX; y = lowY + borderSize; staticBoardBatch.addRectangle( x, y, borderSize, height_ - 2 * borderSize, borderColor); // Right. x = lowX + width_ - borderSize; y = lowY + borderSize; staticBoardBatch.addRectangle( x, y, borderSize, height_ - 2 * borderSize, borderColor); rows_.clear(); currentBlock_ = DrawBlock(tetrisBoard.getBlock(), tetrisBoard.getRows(), squareSize, lowX + borderSize, lowY + borderSize, false); // Add rows to represent the board. // Add free rows to represent potential rows, e.g. the board receives external rows. for (int row = 0; row < rows; ++row) { auto drawRow = std::make_shared<DrawRow>(row, tetrisBoard, squareSize, lowX + borderSize, lowY + borderSize); auto freeRow = std::make_shared<DrawRow>(*drawRow); freeRow->clear(); // Make all elements to only contain blocktype empty squares. rows_.push_back(drawRow); freeRows_.push_back(freeRow); } middleText_ = DrawText(lowX + borderSize + squareSize * columns * 0.5f, lowY + height_ * 0.5f); }
Block FindBlock(const HashValue& hash) override { EXT_LOCK (MtxSqlite) { DbDataReader dr = m_cmdFindBlock.Bind(1, ReducedBlockHash(hash)).ExecuteReader(); return dr.Read() ? LoadBlock(dr) : Block(nullptr); } }
bool File::load(string path) { //load the blend file into the stream if(file.is_open()) file.close(); file.open(ofToDataPath(path, true).c_str(), ios::binary); //info should contain blender now, if not it is compressed string info = readString(7); //check if the file is gzipped if(info != "BLENDER") { seek(0); //unzip the blend file to a temp file and reload Poco::InflatingInputStream inflater(file, Poco::InflatingStreamBuf::STREAM_GZIP); Poco::TemporaryFile tempFile; tempFile.keepUntilExit(); std::ofstream out(tempFile.path().c_str(), ios::binary); Poco::StreamCopier::copyStream( inflater, out); out.close(); file.close(); file.open(tempFile.path().c_str(), ios::binary); info = readString(7); if(info != "BLENDER") { ofLogWarning(OFX_BLENDER) << "Could not read blend file " << path; } else { ofLogVerbose(OFX_BLENDER) << "Blend file is gzipped, temporarily decompressed contents to " << tempFile.path(); } } //now extract the rest of the header data string tempString = readString(1); if(tempString == "-") pointerSize = 8; else if(tempString == "_") pointerSize = 4; //ofLogVerbose(OFX_BLENDER) << "Pointer Size is " << pointerSize; if(pointerSize == 4) { readPointer = std::bind(&File::read<unsigned int>, this); } else { readPointer = std::bind(&File::read<unsigned long>, this); } bool littleEndianness; char structPre = ' '; tempString = readString(1); if(tempString == "v") { littleEndianness = true; structPre = '<'; } else if(tempString == "V") { littleEndianness = false; structPre = '>'; } //ofLogVerbose(OFX_BLENDER) << "Struct pre is " << structPre; //ofLogVerbose(OFX_BLENDER) << "Little Endianness is " << littleEndianness; //version version = readString(3); //now go through all them blocks blocks.push_back(Block(this)); //read the first block readHeader(blocks.back()); while(blocks.back().code != "DNA1" && blocks.back().code != "SDNA") { //skip the block data file.seekg(file.tellg() + streamoff(blocks.back().size)); //read a new block blocks.push_back(Block(this)); readHeader(blocks.back()); } //advance readString(4); readString(4); //NAMES unsigned int numNames = read<unsigned int>(); for(unsigned int i=0; i<numNames; i++) { catalog.names.push_back(DNAName(readString(0))); } align(file); //TYPES readString(4); unsigned int numTypes = read<unsigned int>(); //cout << "FOUND TYPES " << numTypes << endl; for(unsigned int i=0; i<numTypes; i++) { catalog.types.push_back(DNAType(readString(0), i)); } align(file); //TYPE LENGTHS readString(4);; for(unsigned int i=0; i<numTypes; i++) { catalog.types[i].size = read<unsigned short>(); if(catalog.types[i].size == 0) //assume it is a pointer catalog.types[i].size = pointerSize; } align(file); //STRUCTURES readString(4); unsigned int numStructs = read<unsigned int>(); //cout << "FOUND STRUCTURES " << numStructs << endl; for(unsigned int i=0; i<numStructs; i++) { //get the type unsigned int index = read<unsigned short>(); DNAType* type = &catalog.types[index]; catalog.structures.push_back(DNAStructure(type)); DNAStructure& structure = catalog.structures.back(); //get the fields for the structure unsigned short numFields = read<unsigned short>(); unsigned int curOffset = 0; for(unsigned int j=0; j<numFields; j++) { unsigned short typeIndex = read<unsigned short>(); unsigned short nameIndex = read<unsigned short>(); DNAType* type = &catalog.types[typeIndex]; DNAName* name = &catalog.names[nameIndex]; structure.fields.push_back(DNAField(type, name, curOffset)); //if the field is a pointer, then only add the pointer size to offset bool offsetSet = false; if(structure.fields.back().isPointer) { int amount = 0; if(structure.fields.back().isArray) { amount = structure.fields.back().arraySizes[0]; } if(amount == 0) amount = 1; curOffset += (pointerSize * amount); offsetSet = true; } else if(structure.fields.back().isArray) { //arrays add n times the size to offset float multi = 0; for(int s: structure.fields.back().arraySizes) { if(s!=-1) { if(multi == 0) multi += s; else multi *= s; } } if(multi != 0) offsetSet = true; curOffset += type->size * multi; } if(!offsetSet) { curOffset += type->size; } } } align(file); //now link all structures with the File Blocks vector<Block>::iterator it = blocks.begin(); while(it != blocks.end()) { (*it).structure = &catalog.structures[(*it).SDNAIndex]; it++; } ofLogVerbose(OFX_BLENDER) << "Loaded \"" << path << "\" - Blender version is " << version; return true; }
static Block generate_test_log_block() { return Block(1234.2, LogSeverity::WARNING, "test", "test message"); }
Packet::Packet() : m_wire(Block(tlv::LpPacket)) { }
void CFeature::Initialize(const float3& _pos, const FeatureDef* _def, short int _heading, int facing, int _team, int _allyteam, const UnitDef* _udef, const float3& speed, int _smokeTime) { def = _def; udef = _udef; defID = def->id; heading = _heading; buildFacing = facing; team = _team; allyteam = _allyteam; emitSmokeTime = _smokeTime; mass = def->mass; crushResistance = def->crushResistance; health = def->maxHealth; blocking = def->blocking; xsize = ((facing & 1) == 0) ? def->xsize : def->zsize; zsize = ((facing & 1) == 1) ? def->xsize : def->zsize; noSelect = def->noSelect; if (def->drawType == DRAWTYPE_MODEL) { if ((model = def->LoadModel()) == NULL) { LOG_L(L_ERROR, "Features: Couldn't load model for %s", def->name.c_str()); } else { SetMidAndAimPos(model->relMidPos, model->relMidPos, true); SetRadiusAndHeight(model->radius, model->height); } } else { if (def->drawType >= DRAWTYPE_TREE) { // LoadFeaturesFromMap() doesn't set a scale for trees SetMidAndAimPos(UpVector * TREE_RADIUS, UpVector * TREE_RADIUS, true); SetRadiusAndHeight(TREE_RADIUS, TREE_RADIUS * 2.0f); } } // note: gets deleted in ~CSolidObject collisionVolume = new CollisionVolume(def->collisionVolume, radius); Move3D(_pos.cClampInMap(), false); UpdateMidAndAimPos(); CalculateTransform(); featureHandler->AddFeature(this); qf->AddFeature(this); // maybe should not be here, but it prevents crashes caused by team = -1 ChangeTeam(team); if (blocking) { Block(); } if (def->floating) { finalHeight = ground->GetHeightAboveWater(pos.x, pos.z); } else { finalHeight = ground->GetHeightReal(pos.x, pos.z); } if (speed != ZeroVector) { deathSpeed = speed; } reachedFinalPos = (speed == ZeroVector && pos.y == finalHeight); }
Block BlockChain::getBlock(int number) { return Block(_provider.request("eth_getBlockByNumber", Arguments(hex(number), _fetchBlockDetails))); }
/* ExtractHOG is for extracting HOG descriptor of an image Input: im: A grayscale image in height x width. Output: HOGBlock: The HOG descriptor of the input image. */ Mat HOGExtractor::ExtractHOG(const Mat& im) { // Pad the im in order to make the height and width the multiplication of // the size of cells. int height = im.rows; int width = im.cols; int padHeight = height % cells == 0 ? 0 : (cells - height % cells); int padWidth = width % cells == 0 ? 0 : (cells - width % cells); Mat paddedIm(height+padHeight, width+padWidth, CV_32FC1, Scalar(0)); Range imRanges[2]; imRanges[0] = Range(0, height); imRanges[1] = Range(0, width); im.copyTo(paddedIm(imRanges)); height = paddedIm.rows; width = paddedIm.cols; /* TODO 1: Compute the horizontal and vertical gradients for each pixel. Put them in gradX and gradY respectively. In addition, compute the angles (using atan2) and magnitudes by gradX and gradY, and put them in angle and magnitude. */ Mat hx(1, 3, CV_32FC1, Scalar(0)); hx.at<float>(0, 0) = -1; hx.at<float>(0, 1) = 0; hx.at<float>(0, 2) = 1; Mat hy = -hx.t(); Mat gradX(height, width, CV_32FC1, Scalar(0)); Mat gradY(height, width, CV_32FC1, Scalar(0)); Mat angle(height, width, CV_32FC1, Scalar(0)); Mat magnit(height, width, CV_32FC1, Scalar(0)); float pi = 3.1416; // Begin TODO 1 filter2D(paddedIm, gradX, -1, hx); filter2D(paddedIm, gradY, -1, hy); magnitude(gradX, gradY, magnit); for (int i = 0; i < height; ++i) for (int j = 0; j < width; ++j) angle.at<float>(i, j) = atan2(gradY.at<float>(i, j), gradX.at<float>(i, j)); // End TODO 1 /* TODO 2: Construct HOG for each cells, and put them in HOGCell. numberOfVerticalCell and numberOfHorizontalCell are the numbers of cells in vertical and horizontal directions. You should construct the histogram according to the bins. The bins range from -pi to pi in this project, and the interval is given by (2*pi)/bins. */ int numberOfVerticalCell = height / cells; int numberOfHorizontalCell = width / cells; Mat HOGCell(numberOfVerticalCell, numberOfHorizontalCell, CV_32FC(bins), Scalar(0)); float piInterval = 2 * pi / bins; // Begin TODO 2 for (int i = 0; i < numberOfVerticalCell; ++i) for (int j = 0; j < numberOfHorizontalCell; ++j) for (int p = i * cells; p < i * cells + cells; ++p) for (int q = j * cells; q < j * cells + cells; ++q) HOGCell.at<Vec<float, 9>>(i, j)[min(bins - 1, int(floor((angle.at<float>(p, q) + pi) / piInterval)))] += magnit.at<float>(i, j); // End TODO 2 /* TODO 3: Concatenate HOGs of the cells within each blocks and normalize them. The result should be stored in HOGBlock, where numberOfVerticalBlock and numberOfHorizontalBlock are the number of blocks in vertical and horizontal directions. */ int numberOfVerticalBlock = numberOfVerticalCell - 1; int numberOfHorizontalBlock = numberOfHorizontalCell - 1; Mat HOGBlock(numberOfVerticalBlock, numberOfHorizontalBlock, CV_32FC(blocks*blocks*bins), Scalar(0)); Mat Block(1, blocks * blocks * bins, CV_32FC1, Scalar(0)); // Begin TODO 3 for (int i = 0; i < numberOfVerticalBlock; ++i) for (int j = 0; j < numberOfHorizontalBlock; ++j) { for (int k = 0; k < bins; ++k) { Block.at<float>(0, k) = HOGCell.at<Vec<float, 9>>(i, j)[k]; Block.at<float>(0, k + bins) = HOGCell.at<Vec<float, 9>>(i, j + 1)[k]; Block.at<float>(0, k + 2 * bins) = HOGCell.at<Vec<float, 9>>(i + 1, j)[k]; Block.at<float>(0, k + 3 * bins) = HOGCell.at<Vec<float, 9>>(i + 1, j + 1)[k]; } float sum = 0; for (int k = 0; k < blocks * blocks * bins; ++k) sum += Block.at<float>(0,k); for (int k = 0; k < blocks * blocks * bins; ++k) HOGBlock.at<Vec<float, 36>>(i, j)[k] = sum == 0 ? 0 : Block.at<float>(0, k) / sum; } // End TODO 3 return HOGBlock; }
Block BlockChain::getBlock(const char *hash) { return Block(_provider.request("eth_getBlockByHash", Arguments(hash, _fetchBlockDetails))); }
void Window_set_shortcut(int action_id) { short clicked_button; short order_index; short config_index; short redraw_controls=1; word * shortcut_ptr=NULL; word backup_shortcut[2]; shortcut_ptr=Shortcut(action_id); backup_shortcut[0]=shortcut_ptr[0]; backup_shortcut[1]=shortcut_ptr[1]; // Recherche dans hotkeys order_index=0; while (Ordering[order_index]!=action_id) { order_index++; if (order_index>=NB_SHORTCUTS) { Warning_message("Shortcut does not exist!"); return; } } /* config_index=0; while (ConfigKey[config_index].Number!=order_index) { config_index++; if (config_index>=NB_SHORTCUTS) { Error(0); return; } } */ config_index=order_index; // Comprends pas... ça devrait pas marcher Open_window(302,131,"Keyboard shortcut"); Window_set_normal_button(181,111,55,14,"Cancel",0,1,KEY_ESC); // 1 Window_set_normal_button(241,111,55,14,"OK",0,1,SDLK_RETURN); // 2 Window_set_normal_button(6,111,111,14,"Reset default",0,1,KEY_NONE); // 3 // Titre Block(Window_pos_X+(Menu_factor_X*5), Window_pos_Y+(Menu_factor_Y*16), Menu_factor_X*292,Menu_factor_Y*11,MC_Black); Print_in_window(7,18,ConfigKey[config_index].Label,MC_White,MC_Black); // Zone de description Window_display_frame_in(5,68,292,37); Print_in_window(8,70,ConfigKey[config_index].Explanation1,MC_Black,MC_Light); Print_in_window(8,78,ConfigKey[config_index].Explanation2,MC_Black,MC_Light); Print_in_window(8,86,ConfigKey[config_index].Explanation3,MC_Black,MC_Light); // Shortcut 0 Window_set_normal_button(27,30,177,14,"",0,1,KEY_NONE); // 4 Window_set_normal_button(209,30,56,14,"Remove",0,1,KEY_NONE); // 5 // Shortcut 1 Window_set_normal_button(27,49,177,14,"",0,1,KEY_NONE); // 6 Window_set_normal_button(209,49,56,14,"Remove",0,1,KEY_NONE); // 7 Display_cursor(); do { if (redraw_controls) { Hide_cursor(); Block(Window_pos_X+(Menu_factor_X*32), Window_pos_Y+(Menu_factor_Y*33), Menu_factor_X*21*8,Menu_factor_Y*8,MC_Light); Print_in_window_limited(32,33,Key_name(shortcut_ptr[0]),21,MC_Black,MC_Light); Block(Window_pos_X+(Menu_factor_X*32), Window_pos_Y+(Menu_factor_Y*52), Menu_factor_X*21*8,Menu_factor_Y*8,MC_Light); Print_in_window_limited(32,52,Key_name(shortcut_ptr[1]),21,MC_Black,MC_Light); Update_rect(Window_pos_X,Window_pos_Y,302*Menu_factor_X,131*Menu_factor_Y); Display_cursor(); redraw_controls=0; } clicked_button=Window_clicked_button(); switch (clicked_button) { case -1: case 0: break; case 4: // Change 0 Redefine_control(&shortcut_ptr[0], 32, 33); redraw_controls=1; break; case 6: // Change 1 Redefine_control(&shortcut_ptr[1], 32, 52); redraw_controls=1; break; case 5: // Remove 0 shortcut_ptr[0]=0; redraw_controls=1; break; case 7: // Remove 1 shortcut_ptr[1]=0; redraw_controls=1; break; case 3: // Defaults shortcut_ptr[0]=ConfigKey[config_index].Key; shortcut_ptr[1]=ConfigKey[config_index].Key2; redraw_controls=1; break; case 1: // Cancel shortcut_ptr[0]=backup_shortcut[0]; shortcut_ptr[1]=backup_shortcut[1]; case 2: // OK default: break; } } while ((clicked_button!=1) && (clicked_button!=2) && (Key!=SDLK_RETURN)); Key=0; Close_window(); Display_cursor(); }
Block BlockChain::getUncle(const char *blockHash, int index) { return Block(_provider.request("eth_getUncleByBlockHashAndIndex", Arguments(blockHash, hex(index)))); }
void Button_Stats(void) { short clicked_button; char buffer[37]; dword color_usage[256]; unsigned long long freeRam; qword mem_size = 0; Open_window(310,174,"Statistics"); // Dessin de la fenetre ou va s'afficher le texte Window_display_frame_in(8,17,294,132); Block(Window_pos_X+(Menu_factor_X*9), Window_pos_Y+(Menu_factor_Y*18), Menu_factor_X*292,Menu_factor_Y*130,MC_Black); Window_set_normal_button(120,153,70,14,"OK",0,1,KEY_ESC); // 1 // Affichage du numéro de version Print_in_window(10,19,"Program version:",STATS_TITLE_COLOR,MC_Black); sprintf(buffer,"%s.%s",Program_version, SVN_revision); Print_in_window(146,19,buffer,STATS_DATA_COLOR,MC_Black); Print_in_window(10,35,"Build options:",STATS_TITLE_COLOR,MC_Black); Print_in_window(146,35,TrueType_is_supported()?"TTF fonts":"no TTF fonts",STATS_DATA_COLOR,MC_Black); // Affichage de la mémoire restante Print_in_window(10,51,"Free memory: ",STATS_TITLE_COLOR,MC_Black); freeRam = Memory_free(); if(freeRam > (100ULL*1024*1024*1024)) sprintf(buffer,"%u Gigabytes",(unsigned int)(freeRam/(1024*1024*1024))); else if(freeRam > (100*1024*1024)) sprintf(buffer,"%u Megabytes",(unsigned int)(freeRam/(1024*1024))); else if(freeRam > 100*1024) sprintf(buffer,"%u Kilobytes",(unsigned int)(freeRam/1024)); else sprintf(buffer,"%u bytes",(unsigned int)freeRam); Print_in_window(114,51,buffer,STATS_DATA_COLOR,MC_Black); // Used memory Print_in_window(10,59,"Used memory pages: ",STATS_TITLE_COLOR,MC_Black); if(Stats_pages_memory > (100LL*1024*1024*1024)) sprintf(buffer,"%ld (%lld Gb)",Stats_pages_number, Stats_pages_memory/(1024*1024*1024)); else if(Stats_pages_memory > (100*1024*1024)) sprintf(buffer,"%ld (%lld Mb)",Stats_pages_number, Stats_pages_memory/(1024*1024)); else sprintf(buffer,"%ld (%lld Kb)",Stats_pages_number, Stats_pages_memory/1024); Print_in_window(162,59,buffer,STATS_DATA_COLOR,MC_Black); // Affichage de l'espace disque libre sprintf(buffer,"Free space on %c:",Main_current_directory[0]); Print_in_window(10,67,buffer,STATS_TITLE_COLOR,MC_Black); #if defined(__WIN32__) { ULARGE_INTEGER tailleU; GetDiskFreeSpaceEx(Main_current_directory,&tailleU,NULL,NULL); mem_size = tailleU.QuadPart; } #elif defined(__linux__) || defined(__macosx__) || defined(__FreeBSD__) // Note: under MacOSX, both macros are defined anyway. { struct statfs disk_info; statfs(Main_current_directory,&disk_info); mem_size=(qword) disk_info.f_bfree * (qword) disk_info.f_bsize; } #elif defined(__HAIKU__) mem_size = haiku_get_free_space(Main_current_directory); #else // Free disk space is only for shows. Other platforms can display 0. #warning "Missing code for your platform !!! Check and correct please :)" mem_size=0; #endif if(mem_size > (100ULL*1024*1024*1024)) sprintf(buffer,"%u Gigabytes",(unsigned int)(mem_size/(1024*1024*1024))); else if(mem_size > (100*1024*1024)) sprintf(buffer,"%u Megabytes",(unsigned int)(mem_size/(1024*1024))); else if(mem_size > (100*1024)) sprintf(buffer,"%u Kilobytes",(unsigned int)(mem_size/1024)); else sprintf(buffer,"%u bytes",(unsigned int)mem_size); Print_in_window(146,67,buffer,STATS_DATA_COLOR,MC_Black); // Affichage des informations sur l'image Print_in_window(10,83,"Picture info.:",STATS_TITLE_COLOR,MC_Black); // Affichage des dimensions de l'image Print_in_window(18,91,"Dimensions :",STATS_TITLE_COLOR,MC_Black); sprintf(buffer,"%dx%d",Main_image_width,Main_image_height); Print_in_window(122,91,buffer,STATS_DATA_COLOR,MC_Black); // Affichage du nombre de couleur utilisé Print_in_window(18,99,"Colors used:",STATS_TITLE_COLOR,MC_Black); memset(color_usage,0,sizeof(color_usage)); sprintf(buffer,"%d",Count_used_colors(color_usage)); Print_in_window(122,99,buffer,STATS_DATA_COLOR,MC_Black); // Affichage des dimensions de l'écran Print_in_window(10,115,"Resolution:",STATS_TITLE_COLOR,MC_Black); sprintf(buffer,"%dx%d",Screen_width,Screen_height); Print_in_window(106,115,buffer,STATS_DATA_COLOR,MC_Black); Update_rect(Window_pos_X,Window_pos_Y,Menu_factor_X*310,Menu_factor_Y*174); Display_cursor(); do { clicked_button=Window_clicked_button(); if (Is_shortcut(Key,0x200+BUTTON_HELP)) clicked_button=1; } while ( (clicked_button!=1) && (Key!=SDLK_RETURN) ); if(Key==SDLK_RETURN)Key=0; Close_window(); Unselect_button(BUTTON_HELP); Display_cursor(); }
Block BlockChain::getUncle(int blockNumber, int index) { return Block(_provider.request("eth_getUncleByBlockNumberAndIndex", Arguments(hex(blockNumber), hex(index)))); }
double CachedQuarkletProblem<PROBLEM>::a(const Index& lambda, const Index& nu) const { //const int lambda_num = number(lambda,2); double r = 0; WaveletBasis mybasis(basis()); const int jmax = mybasis.get_jmax_(); const int pmax = mybasis.get_pmax_(); const int lambda_num = number(lambda, jmax); const int nu_num = number(nu,jmax); //cout << "Punkt 1" << endl; // BE CAREFUL: KEY OF GENERATOR LEVEL IS j0-1 NOT j0 !!!! typedef typename Index::type_type generator_type; int j = (lambda.e() == generator_type()) ? (lambda.j()-1) : lambda.j(); // check wether entry has already been computed typedef std::list<Index> IntersectingList; // search for column 'nu' typename ColumnCache::iterator col_lb(entries_cache.lower_bound(nu_num)); typename ColumnCache::iterator col_it(col_lb); if (col_lb == entries_cache.end() || entries_cache.key_comp()(nu_num, col_lb->first)) { // insert a new column typedef typename ColumnCache::value_type value_type; col_it = entries_cache.insert(col_lb, value_type(nu_num, Column())); } //cout << "Punkt 2" << endl; Column& col(col_it->second); // check wether the level 'lambda' belongs to has already been calculated typename Column::iterator lb(col.lower_bound(j)); typename Column::iterator it(lb); // no entries have ever been computed for this column and this level if (lb == col.end() || col.key_comp()(j, lb->first)) { //cout << "Punkt 3" << endl; // compute whole level block // #### ONLY CDD COMPRESSION STRATEGY IMPLEMENTED #### // #### MAYBE WE ADD TRUNK FOR STEVENSON APPROACH #### // #### LATER. #### // insert a new level typedef typename Column::value_type value_type; it = col.insert(lb, value_type(j, Block())); Block& block(it->second); IntersectingList nus; for(int p=0; p<=pmax; p++){ intersecting_wavelets(basis(), nu, std::max(j, basis().j0()), j == (basis().j0()-1), nus, p); // for (typename IntersectingList::const_iterator it100(nus.begin()), itend(nus.end()); // it100 != itend; ++it100) { // cout << *it100 << endl; // } // compute entries for (typename IntersectingList::const_iterator it(nus.begin()), itend(nus.end()); it != itend; ++it) { const double entry = problem->a(*it, nu); // cout << *it << ", " << nu << ": " << entry << endl; // cout << (*it).number()+(*it).p()*waveletsonplevel << endl; typedef typename Block::value_type value_type_block; if (entry != 0.) { block.insert(block.end(), value_type_block(number(*it,jmax), entry)); if (number(*it,jmax) == lambda_num) { r = entry; } } } } //cout << "nu" << nu << endl; //cout << block.end() << endl; } // level already exists --> extract row corresponding to 'lambda' else { //cout << "ja" << endl; Block& block(it->second); //typename Block::iterator block_lb(block.lower_bound(lambda)); typename Block::iterator block_lb(block.lower_bound(lambda_num)); typename Block::iterator block_it(block_lb); // level exists, but in row 'lambda' no entry is available ==> entry must be zero if (block_lb == block.end() || block.key_comp()(lambda_num, block_lb->first)) { r = 0; } else { r = block_it->second; } } return r; }
Block Sqlite3Statement::getBlock(int column) { return Block(reinterpret_cast<const uint8_t*>(sqlite3_column_blob(m_stmt, column)), sqlite3_column_bytes(m_stmt, column)); }
Script::Script(File const &file) : d(new Instance) { d->path = file.path(); Parser().parse(String::fromUtf8(Block(file)), *this); }
u32 BlockAllocator::AllocAligned(u32 &size, u32 grain, bool fromTop, const char *tag) { // Sanity check if (size == 0 || size > rangeSize_) { ERROR_LOG(HLE, "Clearly bogus size: %08x - failing allocation", size); return -1; } // It could be off step, but the grain should generally be a power of 2. if (grain < grain_) grain = grain_; // upalign size to grain size = (size + grain - 1) & ~(grain - 1); if (!fromTop) { //Allocate from bottom of mem for (std::list<Block>::iterator iter = blocks.begin(); iter != blocks.end(); iter++) { BlockAllocator::Block &b = *iter; u32 offset = b.start % grain; u32 needed = offset + size; if (b.taken == false && b.size >= needed) { if (b.size == needed) { b.taken = true; b.SetTag(tag); return b.start + offset; } else { blocks.insert(++iter, Block(b.start + needed, b.size - needed, false)); b.taken = true; b.size = needed; b.SetTag(tag); return b.start + offset; } } } } else { // Allocate from top of mem. for (std::list<Block>::reverse_iterator iter = blocks.rbegin(); iter != blocks.rend(); ++iter) { std::list<Block>::reverse_iterator hey = iter; BlockAllocator::Block &b = *((++hey).base()); //yes, confusing syntax. reverse_iterators are confusing u32 offset = b.start % grain; u32 needed = offset + size; if (b.taken == false && b.size >= needed) { if (b.size == needed) { b.taken = true; b.SetTag(tag); return b.start + offset; } else { blocks.insert(hey.base(), Block(b.start, b.size - needed, false)); b.taken = true; b.start += b.size - needed; b.size = needed; b.SetTag(tag); return b.start + offset; } } } } //Out of memory :( ListBlocks(); ERROR_LOG(HLE, "Block Allocator failed to allocate %i (%08x) bytes of contiguous memory", size, size); return -1; }