void PanelModeButton::Render(int realX, int realY, bool highlighted, bool clicked) { #ifndef NON_PLAYABLE SidePanel *parent = (SidePanel *)m_parent; if( m_imageButton ) { Team *team = g_app->GetWorld()->GetTeam(g_app->GetWorld()->m_myTeamId); if( !team ) return; Image *bmpImage = g_resource->GetImage( bmpImageFilename ); g_renderer->SetBlendMode( Renderer::BlendModeSubtractive ); Colour col(30,30,30,0); for( int x = -1; x <= 1; ++x ) { for( int y = -1; y <= 1; ++y ) { g_renderer->Blit( bmpImage, realX+x, realY+y, m_w, m_h, col ); } } g_renderer->SetBlendMode( Renderer::BlendModeAdditive ); Colour colour = team->GetTeamColour(); if( highlighted ) { colour.m_b += 40; colour.m_g += 40; colour.m_r += 40; } if( clicked ) { colour.m_b += 80; colour.m_g += 80; colour.m_r += 80; } colour.m_a = 255; if( m_disabled ) { colour = Colour(50, 50, 50, 255); } float size = 32.0f; if( bmpImage ) { g_renderer->Blit( bmpImage, realX, realY, m_w, m_h, colour ); g_renderer->SetBlendMode( Renderer::BlendModeNormal ); } Colour textCol = White; if( m_disabled ) { textCol = Colour(50,50,50,255); } if( m_captionIsLanguagePhrase ) { g_renderer->TextCentreSimple( realX + m_w/2, realY+m_h, textCol, parent->m_fontsize, LANGUAGEPHRASE(m_caption) ); } else { g_renderer->TextCentreSimple( realX + m_w/2, realY+m_h, textCol, parent->m_fontsize, m_caption ); } } else { InterfaceButton::Render( realX, realY, highlighted, clicked ); } #endif }
void CsrMatrixGpu::createStructure(const Triangle1* const elements, const size_t num_elem) { const size_t max_rowlength(20); size_t* num_nonzeros = new size_t[_numrows]; for (size_t i(0); i < _numrows; ++i) num_nonzeros[i] = 0; size_t* colind = new size_t[max_rowlength*_numrows]; for (size_t i(0); i < num_elem; ++i) { size_t nodes[3]; nodes[0] = elements[i].nodeA; nodes[1] = elements[i].nodeB; nodes[2] = elements[i].nodeC; for (size_t node1(0); node1 < 3; ++node1) { for (size_t node2(0); node2 < 3; ++node2) { size_t a(nodes[node1]); size_t b(nodes[node2]); size_t j(0); while (j < num_nonzeros[a] && colind[a*max_rowlength + j] != b) ++j; if (num_nonzeros[a] == j) { ++(num_nonzeros[a]); assert(num_nonzeros[a] <= max_rowlength); colind[a*max_rowlength + j] = b; } } } } for (size_t i(0); i < _numrows; ++i) for (size_t a(num_nonzeros[i]-1); a > 0; --a) for (size_t b(0); b < a; ++b) if (colind[i*max_rowlength + b] > colind[i*max_rowlength + b+1]) { size_t tmp(colind[i*max_rowlength + b]); colind[i*max_rowlength + b] = colind[i*max_rowlength + b+1]; colind[i*max_rowlength + b+1] = tmp; } size_t* h_rowptr = new size_t[_numrows+1]; size_t num_values(0); for (size_t i(0); i < _numrows; ++i) { h_rowptr[i] = num_values; num_values += num_nonzeros[i]; } h_rowptr[_numrows] = num_values; free_cuda(_colind); malloc_cuda(&_colind, num_values*sizeof(size_t)); size_t* h_colind = new size_t[num_values]; size_t current_pos(0); for (size_t row(0); row < _numrows; ++row) for (size_t col(0); col < num_nonzeros[row]; ++col) h_colind[current_pos++] = colind[row*max_rowlength + col]; free_cuda(_values); malloc_cuda(&_values, num_values*sizeof(float)); float* h_values = new float[num_values]; for (size_t i(0); i < num_values; ++i) h_values[i] = 0.0; memcpy_cuda(_colind, h_colind, num_values*sizeof(size_t), h2d); memcpy_cuda(_rowptr, h_rowptr, (_numrows+1)*sizeof(size_t), h2d); memcpy_cuda(_values, h_values, num_values*sizeof(float), h2d); delete[] num_nonzeros; delete[] colind; delete[] h_rowptr; delete[] h_colind; delete[] h_values; //cudaDeviceSynchronize(); // needed? }
void CaculateNorm::run() { const IndexType k = 36; //36; int size = SampleSet::get_instance().size(); for ( int ii = 0 ; ii<size; ++ii){ Sample& smp = SampleSet::get_instance()[ii]; std::cout<< "caculate:"<< ii<<std::endl; if( !smp.num_triangles()) //only have points { for ( IndexType i=0; i < smp.num_vertices(); i++ ) { MatrixX3 k_nearest_verts(k, 3); IndexType neighbours[k]; ScalarType dist[k]; smp.neighbours( i, k, neighbours, dist ); for ( IndexType j=0; j<k; j++ ) { IndexType neighbour_idx = neighbours[j]; k_nearest_verts.row(j) << smp[neighbour_idx].x(), smp[neighbour_idx].y(), smp[neighbour_idx].z(); } MatrixX3 vert_mean = k_nearest_verts.colwise().mean(); MatrixX3 Q(k, 3); for ( IndexType j=0; j<k;j++) { Q.row(j) = k_nearest_verts.row(j) - vert_mean; } Matrix33 sigma = Q.transpose() * Q; Eigen::EigenSolver<Matrix33> eigen_solver(sigma, Eigen::ComputeFullU | Eigen::ComputeFullV); auto ev = eigen_solver.eigenvectors(); auto eval = eigen_solver.eigenvalues(); ScalarType tmp[3] = { eval(0).real(),eval(1).real(),eval(2).real() }; IndexType min_idx = std::min_element(tmp,tmp+3) - tmp; NormalType nv; nv(0) = (ev.col(min_idx))(0).real(); nv(1) = (ev.col(min_idx))(1).real(); nv(2) = (ev.col(min_idx))(2).real(); nv.normalize(); if ( (baseline_).dot(nv) < 0 ) { nv = - nv; } smp[i].set_normal( nv ); } }else { //has face //auto& m_triangles = smp.triangle_array; for ( IndexType i=0; i < smp.num_triangles(); ++i ) { IndexType i_vetex1 = smp.getTriangle(i).get_i_vertex(0); IndexType i_vetex2 = smp.getTriangle(i).get_i_vertex(1); IndexType i_vetex3 = smp.getTriangle(i).get_i_vertex(2); PointType vtx1(smp[i_vetex1].x(),smp[i_vetex1].y(),smp[i_vetex1].z()); PointType vtx2(smp[i_vetex2].x(),smp[i_vetex2].y(),smp[i_vetex2].z()); PointType vtx3(smp[i_vetex3].x(),smp[i_vetex3].y(),smp[i_vetex3].z()); PointType vector1 = vtx2 - vtx1; PointType vector2 = vtx3 - vtx1; vector1.normalize(); vector2.normalize(); PointType vector3 = vector1.cross(vector2); //get the normal of the triangle vector3.normalize(); //Logger<<"vector1: "<<vector1(0)<<" "<<vector1(1)<<" "<<vector1(2)<<std::endl; //Logger<<"vector2: "<<vector2(0)<<" "<<vector2(1)<<" "<<vector2(2)<<std::endl; //Logger<<"vector3: "<<vector3(0)<<" "<<vector3(1)<<" "<<vector3(2)<<std::endl; //assign the normal to all the vertex of the triangle for(int x = 0 ; x<3;++x) { IndexType i_normal = smp.getTriangle(i).get_i_normal(x); //Logger<<"norm: "<<smp[i_normal].nx()<<" "<<smp[i_normal].ny()<<" "<<smp[i_normal].nz()<<std::endl; smp[i_normal].set_normal( NormalType( smp[i_normal].nx() + vector3(0),smp[i_normal].ny() +vector3(1),smp[i_normal].nz()+vector3(2) )); } } for ( IndexType i=0; i < smp.num_vertices(); i++ ) { NormalType norm(smp[i].nx(),smp[i].ny(),smp[i].nz()); norm.normalize(); // Logger<<"norm: "<<norm(0)<<" "<<norm(1)<<" "<<norm(2)<<std::endl; smp[i].set_normal(norm); } } } }
/*! \brief Get the colums name (also the positional name) * */ std::string get_csv_colums() { std::stringstream str; // write positional columns for (size_t i = 0 ; i < v_pos::value_type::dims ; i++) { if (i == 0) str << "x[" << i << "]"; else str << "," << "x[" << i << "]"; } // write positional information csv_col<typename v_prp::value_type,has_attributes<typename v_prp::value_type>::value> col(str); // Iterate through all the vertex and create the vertex list boost::mpl::for_each< boost::mpl::range_c<int,0,v_prp::value_type::max_prop> >(col); str << "\n"; return str.str(); }
bool AsciiProcessor::ins_grid( const char * buf, int fref, BuilderBase * build, const char * & next ) { int id = 0, lay = 0, fil = 0; RGBcolor col( 0, 0, 0 ); if ( ! get_obj_attr( buf, id, lay, col, fil, next ) ) { return CMD_ERR; } int idx = 0; while ( true ) //accept more then one grid! { double p_x, p_y, v1_x, v1_y, v2_x, v2_y, d3, d4, d5; int num_v1 = 1, num_v2 = 1; if ( ! strskip( next, '(', next ) ) { return CMD_ERR; } if ( get_max5_tuple( next, 2, p_x, p_y, d3, d4, d5, next ) != 2 ) { return CMD_ERR; } if ( get_max5_tuple( next, 2, v1_x, v1_y, d3, d4, d5, next ) != 2 ) { return CMD_ERR; } if ( strskip( next, ':', next ) ) { if ( ! str2val( next, num_v1, next ) ) { return CMD_ERR; } } if ( get_max5_tuple( next, 2, v2_x, v2_y, d3, d4, d5, next ) != 2 ) { return CMD_ERR; } if ( strskip( next, ':', next ) ) { if ( ! str2val( next, num_v2, next ) ) { return CMD_ERR; } } if ( ! strskip( next, ')', next ) ) { return CMD_ERR; } lines.set_cur_size( idx ); lines.set_max_size_and_preserve_cur_size( idx + num_v1 + num_v2 + 2 ); const double d1 = 1.0 / double( num_v1 ); const double d2 = 1.0 / double( num_v2 ); for ( int i = 0; i < num_v2 + 1; ++i ) { Line2d & l = lines.tab[idx]; l.p1.x = p_x + i * v2_x * d2 ; l.p1.y = p_y + i * v2_y * d2 ; l.p2.x = l.p1.x + v1_x; l.p2.y = l.p1.y + v1_y; idx++; } for ( int i = 0; i < num_v1 + 1; ++i ) { Line2d & l = lines.tab[idx]; l.p1.x = p_x + i * v1_x * d1 ; l.p1.y = p_y + i * v1_y * d1 ; l.p2.x = l.p1.x + v2_x; l.p2.y = l.p1.y + v2_y; idx++; } if ( strskip( next, DELIMITER_CHAR, next ) ) { break; } } build->set_cmd_insert_lines( fref, id, idx, lines.tab, lay, col ); return CMD_OK; }
virtual void OnSetConstants(video::IMaterialRendererServices* services, s32 userData) { IVideoDriver* drv=device->getVideoDriver(); // set inverted world matrix(设置世界的逆矩) // if we are using highlevel shaders (the user can select this when(如果我们要用高级着色渲染,我们必须设置constants的名字) // starting the program), we must set the constants by name. //得到世界矩阵 core::matrix4 invWorld = drv->getTransform(video::ETS_WORLD); invWorld.makeInverse();//逆矩 services->setVertexShaderConstant("mInvWorld", invWorld.pointer(), 16); // set clip matrix 设置剪裁矩阵 core::matrix4 worldViewProj; worldViewProj = drv->getTransform(video::ETS_PROJECTION); worldViewProj *= drv->getTransform(video::ETS_VIEW); worldViewProj *= drv->getTransform(video::ETS_WORLD); services->setVertexShaderConstant("mWorldViewProj", worldViewProj.pointer(), 16); // set camera position core::vector3df pos = device->getSceneManager()->getActiveCamera()->getAbsolutePosition(); services->setVertexShaderConstant("mLightPos", reinterpret_cast<f32*>(&pos), 3); // set light color num=RandNum2(0.1f,0.90f,0.0025); video::SColorf col(1-num,1-num,num,0.0f); // num=RandNum2(0.1f,2.0f,0.0025); // video::SColorf col(num,1.0f-num,num,0.0f); //if(num>1.0f){ // col=SColorf(2-num,2.0f-num,num-1,0.0f); //}else{ // col=SColorf(num,1.0f-num,num,0.0f); //} //video::SColorf col(1,1,1,0.0f); //printf("%3.1f ",num); services->setVertexShaderConstant("mLightColor", reinterpret_cast<f32*>(&col), 4); //透明度 mAlpha=0.90f; /*if(mAlpha>=1.0f) mAlpha=0.1f; printf("mAlpha:%3.1f \n",mAlpha);*/ services->setVertexShaderConstant("mAlpha", reinterpret_cast<f32*>(&mAlpha), 1); // set transposed world matrix core::matrix4 world = drv->getTransform(video::ETS_WORLD); world = world.getTransposed(); services->setVertexShaderConstant("mTransWorld", world.pointer(), 16); }
/*! Initializes the main menu state * * @param pContentLoader Pointer to the content loader * @returns ICRESULT Success/failure of initialization **/ ICRESULT SettingsMenu::Init(icContentLoader* pContentLoader) { if (!pContentLoader) return IC_FAIL_GEN; m_pContent = pContentLoader; icTexture *tex1 = NULL; icTexture *tex2 = NULL; icTexture* bone_theme = NULL; icSoundParam param; param.bLoop = false; param.fPitch = 1.0f; param.fVol = gApp.GetSettings().fSfx_vol; // load the textures if (ICEFAIL(m_pContent->Load("Resource/textures/UI_settings_menu.tga", &tex1))) return IC_FAIL_GEN; if (ICEFAIL(m_pContent->Load("Resource/textures/UI_settings_menu_sel.tga", &tex2))) return IC_FAIL_GEN; if (ICEFAIL(m_pContent->Load("Resource/textures/UI_bone_theme.tga", &bone_theme))) return IC_FAIL_GEN; // load the sounds if (ICEFAIL(m_pContent->Load("Resource/audio/whip_01.wav", &m_pHover))) return IC_FAIL_GEN; if (ICEFAIL(m_pContent->Load("Resource/audio/menu_click.wav", &m_pClick))) return IC_FAIL_GEN; m_pHover->SetParams(param); m_pClick->SetParams(param); icReal sx = (icReal)gApp.GetSettings().iScreen_x; icReal sy = (icReal)gApp.GetSettings().iScreen_y; icReal rat = sy/1024.0f; icReal mx = sx/2.0f; // set up UI Frame m_uiFrame = new icFrame(m_pContent); //m_uiFrame->SetTextures(tex1,tex2); icVector2 bl(0.0f,0.733f); icVector2 tl(0.0f,1.0f); icVector2 tr(1.0f,1.0f); icVector2 br(1.0f,0.733f); //m_uiFrame->SetUVs( tl, tr, bl, br ); icVector2 size(sx,sy); icVector2 pos(mx,sy*0.5f); icColor col(0,0,0,255); m_uiFrame->SetSize(size); m_uiFrame->SetPos(pos); m_uiFrame->SetColor(col); // SFX Slider m_slidSfxVol = new icSlider(m_pContent); m_slidSfxVol->SetTextures(bone_theme,NULL); size.Set(512.0f*rat,71.0f*rat); pos.Set(mx + mx*0.35f,sy*0.409f); //col.Set(0,0,0,255); m_slidSfxVol->SetSize(size); m_slidSfxVol->SetPos(pos); m_slidSfxVol->SetColor(col); bl.Set(0.0f,0.0f); tl.Set(0.0f,0.138f); tr.Set(1.0f,0.138f); br.Set(1.0f,0.0f); m_slidSfxVol->SetUVs(tl,tr,bl,br); m_slidSfxVol->SetHighUVs(tl,tr,bl,br); m_slidSfxVol->EnableHighlight(false); m_slidSfxVol->SetMinMax(0,1000); bl.Set(0.916f,0.156f); tl.Set(0.916f,0.402f); tr.Set(1.0f,0.402f); br.Set(1.0f,0.156f); m_slidSfxVol->SetTickUVs(tl,tr,bl,br); m_slidSfxVol->SetTickHighUVs(tl,tr,bl,br); m_slidSfxVol->SetVal((int)(gApp.GetSettings().fSfx_vol*1000.0f)); size.Set(44.0f*rat,132.0f*rat); m_slidSfxVol->SetTickSize(size); m_uiFrame->AddChild(m_slidSfxVol); // Music Slider m_slidMusicVol = new icSlider(m_pContent); m_slidMusicVol->SetTextures(bone_theme,NULL); size.Set(512.0f*rat,71.0f*rat); pos.Set(mx + mx*0.35f,sy*0.259f); //col.Set(0,0,0,255); m_slidMusicVol->SetSize(size); m_slidMusicVol->SetPos(pos); m_slidMusicVol->SetColor(col); bl.Set(0.0f,0.0f); tl.Set(0.0f,0.138f); tr.Set(1.0f,0.138f); br.Set(1.0f,0.0f); m_slidMusicVol->SetUVs(tl,tr,bl,br); m_slidMusicVol->SetHighUVs(tl,tr,bl,br); m_slidMusicVol->EnableHighlight(false); m_slidMusicVol->SetMinMax(0,1000); bl.Set(0.916f,0.156f); tl.Set(0.916f,0.402f); tr.Set(1.0f,0.402f); br.Set(1.0f,0.156f); m_slidMusicVol->SetTickUVs(tl,tr,bl,br); m_slidMusicVol->SetTickHighUVs(tl,tr,bl,br); m_slidMusicVol->SetVal((int)(gApp.GetSettings().fMusic_vol*1000.0f)); size.Set(44.0f*rat,132.0f*rat); m_slidMusicVol->SetTickSize(size); m_uiFrame->AddChild(m_slidMusicVol); // Settings widget m_ptxtSettings = new icWidget(m_pContent); m_ptxtSettings->SetTextures(tex1,tex2); size.Set(650.0f*rat,175.0f*rat); pos.Set(mx,sy*0.599f); //col.Set(0,0,0,255); m_ptxtSettings->SetSize(size); m_ptxtSettings->SetPos(pos); m_ptxtSettings->SetColor(col); bl.Set(0.0f,0.826f); tl.Set(0.0f,1.0f); tr.Set(1.0f,1.0f); br.Set(1.0f,0.826f); m_ptxtSettings->SetUVs(tl,tr,bl,br); m_ptxtSettings->SetHighUVs(tl,tr,bl,br); m_ptxtSettings->EnableHighlight(false); m_uiFrame->AddChild(m_ptxtSettings); // SFX Widget m_ptxtSfx = new icWidget(m_pContent); m_ptxtSfx->SetTextures(tex1,tex2); size.Set(512.0f*rat,115.0f*rat); pos.Set(mx - mx*0.15f,sy*0.409f); m_ptxtSfx->SetSize(size); m_ptxtSfx->SetPos(pos); m_ptxtSfx->SetColor(col); bl.Set(0.0f,0.627f); tl.Set(0.0f,0.826f); tr.Set(1.0f,0.826f); br.Set(1.0f,0.627f); m_ptxtSfx->SetUVs(tl,tr,bl,br); m_ptxtSfx->SetHighUVs(tl,tr,bl,br); m_ptxtSfx->EnableHighlight(false); m_uiFrame->AddChild(m_ptxtSfx); // Music Widget m_ptxtMusic = new icWidget(m_pContent); m_ptxtMusic->SetTextures(tex1,tex2); size.Set(512.0f*rat,115.0f*rat); pos.Set(mx - mx*0.21f,sy*0.259f); m_ptxtMusic->SetSize(size); m_ptxtMusic->SetPos(pos); m_ptxtMusic->SetColor(col); bl.Set(0.0f,0.420f); tl.Set(0.0f,0.627f); tr.Set(1.0f,0.627f); br.Set(1.0f,0.420f); m_ptxtMusic->SetUVs(tl,tr,bl,br); m_ptxtMusic->SetHighUVs(tl,tr,bl,br); m_ptxtMusic->EnableHighlight(false); m_uiFrame->AddChild(m_ptxtMusic); // back button m_pbtnBack = new icButton(m_pContent); m_pbtnBack->SetTextures(tex1,tex2); size.Set(512.0f*rat,115.0f*rat); pos.Set(mx,sy*0.109f); //col.Set(0,0,0,255); m_pbtnBack->SetSize(size); m_pbtnBack->SetPos(pos); m_pbtnBack->SetColor(col); bl.Set(0.0f,0.0f); tl.Set(0.0f,0.221f); tr.Set(1.0f,0.221f); br.Set(1.0f,0.0f); m_pbtnBack->SetUVs(tl,tr,bl,br); m_pbtnBack->SetHighUVs(tl,tr,bl,br); m_pbtnBack->SetSounds(m_pClick,m_pHover); m_uiFrame->AddChild(m_pbtnBack); return IC_OK; }// END FUNCTION Init(icContentLoader* pContentLoader)
void wxTabControl::OnDraw(wxDC& dc, bool lastInRow) { // Old, but in some ways better (drawing opaque tabs) #ifndef wxUSE_NEW_METHOD if (!m_view) return; // Top-left of tab view area int viewX = m_view->GetViewRect().x; int viewY = m_view->GetViewRect().y; // Top-left of tab control int tabX = GetX() + viewX; int tabY = GetY() + viewY; int tabHeightInc = 0; if (m_isSelected) { tabHeightInc = (m_view->GetTabSelectionHeight() - m_view->GetTabHeight()); tabY -= tabHeightInc; } dc.SetPen(*wxTRANSPARENT_PEN); // Draw grey background if (m_view->GetTabStyle() & wxTAB_STYLE_COLOUR_INTERIOR) { dc.SetBrush(*m_view->GetBackgroundBrush()); // Add 1 because the pen is transparent. Under Motif, may be different. #ifdef __WXMOTIF__ dc.DrawRectangle(tabX, tabY, (GetWidth()+1), (GetHeight() + tabHeightInc)); #else dc.DrawRectangle(tabX, tabY, (GetWidth()+1), (GetHeight() + 1 + tabHeightInc)); #endif } // Draw highlight and shadow dc.SetPen(*m_view->GetHighlightPen()); // Calculate the top of the tab beneath. It's the height of the tab, MINUS // a bit if the tab below happens to be selected. Check. wxTabControl *tabBeneath = NULL; int subtractThis = 0; if (GetColPosition() > 0) tabBeneath = m_view->FindTabControlForPosition(GetColPosition() - 1, GetRowPosition()); if (tabBeneath && tabBeneath->IsSelected()) subtractThis = (m_view->GetTabSelectionHeight() - m_view->GetTabHeight()); // Vertical highlight: if first tab, draw to bottom of view if (tabX == m_view->GetViewRect().x && (m_view->GetTabStyle() & wxTAB_STYLE_DRAW_BOX)) dc.DrawLine(tabX, tabY, tabX, (m_view->GetViewRect().y + m_view->GetViewRect().height)); else if (tabX == m_view->GetViewRect().x) // Not box drawing, just to top of view. dc.DrawLine(tabX, tabY, tabX, (m_view->GetViewRect().y)); else dc.DrawLine(tabX, tabY, tabX, (tabY + GetHeight() + tabHeightInc - subtractThis)); dc.DrawLine(tabX, tabY, (tabX + GetWidth()), tabY); dc.SetPen(*m_view->GetShadowPen()); // Test if we're outside the right-hand edge of the view area if (((tabX + GetWidth()) >= m_view->GetViewRect().x + m_view->GetViewRect().width) && (m_view->GetTabStyle() & wxTAB_STYLE_DRAW_BOX)) { int bottomY = m_view->GetViewRect().y + m_view->GetViewRect().height + GetY() + m_view->GetTabHeight() + m_view->GetTopMargin(); // Add a tab height since we wish to draw to the bottom of the view. dc.DrawLine((tabX + GetWidth()), tabY, (tabX + GetWidth()), bottomY); // Calculate the far-right of the view, since we don't wish to // draw inside that int rightOfView = m_view->GetViewRect().x + m_view->GetViewRect().width + 1; // Draw the horizontal bit to connect to the view rectangle dc.DrawLine((wxMax((tabX + GetWidth() - m_view->GetHorizontalTabOffset()), rightOfView)), (bottomY-1), (tabX + GetWidth()), (bottomY-1)); // Draw black line to emphasize shadow dc.SetPen(*wxBLACK_PEN); dc.DrawLine((tabX + GetWidth() + 1), (tabY+1), (tabX + GetWidth() + 1), bottomY); // Draw the horizontal bit to connect to the view rectangle dc.DrawLine((wxMax((tabX + GetWidth() - m_view->GetHorizontalTabOffset()), rightOfView)), (bottomY), (tabX + GetWidth() + 1), (bottomY)); } else { if (lastInRow) { // 25/5/97 UNLESS it's less than the max number of positions in this row int topY = m_view->GetViewRect().y - m_view->GetTopMargin(); int maxPositions = ((wxTabLayer *)m_view->GetLayers().Item(0)->GetData())->GetCount(); // Only down to the bottom of the tab, not to the top of the view if ( GetRowPosition() < (maxPositions - 1) ) topY = tabY + GetHeight() + tabHeightInc; #ifdef __WXMOTIF__ topY -= 1; #endif // Shadow dc.DrawLine((tabX + GetWidth()), tabY, (tabX + GetWidth()), topY); // Draw black line to emphasize shadow dc.SetPen(*wxBLACK_PEN); dc.DrawLine((tabX + GetWidth() + 1), (tabY+1), (tabX + GetWidth() + 1), topY); } else { // Calculate the top of the tab beneath. It's the height of the tab, MINUS // a bit if the tab below (and next col along) happens to be selected. Check. wxTabControl *tabBeneath = NULL; int subtractThis = 0; if (GetColPosition() > 0) tabBeneath = m_view->FindTabControlForPosition(GetColPosition() - 1, GetRowPosition() + 1); if (tabBeneath && tabBeneath->IsSelected()) subtractThis = (m_view->GetTabSelectionHeight() - m_view->GetTabHeight()); #ifdef __WXMOTIF__ subtractThis += 1; #endif // Draw only to next tab down. dc.DrawLine((tabX + GetWidth()), tabY, (tabX + GetWidth()), (tabY + GetHeight() + tabHeightInc - subtractThis)); // Draw black line to emphasize shadow dc.SetPen(*wxBLACK_PEN); dc.DrawLine((tabX + GetWidth() + 1), (tabY+1), (tabX + GetWidth() + 1), (tabY + GetHeight() + tabHeightInc - subtractThis)); } } // Draw centered text int textY = tabY + m_view->GetVerticalTabTextSpacing() + tabHeightInc; if (m_isSelected) dc.SetFont(* m_view->GetSelectedTabFont()); else dc.SetFont(* GetFont()); wxColour col(m_view->GetTextColour()); dc.SetTextForeground(col); dc.SetBackgroundMode(wxTRANSPARENT); long textWidth, textHeight; dc.GetTextExtent(GetLabel(), &textWidth, &textHeight); int textX = (int)(tabX + (GetWidth() - textWidth)/2.0); if (textX < (tabX + 2)) textX = (tabX + 2); dc.SetClippingRegion(tabX, tabY, GetWidth(), GetHeight()); dc.DrawText(GetLabel(), textX, textY); dc.DestroyClippingRegion(); if (m_isSelected) { dc.SetPen(*m_view->GetHighlightPen()); // Draw white highlight from the tab's left side to the left hand edge of the view dc.DrawLine(m_view->GetViewRect().x, (tabY + GetHeight() + tabHeightInc), tabX, (tabY + GetHeight() + tabHeightInc)); // Draw white highlight from the tab's right side to the right hand edge of the view dc.DrawLine((tabX + GetWidth()), (tabY + GetHeight() + tabHeightInc), m_view->GetViewRect().x + m_view->GetViewRect().width, (tabY + GetHeight() + tabHeightInc)); } #else // New HEL version with rounder tabs if (!m_view) return; int tabInc = 0; if (m_isSelected) { tabInc = m_view->GetTabSelectionHeight() - m_view->GetTabHeight(); } int tabLeft = GetX() + m_view->GetViewRect().x; int tabTop = GetY() + m_view->GetViewRect().y - tabInc; int tabRight = tabLeft + m_view->GetTabWidth(); int left = m_view->GetViewRect().x; int top = tabTop + m_view->GetTabHeight() + tabInc; int right = left + m_view->GetViewRect().width; int bottom = top + m_view->GetViewRect().height; if (m_isSelected) { // TAB is selected - draw TAB and the View's full outline dc.SetPen(*(m_view->GetHighlightPen())); wxPoint pnts[10]; int n = 0; pnts[n].x = left; pnts[n++].y = bottom; pnts[n].x = left; pnts[n++].y = top; pnts[n].x = tabLeft; pnts[n++].y = top; pnts[n].x = tabLeft; pnts[n++].y = tabTop + 2; pnts[n].x = tabLeft + 2; pnts[n++].y = tabTop; pnts[n].x = tabRight - 1; pnts[n++].y = tabTop; dc.DrawLines(n, pnts); if (!lastInRow) { dc.DrawLine( (tabRight + 2), top, right, top ); } dc.SetPen(*(m_view->GetShadowPen())); dc.DrawLine( tabRight, tabTop + 2, tabRight, top ); dc.DrawLine( right, top, right, bottom ); dc.DrawLine( right, bottom, left, bottom ); dc.SetPen(*wxBLACK_PEN); dc.DrawPoint( tabRight, tabTop + 1 ); dc.DrawPoint( tabRight + 1, tabTop + 2 ); if (lastInRow) { dc.DrawLine( tabRight + 1, bottom, tabRight + 1, tabTop + 1 ); } else { dc.DrawLine( tabRight + 1, tabTop + 2, tabRight + 1, top ); dc.DrawLine( right + 1, top, right + 1, bottom + 1 ); } dc.DrawLine( right + 1, bottom + 1, left + 1, bottom + 1 ); } else { // TAB is not selected - just draw TAB outline and RH edge // if the TAB is the last in the row int maxPositions = ((wxTabLayer*)m_view->GetLayers().Item(0)->GetData())->GetCount(); wxTabControl* tabBelow = 0; wxTabControl* tabBelowRight = 0; if (GetColPosition() > 0) { tabBelow = m_view->FindTabControlForPosition( GetColPosition() - 1, GetRowPosition() ); } if (!lastInRow && GetColPosition() > 0) { tabBelowRight = m_view->FindTabControlForPosition( GetColPosition() - 1, GetRowPosition() + 1 ); } float raisedTop = top - m_view->GetTabSelectionHeight() + m_view->GetTabHeight(); dc.SetPen(*(m_view->GetHighlightPen())); wxPoint pnts[10]; int n = 0; pnts[n].x = tabLeft; if (tabBelow && tabBelow->IsSelected()) { pnts[n++].y = (long)raisedTop; } else { pnts[n++].y = top; } pnts[n].x = tabLeft; pnts[n++].y = tabTop + 2; pnts[n].x = tabLeft + 2; pnts[n++].y = tabTop; pnts[n].x = tabRight - 1; pnts[n++].y = tabTop; dc.DrawLines(n, pnts); dc.SetPen(*(m_view->GetShadowPen())); if (GetRowPosition() >= maxPositions - 1) { dc.DrawLine( tabRight, (tabTop + 2), tabRight, bottom ); dc.DrawLine( tabRight, bottom, (tabRight - m_view->GetHorizontalTabOffset()), bottom ); } else { if (tabBelowRight && tabBelowRight->IsSelected()) { dc.DrawLine( tabRight, (long)raisedTop, tabRight, tabTop + 1 ); } else { dc.DrawLine( tabRight, top - 1, tabRight, tabTop + 1 ); } } dc.SetPen(*wxBLACK_PEN); dc.DrawPoint( tabRight, tabTop + 1 ); dc.DrawPoint( tabRight + 1, tabTop + 2 ); if (GetRowPosition() >= maxPositions - 1) { // draw right hand edge to bottom of view dc.DrawLine( tabRight + 1, bottom + 1, tabRight + 1, tabTop + 2 ); dc.DrawLine( tabRight + 1, bottom + 1, (tabRight - m_view->GetHorizontalTabOffset()), bottom + 1 ); } else { // draw right hand edge of TAB if (tabBelowRight && tabBelowRight->IsSelected()) { dc.DrawLine( tabRight + 1, (long)(raisedTop - 1), tabRight + 1, tabTop + 2 ); } else { dc.DrawLine( tabRight + 1, top - 1, tabRight + 1, tabTop + 2 ); } } } // Draw centered text dc.SetPen(*wxBLACK_PEN); if (m_isSelected) { dc.SetFont(*(m_view->GetSelectedTabFont())); } else { dc.SetFont(*(GetFont())); } wxColour col(m_view->GetTextColour()); dc.SetTextForeground(col); dc.SetBackgroundMode(wxTRANSPARENT); long textWidth, textHeight; dc.GetTextExtent(GetLabel(), &textWidth, &textHeight); float textX = (tabLeft + tabRight - textWidth) / 2; float textY = (tabInc + tabTop + m_view->GetVerticalTabTextSpacing()); dc.DrawText(GetLabel(), (long)textX, (long)textY); #endif }
CC_FILE_ERROR MAFilter::saveToFile(ccHObject* entity, QString filename, SaveParameters& parameters) { if (!entity || filename.isEmpty()) return CC_FERR_BAD_ARGUMENT; //the mesh to save ccGenericMesh* theMesh = ccHObjectCaster::ToGenericMesh(entity); if (!theMesh) { ccLog::Error("[MA] This filter can only save one mesh at a time!"); return CC_FERR_BAD_ENTITY_TYPE; } //and its vertices ccGenericPointCloud* theCloud = theMesh->getAssociatedCloud(); unsigned numberOfTriangles = theMesh->size(); unsigned numberOfVertexes = theCloud->size(); if (numberOfTriangles == 0 || numberOfVertexes == 0) { ccLog::Error("Mesh is empty!"); return CC_FERR_BAD_ENTITY_TYPE; } bool hasColors = false; if (theCloud->isA(CC_TYPES::POINT_CLOUD)) static_cast<ccPointCloud*>(theCloud)->hasColors(); //and its scalar field //ccScalarField* sf = 0; //if (theCloud->isA(CC_TYPES::POINT_CLOUD)) // sf = static_cast<ccPointCloud*>(theCloud)->getCurrentDisplayedScalarField(); //if (!sf) // ccLog::Warning("No displayed scalar field! Values will all be 0!\n"); //open ASCII file for writing FILE* fp = fopen(qPrintable(filename) , "wt"); if (!fp) return CC_FERR_WRITING; //progress dialog ccProgressDialog pdlg(true, parameters.parentWidget); //cancel available const int coloursAdjustment = (hasColors ? 1 : 0); CCLib::NormalizedProgress nprogress(&pdlg, ((2 + coloursAdjustment) * numberOfTriangles + (3 + coloursAdjustment) * numberOfVertexes)); pdlg.setMethodTitle(QObject::tr("Save MA file")); pdlg.setInfo(QObject::tr("Triangles = %1").arg(numberOfTriangles)); pdlg.start(); //we extract the (short) filename from the whole path QString baseFilename = QFileInfo(filename).fileName(); //header if (fprintf(fp,"//Maya ASCII 7.0 scene\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"//Name: %s\n",qPrintable(baseFilename)) < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"//Last modified: Sat, Mai 10, 2008 00:00:00 PM\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"requires maya \"4.0\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"currentUnit -l %s -a degree -t film;\n","centimeter") < 0) {fclose(fp);return CC_FERR_WRITING;} //for multiple meshes handling (does not work yet) unsigned char currentMesh = 0; //transformation node if (fprintf(fp,"createNode transform -n \"Mesh%i\";\n",currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} //main node if (fprintf(fp,"createNode mesh -n \"MeshShape%i\" -p \"Mesh%i\";\n",currentMesh+1,currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr -k off \".v\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".uvst[0].uvsn\" -type \"string\" \"map1\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".cuvs\" -type \"string\" \"map1\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (hasColors) { if (fprintf(fp,"\tsetAttr \".dcol\" yes;\n") < 0) {fclose(fp);return CC_FERR_WRITING;} } if (fprintf(fp,"\tsetAttr \".dcc\" -type \"string\" \"Ambient+Diffuse\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".ccls\" -type \"string\" \"colorSet%i\";\n",currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".clst[0].clsn\" -type \"string\" \"colorSet%i\";\n",currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} if (hasColors) { if (fprintf(fp,"\tsetAttr \".ndt\" 0;\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".tgsp\" 1;\n") < 0) {fclose(fp);return CC_FERR_WRITING;} //insert a secondary nodes if (fprintf(fp,"createNode mesh -n \"polySurfaceShape%i\" -p \"Mesh%i\";\n",currentMesh+1,currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr -k off \".v\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".io\" yes;\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".uvst[0].uvsn\" -type \"string\" \"map1\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".cuvs\" -type \"string\" \"map1\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".dcol\" yes;\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".dcc\" -type \"string\" \"Ambient+Diffuse\";\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".ccls\" -type \"string\" \"colorSet%i\";\n",currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".clst[0].clsn\" -type \"string\" \"colorSet%i\";\n",currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} } //save vertexes if (fprintf(fp,"\tsetAttr -s %u \".vt[0:%u]\"\n",numberOfVertexes,numberOfVertexes-1) < 0) { fclose(fp); return CC_FERR_WRITING; } { for (unsigned i=0; i<numberOfVertexes; ++i) { const CCVector3* P = theCloud->getPoint(i); CCVector3d Pglobal = theCloud->toGlobal3d<PointCoordinateType>(*P); if (fprintf(fp,(i+1==numberOfVertexes ? "\t\t%f %f %f;\n" : "\t\t%f %f %f\n"), Pglobal.x, Pglobal.y, Pglobal.z) < 0) { fclose(fp); return CC_FERR_WRITING; } nprogress.oneStep(); } } //save "edges" edge** theEdges = new edge*[numberOfVertexes]; memset(theEdges,0,sizeof(edge*)*numberOfVertexes); unsigned ind[3],a,b; int lastEdgeIndexPushed = -1; int hard = 0; //Maya edges cab be "hard" or "soft" ... { theMesh->placeIteratorAtBegining(); for (unsigned i=0; i<numberOfTriangles; ++i) { const CCLib::VerticesIndexes* tsi = theMesh->getNextTriangleVertIndexes(); //DGM: getNextTriangleVertIndexes is faster for mesh groups! ind[0] = tsi->i1; ind[1] = tsi->i2; ind[2] = tsi->i3; for (unsigned char k=0; k<3; ++k) { unsigned char l = (k<2 ? k+1 : 0); a = (ind[k]<ind[l] ? ind[k] : ind[l]); b = (a==ind[k] ? ind[l] : ind[k]); int currentEdgeIndex = -1; edge* e = theEdges[a]; while (e) { if (e->theOtherPoint == b) { currentEdgeIndex = e->edgeIndex; break; } e = e->nextEdge; } if (currentEdgeIndex < 0) //create a new edge { edge* newEdge = new edge; newEdge->nextEdge = NULL; newEdge->theOtherPoint = b; newEdge->positif = (a==ind[k]); //newEdge->edgeIndex = ++lastEdgeIndexPushed; //don't write the edge right now newEdge->edgeIndex = 0; ++lastEdgeIndexPushed; //currentEdgeIndex = lastEdgeIndexPushed; //don't forget the node! if (theEdges[a]) { e = theEdges[a]; while (e->nextEdge) e = e->nextEdge; e->nextEdge = newEdge; } else { theEdges[a] = newEdge; } /*if (fprintf(fp,"\n \t\t%i %i %i",a,b,hard) < 0) return CC_FERR_WRITING;*/ } } nprogress.oneStep(); } } //now write the edges { unsigned numberOfEdges = static_cast<unsigned>(lastEdgeIndexPushed+1); if (fprintf(fp,"\tsetAttr -s %u \".ed[0:%u]\"",numberOfEdges,numberOfEdges-1) < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } lastEdgeIndexPushed = 0; for (unsigned i=0; i<numberOfVertexes; ++i) { edge* e = theEdges[i]; while (e) { e->edgeIndex = lastEdgeIndexPushed++; if (fprintf(fp,"\n \t\t%u %u %i",i,e->theOtherPoint,hard) < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } e = e->nextEdge; } nprogress.oneStep(); } } if (fprintf(fp,";\n") < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } //write faces if (fprintf(fp,"\tsetAttr -s %u \".fc[0:%u]\" -type \"polyFaces\"\n",numberOfTriangles,numberOfTriangles-1) < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } theMesh->placeIteratorAtBegining(); { for (unsigned i=0; i<numberOfTriangles; ++i) { if (fprintf(fp,"\t\tf 3") < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } CCLib::VerticesIndexes* tsi = theMesh->getNextTriangleVertIndexes(); //DGM: getNextTriangleVertIndexes is faster for mesh groups! ind[0] = tsi->i1; ind[1] = tsi->i2; ind[2] = tsi->i3; for (unsigned char k=0; k<3; ++k) { unsigned char l = (k<2 ? k+1 : 0); a = (ind[k]<ind[l] ? ind[k] : ind[l]); b = (a==ind[k] ? ind[l] : ind[k]); edge* e = theEdges[a]; while (e->theOtherPoint != b) e = e->nextEdge; if (fprintf(fp," %i",((e->positif && a==ind[k]) || (!e->positif && a==ind[l]) ? e->edgeIndex : -(e->edgeIndex+1))) < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } } if (fprintf(fp,(i+1==numberOfTriangles ? ";\n" : "\n")) < 0) { fclose(fp); ReleaseEdgeList(theEdges, numberOfVertexes); return CC_FERR_WRITING; } nprogress.oneStep(); } } //free memory { ReleaseEdgeList(theEdges, numberOfVertexes, &nprogress); } //bonus track if ( fprintf(fp,"\tsetAttr \".cd\" -type \"dataPolyComponent\" Index_Data Edge 0 ;\n") < 0 || fprintf(fp,"\tsetAttr \".ndt\" 0;\n") < 0 || fprintf(fp,"\tsetAttr \".tgsp\" 1;\n") < 0 ) { fclose(fp); return CC_FERR_WRITING; } //vertex colors if (hasColors) { assert(theCloud->isA(CC_TYPES::POINT_CLOUD)); ccPointCloud* pc = static_cast<ccPointCloud*>(theCloud); if (fprintf(fp,"createNode polyColorPerVertex -n \"polyColorPerVertex%i\";\n",currentMesh+1) < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr \".uopa\" yes;\n") < 0) {fclose(fp);return CC_FERR_WRITING;} if (fprintf(fp,"\tsetAttr -s %u \".vclr\";\n",numberOfVertexes) < 0) {fclose(fp);return CC_FERR_WRITING;} //association of each vertex with the faces it belongs to faceIndexes** theFacesIndexes = new faceIndexes*[numberOfVertexes]; memset(theFacesIndexes,0,sizeof(faceIndexes*)*numberOfVertexes); theMesh->placeIteratorAtBegining(); { for (unsigned i=0; i<numberOfTriangles; ++i) { CCLib::VerticesIndexes* tsi = theMesh->getNextTriangleVertIndexes(); //DGM: getNextTriangleVertIndexes is faster for mesh groups! ind[0] = tsi->i1; ind[1] = tsi->i2; ind[2] = tsi->i3; for (unsigned char j=0; j<3; ++j) { if (!theFacesIndexes[ind[j]]) { faceIndexes* f = new faceIndexes; f->faceIndex = i; f->nextFace = NULL; theFacesIndexes[ind[j]] = f; } else { faceIndexes* f = theFacesIndexes[ind[j]]; while (f->nextFace) f = f->nextFace; f->nextFace = new faceIndexes; f->nextFace->faceIndex = i; f->nextFace->nextFace = NULL; } } nprogress.oneStep(); } } //for each vertex { for (unsigned i=0; i<numberOfVertexes; ++i) { const ColorCompType* c = pc->getPointColor(i); ccColor::Rgbf col( static_cast<float>(c[0])/ccColor::MAX, static_cast<float>(c[1])/ccColor::MAX, static_cast<float>(c[2])/ccColor::MAX); //on compte le nombre de faces int nf = 0; faceIndexes* f = theFacesIndexes[i]; while (f) { ++nf; f = f->nextFace; } if (nf > 0) { if (fprintf(fp,"\tsetAttr -s %i \".vclr[%u].vfcl\";\n",nf,i) < 0) { fclose(fp); delete[] theFacesIndexes; //DGM: we are missing soem faces here, aren't we? return CC_FERR_WRITING; } faceIndexes* f = theFacesIndexes[i]; while (f) { if (fprintf(fp,"\tsetAttr \".vclr[%u].vfcl[%i].frgb\" -type \"float3\" %f %f %f;\n",i,f->faceIndex,col.r,col.g,col.b) < 0) { fclose(fp); delete[] theFacesIndexes; //DGM: we are missing soem faces here, aren't we? return CC_FERR_WRITING; } faceIndexes* oldf = f; f = f->nextFace; delete oldf; } theFacesIndexes[i] = NULL; } nprogress.oneStep(); } } delete[] theFacesIndexes; theFacesIndexes = 0; if (fprintf(fp,"\tsetAttr \".cn\" -type \"string\" \"colorSet%i\";\n",currentMesh+1) < 0) { fclose(fp); return CC_FERR_WRITING; } } //Maya connections if (hasColors) { if ( fprintf(fp,"connectAttr \"polyColorPerVertex%i.out\" \"MeshShape%i.i\";\n",currentMesh+1,currentMesh+1) < 0 || fprintf(fp,"connectAttr \"polySurfaceShape%i.o\" \"polyColorPerVertex%i.ip\";\n",currentMesh+1,currentMesh+1) < 0 ) { fclose(fp); return CC_FERR_WRITING; } } if (fprintf(fp,"connectAttr \"MeshShape%i.iog\" \":initialShadingGroup.dsm\" -na;\n",currentMesh+1) < 0) { fclose(fp); return CC_FERR_WRITING; } //end of file if (fprintf(fp,"//End of %s\n",qPrintable(baseFilename)) < 0) { fclose(fp); return CC_FERR_WRITING; } fclose(fp); return CC_FERR_NO_ERROR; }
QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* parent ) : QWidget( parent ) { mLayer = layer; if ( !layer ) { return; } setupUi( this ); mBackgroundColorButton->setColorDialogTitle( tr( "Background color" ) ); mBackgroundColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel ); mDiagramPenColorButton->setColorDialogTitle( tr( "Pen color" ) ); mDiagramPenColorButton->setColorDialogOptions( QColorDialog::ShowAlphaChannel ); mValueLineEdit->setValidator( new QDoubleValidator( mValueLineEdit ) ); mMinimumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMinimumDiagramScaleLineEdit ) ); mMaximumDiagramScaleLineEdit->setValidator( new QDoubleValidator( mMaximumDiagramScaleLineEdit ) ); mDiagramUnitComboBox->insertItem( 0, tr( "mm" ), QgsDiagramSettings::MM ); mDiagramUnitComboBox->insertItem( 1, tr( "Map units" ), QgsDiagramSettings::MapUnits ); QGis::GeometryType layerType = layer->geometryType(); if ( layerType == QGis::UnknownGeometry || layerType == QGis::NoGeometry ) { mDisplayDiagramsGroupBox->setChecked( false ); mDisplayDiagramsGroupBox->setEnabled( false ); } //insert placement options if ( layerType == QGis::Point || layerType == QGis::Polygon ) { mPlacementComboBox->addItem( tr( "Around Point" ), QgsDiagramLayerSettings::AroundPoint ); mPlacementComboBox->addItem( tr( "Over Point" ), QgsDiagramLayerSettings::OverPoint ); } if ( layerType == QGis::Line || layerType == QGis::Polygon ) { mPlacementComboBox->addItem( tr( "Line" ), QgsDiagramLayerSettings::Line ); mPlacementComboBox->addItem( tr( "Horizontal" ), QgsDiagramLayerSettings::Horizontal ); } if ( layerType == QGis::Polygon ) { mPlacementComboBox->addItem( tr( "Free" ), QgsDiagramLayerSettings::Free ); } if ( layerType == QGis::Line ) { mLineOptionsComboBox->addItem( tr( "On line" ), QgsDiagramLayerSettings::OnLine ); mLineOptionsComboBox->addItem( tr( "Above line" ), QgsDiagramLayerSettings::AboveLine ); mLineOptionsComboBox->addItem( tr( "Below Line" ), QgsDiagramLayerSettings::BelowLine ); mLineOptionsComboBox->addItem( tr( "Map orientation" ), QgsDiagramLayerSettings::MapOrientation ); } else { mLineOptionsComboBox->setVisible( false ); mLineOptionsLabel->setVisible( false ); } QPixmap pix = QgsApplication::getThemePixmap( "pie-chart" ); mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE ); pix = QgsApplication::getThemePixmap( "text" ); mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT ); pix = QgsApplication::getThemePixmap( "histogram" ); mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM ); mLabelPlacementComboBox->addItem( tr( "Height" ), QgsDiagramSettings::Height ); mLabelPlacementComboBox->addItem( tr( "x-height" ), QgsDiagramSettings::XHeight ); mScaleDependencyComboBox->addItem( tr( "Area" ), true ); mScaleDependencyComboBox->addItem( tr( "Diameter" ), false ); mDataDefinedXComboBox->addItem( tr( "None" ), -1 ); mDataDefinedYComboBox->addItem( tr( "None" ), -1 ); //insert all attributes into the combo boxes const QgsFields& layerFields = layer->pendingFields(); for ( int idx = 0; idx < layerFields.count(); ++idx ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget ); newItem->setText( 0, layerFields[idx].name() ); newItem->setData( 0, Qt::UserRole, idx ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); if ( layerFields[idx].type() != QVariant::String ) { mSizeAttributeComboBox->addItem( layerFields[idx].name(), idx ); } mDataDefinedXComboBox->addItem( layerFields[idx].name(), idx ); mDataDefinedYComboBox->addItem( layerFields[idx].name(), idx ); } const QgsDiagramRendererV2* dr = layer->diagramRenderer(); if ( !dr ) //no diagram renderer yet, insert reasonable default { mDisplayDiagramsGroupBox->setChecked( false ); mFixedSizeCheckBox->setChecked( true ); mDiagramUnitComboBox->setCurrentIndex( mDiagramUnitComboBox->findText( tr( "mm" ) ) ); mLabelPlacementComboBox->setCurrentIndex( mLabelPlacementComboBox->findText( tr( "x-height" ) ) ); mDiagramSizeSpinBox->setValue( 30 ); mBarWidthSpinBox->setValue( 5 ); mVisibilityGroupBox->setChecked( false ); switch ( layerType ) { case QGis::Point: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) ); break; case QGis::Line: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 3 ) ); mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( 2 ) ); break; case QGis::Polygon: mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( 0 ) ); break; case QGis::UnknownGeometry: case QGis::NoGeometry: break; } mBackgroundColorButton->setColor( QColor( 255, 255, 255, 255 ) ); } else // already a diagram renderer present { mDisplayDiagramsGroupBox->setChecked( true ); //single category renderer or interpolated one? mFixedSizeCheckBox->setChecked( dr->rendererName() == "SingleCategory" ); //assume single category or linearly interpolated diagram renderer for now QList<QgsDiagramSettings> settingList = dr->diagramSettings(); if ( settingList.size() > 0 ) { mDiagramFont = settingList.at( 0 ).font; QSizeF size = settingList.at( 0 ).size; mBackgroundColorButton->setColor( settingList.at( 0 ).backgroundColor ); mTransparencySlider->setValue( settingList.at( 0 ).transparency ); mDiagramPenColorButton->setColor( settingList.at( 0 ).penColor ); mPenWidthSpinBox->setValue( settingList.at( 0 ).penWidth ); mDiagramSizeSpinBox->setValue(( size.width() + size.height() ) / 2.0 ); mMinimumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).minScaleDenominator, 'f' ) ); mMaximumDiagramScaleLineEdit->setText( QString::number( settingList.at( 0 ).maxScaleDenominator, 'f' ) ); mVisibilityGroupBox->setChecked( settingList.at( 0 ).minScaleDenominator != -1 && settingList.at( 0 ).maxScaleDenominator != -1 ); if ( settingList.at( 0 ).sizeType == QgsDiagramSettings::MM ) { mDiagramUnitComboBox->setCurrentIndex( 0 ); } else { mDiagramUnitComboBox->setCurrentIndex( 1 ); } if ( settingList.at( 0 ).labelPlacementMethod == QgsDiagramSettings::Height ) { mLabelPlacementComboBox->setCurrentIndex( 0 ); } else { mLabelPlacementComboBox->setCurrentIndex( 1 ); } mOrientationLeftButton->setProperty( "direction", QgsDiagramSettings::Left ); mOrientationRightButton->setProperty( "direction", QgsDiagramSettings::Right ); mOrientationUpButton->setProperty( "direction", QgsDiagramSettings::Up ); mOrientationDownButton->setProperty( "direction", QgsDiagramSettings::Down ); switch ( settingList.at( 0 ).diagramOrientation ) { case QgsDiagramSettings::Left: mOrientationLeftButton->setChecked( true ); break; case QgsDiagramSettings::Right: mOrientationRightButton->setChecked( true ); break; case QgsDiagramSettings::Up: mOrientationUpButton->setChecked( true ); break; case QgsDiagramSettings::Down: mOrientationDownButton->setChecked( true ); break; } mBarWidthSpinBox->setValue( settingList.at( 0 ).barWidth ); mIncreaseSmallDiagramsGroupBox->setChecked( settingList.at( 0 ).minimumSize != 0 ); mIncreaseMinimumSizeSpinBox->setValue( settingList.at( 0 ).minimumSize ); if ( settingList.at( 0 ).scaleByArea ) { mScaleDependencyComboBox->setCurrentIndex( 0 ); } else { mScaleDependencyComboBox->setCurrentIndex( 1 ); } QList< QColor > categoryColors = settingList.at( 0 ).categoryColors; QList< int > categoryIndices = settingList.at( 0 ).categoryIndices; QList< int >::const_iterator catIt = categoryIndices.constBegin(); QList< QColor >::const_iterator coIt = categoryColors.constBegin(); for ( ;catIt != categoryIndices.constEnd(); ++catIt, ++coIt ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget ); newItem->setText( 0, layer->pendingFields()[*catIt].name() ); newItem->setData( 0, Qt::UserRole, *catIt ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); QColor col( *coIt ); col.setAlpha( 255 ); newItem->setBackground( 1, QBrush( col ) ); } } if ( dr->rendererName() == "LinearlyInterpolated" ) { const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast<const QgsLinearlyInterpolatedDiagramRenderer*>( dr ); if ( lidr ) { mDiagramSizeSpinBox->setEnabled( false ); mValueLineEdit->setText( QString::number( lidr->upperValue(), 'f' ) ); mSizeSpinBox->setValue(( lidr->upperSize().width() + lidr->upperSize().height() ) / 2 ); mSizeAttributeComboBox->setCurrentIndex( mSizeAttributeComboBox->findData( lidr->classificationAttribute() ) ); } } const QgsDiagramLayerSettings *dls = layer->diagramLayerSettings(); if ( dls ) { mDiagramDistanceSpinBox->setValue( dls->dist ); mPrioritySlider->setValue( dls->priority ); mDataDefinedXComboBox->setCurrentIndex( mDataDefinedXComboBox->findData( dls->xPosColumn ) ); mDataDefinedYComboBox->setCurrentIndex( mDataDefinedYComboBox->findData( dls->yPosColumn ) ); if ( dls->xPosColumn != -1 || dls->yPosColumn != -1 ) { mDataDefinedPositionGroupBox->setChecked( true ); } mPlacementComboBox->setCurrentIndex( mPlacementComboBox->findData( dls->placement ) ); mLineOptionsComboBox->setCurrentIndex( mLineOptionsComboBox->findData( dls->placementFlags ) ); } if ( dr->diagram() ) { QString diagramName = dr->diagram()->diagramName(); mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( diagramName ) ); if ( mDiagramTypeComboBox->currentIndex() == -1 ) { QMessageBox::warning( this, tr( "Unknown diagram type." ), tr( "The diagram type '%1' is unknown. A default type is selected for you." ).arg( diagramName ), QMessageBox::Ok ); mDiagramTypeComboBox->setCurrentIndex( mDiagramTypeComboBox->findData( DIAGRAM_NAME_PIE ) ); } } } // if ( !dr ) // Trigger a clicked event, so all the items get properly enabled and disabled on_mDisplayDiagramsGroupBox_toggled( mDisplayDiagramsGroupBox->isChecked() ); }
bool SevenZipArch::processLine( const TQCString& _line ) { TQString line; TQString columns[ 11 ]; unsigned int pos = 0; int strpos, len; TQTextCodec *codec = TQTextCodec::codecForLocale(); line = codec->toUnicode( _line ); columns[ 0 ] = line.right( line.length() - m_nameColumnPos); line.truncate( m_nameColumnPos ); // Go through our columns, try to pick out data, return silently on failure for ( TQPtrListIterator <ArchColumns>col( m_archCols ); col.current(); ++col ) { ArchColumns *curCol = *col; strpos = curCol->pattern.search( line, pos ); len = curCol->pattern.matchedLength(); if ( ( strpos == -1 ) || ( len > curCol->maxLength ) ) { if ( curCol->optional ) continue; // More? else { kdDebug(1601) << "processLine failed to match critical column" << endl; return false; } } pos = strpos + len; columns[ curCol->colRef ] = line.mid( strpos, len ); } // Separated directories pass if(columns[4].length() && columns[4][0] == 'D') return true; if ( m_dateCol >= 0 ) { TQString year = ( m_repairYear >= 0 ) ? ArkUtils::fixYear( columns[ m_repairYear ].ascii()) : columns[ m_fixYear ]; TQString month = ( m_repairMonth >= 0 ) ? TQString( "%1" ) .arg( ArkUtils::getMonth( columns[ m_repairMonth ].ascii() ) ) : columns[ m_fixMonth ]; TQString timestamp = TQString::fromLatin1( "%1-%2-%3 %4" ) .arg( year ) .arg( month ) .arg( columns[ m_fixDay ] ) .arg( columns[ m_fixTime ] ); columns[ m_dateCol ] = timestamp; } TQStringList list; for ( int i = 0; i < m_numCols; ++i ) { list.append( columns[ i ] ); } m_gui->fileList()->addItem( list ); // send the entry to the GUI return true; }
void operator()( const state_type& x, matrix_type& jacobi, const double& t, state_type& dfdt) const { // fill 0 into jacobi and dfdt for (state_type::iterator i(dfdt.begin()); i != dfdt.end(); ++i) { *i = 0.0; } for (matrix_type::array_type::iterator i(jacobi.data().begin()); i != jacobi.data().end(); ++i) { *i = 0.0; } // Calculate jacobian for each reaction and merge it. for (reaction_container_type::const_iterator i(reactions_.begin()); i != reactions_.end(); i++) { // Calculate a reaction's jacobian. // prepare state_array that contain amounts of reactants index_container_type::size_type reactants_size(i->reactants.size()); index_container_type::size_type products_size(i->products.size()); Ratelaw::state_container_type reactants_states(reactants_size); Ratelaw::state_container_type products_states(products_size); Ratelaw::state_container_type::size_type cnt(0); for (index_container_type::const_iterator j((*i).reactants.begin()); j != (*i).reactants.end(); ++j, cnt++) { reactants_states[cnt] = x[*j]; } cnt = 0; for (index_container_type::const_iterator j((*i).products.begin()); j != (*i).products.end(); ++j, cnt++) { products_states[cnt] = x[*j]; } // prepare matrix object that will be filled with numerical differentiate. matrix_type::size_type row_length = reactants_size + products_size; matrix_type::size_type col_length = row_length; matrix_type mat(row_length, col_length); // get the pointer of Ratelaw object and call it. if (i->ratelaw.expired() || i->ratelaw.lock()->is_available() == false) { boost::scoped_ptr<Ratelaw> temporary_ratelaw_obj(new RatelawMassAction(i->k)); temporary_ratelaw_obj->jacobi_func(mat, reactants_states, products_states, volume_); } else { boost::shared_ptr<Ratelaw> ratelaw = (*i).ratelaw.lock(); (*ratelaw).jacobi_func(mat, reactants_states, products_states, volume_); } //merge jacobian for(matrix_type::size_type row(0); row < row_length; row++) { matrix_type::size_type j_row(row < reactants_size ? (*i).reactants[row] : (*i).products[row - reactants_size]); for(matrix_type::size_type col(0); col < col_length; col++) { matrix_type::size_type j_col(col < reactants_size ? (*i).reactants[col] : (*i).products[col - reactants_size]); jacobi(j_row, j_col) += mat(row, col); } } } }
void set_leds(vlpp::client& cl, const std::string& leds, const std::string& color) { vlpp::rgba_color col(color); cl.set_leds(str_to_ids(leds), col); }
void AddToFleetButton::Render( int realX, int realY, bool highlighted, bool clicked ) { #ifndef NON_PLAYABLE SidePanel *parent = (SidePanel *)m_parent; Team *team = g_app->GetWorld()->GetTeam(g_app->GetWorld()->m_myTeamId); if( parent->m_mode == SidePanel::ModeFleetPlacement ) { m_disabled = false; Image *bmpImage = g_resource->GetImage( g_app->GetMapRenderer()->m_imageFiles[m_unitType] ); g_renderer->SetBlendMode( Renderer::BlendModeSubtractive ); Colour col(30,30,30,0); for( int x = -1; x <= 1; ++x ) { for( int y = -1; y <= 1; ++y ) { g_renderer->Blit( bmpImage, realX+x, realY+y, m_w, m_h, col ); } } g_renderer->SetBlendMode( Renderer::BlendModeAdditive ); Colour colour = team->GetTeamColour(); if( highlighted ) { colour.m_b += 40; colour.m_g += 40; colour.m_r += 40; } if( clicked ) { colour.m_b += 80; colour.m_g += 80; colour.m_r += 80; } if( team->m_unitsAvailable[m_unitType] <= 0 || team->m_unitCredits < g_app->GetWorld()->GetUnitValue(m_unitType)) { m_disabled = true; } else { m_disabled = false; } if( m_disabled ) { colour = Colour(50, 50, 50, 255); } //float size = 32.0f; if( bmpImage ) { g_renderer->Blit( bmpImage, realX, realY, m_w, m_h, colour ); g_renderer->SetBlendMode( Renderer::BlendModeNormal ); } char languageString[64]; switch( m_unitType ) { case WorldObject::TypeBattleShip : sprintf( languageString, "unit_battleship" ); break; case WorldObject::TypeCarrier : sprintf( languageString, "unit_carrier" ); break; case WorldObject::TypeSub : sprintf( languageString, "unit_sub" ); break; } char caption[256]; sprintf(caption, "%s(%u)", LANGUAGEPHRASE(languageString), team->m_unitsAvailable[m_unitType]); Colour textCol = White; if( m_disabled ) { textCol = Colour(50,50,50,255); } g_renderer->TextCentreSimple( realX + m_w/2, realY+m_h, textCol, parent->m_fontsize, caption ); int variableTeamUnits = g_app->GetGame()->GetOptionValue("VariableUnitCounts"); if( variableTeamUnits == 1 ) { char caption[8]; sprintf( caption, "%d", g_app->GetWorld()->GetUnitValue( m_unitType )); Colour col = Colour(255,255,0,255); g_renderer->TextCentreSimple( realX + m_w/2, realY+m_h+14, col, parent->m_fontsize, caption ); } if( highlighted || clicked ) { InfoWindow *info = (InfoWindow *)EclGetWindow("Info"); if( info ) { info->SwitchInfoDisplay( m_unitType, -1 ); } } } else { m_disabled = true; } #endif }
//-------------------------------------------------------------- void kinectGuiApp::update(){ getCurVideo().update(); kinect.update(); if (joyAxisLeftY != 0) { ofColor c = kinect.lineColor.get(); int foo = -4*joyAxisLeftY; //ofLogNotice() << "joy: " << joyAxisLeftY << " foo: " << foo; //c[3] += int(-2*joyAxisLeftY); // -1 reverse negative is up on stick c[3] = ofClamp(c[3] + foo, 0, 255); //c.clamp(); kinect.lineColor.set(c); mainAlpha = ofClamp(mainAlpha+foo, 0, 255); } //if (joyAxisRightX != 0) { // mainHue = ofClamp(mainHue+(-4*joyAxisRightX), 0, 255); //} //if (joyAxisRightY != 0) { // mainSaturation = ofClamp(mainSaturation+(-4*joyAxisRightY), 0, 255); //} // Copy the kinect grey image into our video layer unsigned char* newPix = imgMain.getPixels(); unsigned char* pix = kinect.grayImg.getPixels(); int numPix = kinect.grayImg.getWidth() * kinect.grayImg.getHeight(); ofColor col(0,0,0,0); ofColor blank(0,0,0,0); for ( int i=0; i<numPix; i++ ) { if ( pix[i] < 1 ) { newPix[i*4] = 0; newPix[i*4+1] = 0; newPix[i*4+2] = 0; newPix[i*4+3] = 0; } else { int val = pix[i]; //ofColor newcol = ofColor(val, mainAlpha); ofColor newcol = ofColor::fromHsb(mainHue, mainSaturation, pix[i], mainAlpha); //col.r = pix[i]; //col.g = pix[i]; //col.b = pix[i]; //col[4] = mainAlpha; //imgMain.setColor(i,col); //newPix[i*4] = pix[i]; //newPix[i*4+1] = pix[i]; //newPix[i*4+2] = pix[i]; //newPix[i*4+3] = mainAlpha //newPix[i*4] = col.r; //newPix[i*4+1] = col.g; //newPix[i*4+2] = col.b; //newPix[i*4+3] = col[4]; newPix[i*4] = newcol.r; newPix[i*4+1] = newcol.g; newPix[i*4+2] = newcol.b; newPix[i*4+3] = newcol[3]; //newPix[i*4+3] = mainAlpha; } } imgMain.update(); }
//对渲染列表进行光照计算 //light表示为光源列表 因为可能同时存在点光源聚光灯等光源类型 void Light_T3RenderList(T3RenderListPtr rendList, T3CameraPtr cam, light *light, int32 numLight) { for(int32 poly = 0; poly < rendList->numPolys; poly++) { //获取当前多边形 T3RenderPolyPtr currentPoly = rendList->polyPtr[poly]; //对于多边形的状态进行判断 if((¤tPoly == Null) || !(currentPoly->state & T3POLY_STATE_ACTIVE) || (currentPoly->state & T3POLY_STATE_CLIPPED) || (currentPoly->state & T3POLY_STATE_BACKFACE)) //无需转换直接跳过此多边形 continue; //保存多边形的三个顶点坐标 T3Point4D vertex0 = currentPoly->transVertexList[0], vertex1 = currentPoly->transVertexList[1], vertex2 = currentPoly->transVertexList[2]; //获取多边形基底RGB分量颜色 float32 baseR = currentPoly->color.getRed(), baseG = currentPoly->color.getGreen(), baseB = currentPoly->color.getBlue(); //受到各种光源照射下后的多边形颜色 float32 sumR = 0.0f, sumG = 0.0f, sumB = 0.0f; //遍历光源 for(int32 i = 0; i < numLight; i++) { if(light[i].state == LIGHTOFF) continue; //状态机思想 if(light[i].attribute == LIGHT_AMBIENT) { sumR += ((light[i].ambient.getRed() * baseR) / 256); sumG += ((light[i].ambient.getGreen() * baseG) / 256); sumB += ((light[i].ambient.getBlue() * baseB) / 256); } if(light[i].attribute == LIGHT_POINT) { //三角形两边的向量以及三角形面法线 T3Vector4D u, v, n; T3Vector4DBuild(&vertex0, &vertex1, &u); T3Vector4DBuild(&vertex0, &vertex2, &v); //计算面法线 T3Vector4DCross(&u, &v, &n); T3Vector4D sufaceToLight; //表面到光源的向量 T3Vector4DBuild(&vertex0, &light[i].position, &sufaceToLight); //计算表面到光源距离 float32 distance = T3Vector4DLengthFast(&sufaceToLight); //将面法线归一化步骤单独列举出来 //使用快速开根号加快运算速度 float32 nLength = T3Vector4DLengthFast(&n); //两单位向量相乘得到cos(theta) float32 dotProduct = T3Vector4DDot(&sufaceToLight, &n); //负角度或0度无需考虑光照影响 if(dotProduct > 0) { //I*C/(kc+kl*d+kq*d*d) float32 atten = light[i].kc + light[i].kl*distance + light[i].kq*distance*distance; //相当于对面法线与距离向量进行归一化 float32 j = dotProduct / (atten*nLength*distance); sumR += light[i].diffuse.getRed()*baseR*j / 256.0; sumG += light[i].diffuse.getGreen()*baseG*j / 256.0; sumB += light[i].diffuse.getBlue()*baseB*j / 256.0; } } if(light[i].attribute == LIGHT_INFINITE) { //三角形两边的向量以及三角形面法线 T3Vector4D u, v, n; T3Vector4DBuild(&vertex0, &vertex1, &u); T3Vector4DBuild(&vertex0, &vertex2, &v); //计算面法线 T3Vector4DCross(&u, &v, &n); //将面法线归一化步骤单独列举出来 //使用快速开根号加快运算速度 float32 nLength = T3Vector4DLengthFast(&n); //两单位向量相乘得到cos(theta) float32 dotProduct = T3Vector4DDot(&light->direction, &n); //负角度或0度无需考虑光照影响 if(dotProduct > 0) { float32 j = dotProduct / nLength; sumR += light[i].diffuse.getRed()*baseR*j / 256.0; sumG += light[i].diffuse.getGreen()*baseG*j / 256.0; sumB += light[i].diffuse.getBlue()*baseB*j / 256.0; } } if(light[i].attribute == LIGHT_SPOTLIGHT) { } } //防止颜色溢出 if(sumR > 255.0) sumR = 255.0; if(sumG > 255.0) sumG = 255.0; if(sumB > 255.0) sumB = 255.0; Color col(sumR, sumG, sumB); //覆盖当前多边形颜色 currentPoly->color = col; } }
Colour Raytracer::shadeRay( Ray3D& ray, int reflectionDepth, int refractionDepth ) { Colour col(0.0, 0.0, 0.0); traverseScene(_root, ray); // Don't bother shading if the ray didn't hit // anything. if (REFRACTION_FLAG_DEBUG) { printf("\n\n checking intersection \n"); printf(" incident ray: (%f, %f, %f) \n", ray.dir[0], ray.dir[1], ray.dir[2]); } Intersection inter = ray.intersection; if ( !inter.none ) { computeShading(ray); if (REFRACTION_FLAG_DEBUG) { printf("\n\n ---------------------- INTERSECTION WITH OBJECT ------------------------------ \n\n"); } //Spawn a ray for reflection if ( reflectionDepth < getReflDepth() ) { Vector3D n = inter.normal; Vector3D de = -ray.dir; Vector3D m = 2 * de.dot(n) * n - de; // reflect across normal // http://www.cdf.toronto.edu/~moore/csc418/Notes/Phong.pdf // reflection if ( inter.mat->refl_amt > 0.0f ) { if (REFRACTION_FLAG_DEBUG) { printf("\n\n ........ DOING REFLECTION ........ \n"); } Ray3D refl_ray; refl_ray.origin = inter.point;// + (DBL_0_UPPER * m); refl_ray.dir = m; Colour rCol(0.0, 0.0, 0.0); rCol = shadeRay(refl_ray, reflectionDepth + 1, refractionDepth); ray.col = ray.col + (inter.mat->refl_amt * rCol); } // Spawn a seperate ray for refraction if ( inter.mat->transparency > 0.0f ) { double th_1 = std::abs(de.dot(n)); double c1, c2; if ( th_1 >= 0 ) { c1 = inter.mat->IOR; c2 = ray._cur_speed; ray._cur_speed = c1; } else { c2 = inter.mat->IOR; c1 = ray._cur_speed; ray._cur_speed = c2; } double IOR = c2 / c1; // double IOR = 1; // will make it transparent, for testing double th_2 = sqrt(1.0 - (IOR * IOR) * (1.0 - (th_1 * th_1))); Ray3D refr_ray; refr_ray.dir = -de + IOR * (th_1 * n) + (-th_2 * n); refr_ray.origin = (inter.point) + (DBL_EPSILON * refr_ray.dir); Colour rCol(0.0, 0.0, 0.0); rCol = shadeRay(refr_ray, reflectionDepth + 1, refractionDepth + 1); ray.col = ray.col + (inter.mat->transparency * rCol); } } col = ray.col; } else { // env map if ( getEnvMapMode() == ENV_MAP_CUBE_SKYBOX ) { col = getEnvMap().getColorForRay(ray.dir); } } col.clamp(); return col; }
//------------------------------------------------------------------------ void CVehicleMovementStdBoat::UpdateSurfaceEffects(const float deltaTime) { FUNCTION_PROFILER(GetISystem(), PROFILE_GAME); if(0 == g_pGameCVars->v_pa_surface) { ResetParticles(); return; } IEntity *pEntity = m_pVehicle->GetEntity(); const Matrix34 &worldTM = pEntity->GetWorldTM(); float distSq = worldTM.GetTranslation().GetSquaredDistance(gEnv->pRenderer->GetCamera().GetPosition()); if(distSq > sqr(300.f) || (distSq > sqr(50.f) && !m_pVehicle->GetGameObject()->IsProbablyVisible())) return; Matrix34 worldTMInv = worldTM.GetInverted(); const SVehicleStatus &status = m_pVehicle->GetStatus(); float velDot = status.vel * worldTM.GetColumn1(); float powerNorm = min(abs(m_movementAction.power), 1.f); SEnvironmentParticles *envParams = m_pPaParams->GetEnvironmentParticles(); SEnvParticleStatus::TEnvEmitters::iterator end = m_paStats.envStats.emitters.end(); for(SEnvParticleStatus::TEnvEmitters::iterator emitterIt = m_paStats.envStats.emitters.begin(); emitterIt!=end; ++emitterIt) { if(emitterIt->layer < 0) { assert(0); continue; } const SEnvironmentLayer &layer = envParams->GetLayer(emitterIt->layer); SEntitySlotInfo info; info.pParticleEmitter = 0; pEntity->GetSlotInfo(emitterIt->slot, info); float countScale = 1.f; float sizeScale = 1.f; float speedScale = 1.f; float speed = 0.f; // check if helper position is beneath water level Vec3 emitterWorldPos = worldTM * emitterIt->quatT.t; float waterLevel = gEnv->p3DEngine->GetWaterLevel(&emitterWorldPos); int matId = 0; if(emitterWorldPos.z <= waterLevel+0.1f && m_statusDyn.submergedFraction<0.999f) { matId = gEnv->pPhysicalWorld->GetWaterMat(); speed = status.speed; bool spray = !strcmp(layer.GetName(), "spray"); if(spray) { // slip based speed -= abs(velDot); } GetParticleScale(layer, speed, powerNorm, countScale, sizeScale, speedScale); } else { countScale = 0.f; } if(matId && matId != emitterIt->matId) { // change effect IParticleEffect *pEff = 0; const char *effect = GetEffectByIndex(matId, layer.GetName()); if(effect && (pEff = gEnv->pParticleManager->FindEffect(effect))) { #if ENABLE_VEHICLE_DEBUG if(DebugParticles()) CryLog("%s changes water sfx to %s (slot %i)", pEntity->GetName(), effect, emitterIt->slot); #endif if(info.pParticleEmitter) { info.pParticleEmitter->Activate(false); pEntity->FreeSlot(emitterIt->slot); } emitterIt->slot = pEntity->LoadParticleEmitter(emitterIt->slot, pEff); if(emitterIt->slot != -1) pEntity->SetSlotLocalTM(emitterIt->slot, Matrix34(emitterIt->quatT)); info.pParticleEmitter = 0; pEntity->GetSlotInfo(emitterIt->slot, info); } else countScale = 0.f; } if(matId) emitterIt->matId = matId; if(info.pParticleEmitter) { SpawnParams sp; sp.fSizeScale = sizeScale; sp.fCountScale = countScale; sp.fSpeedScale = speedScale; info.pParticleEmitter->SetSpawnParams(sp); if(layer.alignToWater && countScale > 0.f) { Vec3 worldPos(emitterWorldPos.x, emitterWorldPos.y, waterLevel+0.05f); Matrix34 localTM(emitterIt->quatT); localTM.SetTranslation(worldTMInv * worldPos); pEntity->SetSlotLocalTM(emitterIt->slot, localTM); } } #if ENABLE_VEHICLE_DEBUG if(DebugParticles() && m_pVehicle->IsPlayerDriving()) { float color[] = {1,1,1,1}; ColorB red(255,0,0,255); IRenderAuxGeom *pAuxGeom = gEnv->pRenderer->GetIRenderAuxGeom(); const char *effect = info.pParticleEmitter ? info.pParticleEmitter->GetName() : ""; const Matrix34 &slotTM = m_pEntity->GetSlotWorldTM(emitterIt->slot); Vec3 ppos = slotTM.GetTranslation(); pAuxGeom->DrawSphere(ppos, 0.2f, red); pAuxGeom->DrawCone(ppos, slotTM.GetColumn1(), 0.1f, 0.5f, red); gEnv->pRenderer->Draw2dLabel(50.f, (float)(400+10*emitterIt->slot), 1.2f, color, false, "<%s> water fx: slot %i [%s], speed %.1f, sizeScale %.2f, countScale %.2f (pos %.0f,%0.f,%0.f)", pEntity->GetName(), emitterIt->slot, effect, speed, sizeScale, countScale, ppos.x, ppos.y, ppos.z); } #endif } // generate water splashes Vec3 wakePos; if(m_pSplashPos) { wakePos = m_pSplashPos->GetWorldSpaceTranslation(); } else { wakePos = worldTM.GetTranslation(); } float wakeWaterLevel = gEnv->p3DEngine->GetWaterLevel(&wakePos); Vec3 localW = worldTMInv.TransformVector(m_statusDyn.w); if(localW.x >= 0.f) m_diving = false; if(!m_diving && localW.x < -0.03f && status.speed > 10.f && wakePos.z < m_lastWakePos.z && wakeWaterLevel+0.1f >= wakePos.z) { float speedRatio = min(1.f, status.speed/m_maxSpeed); m_diving = true; if(m_pWaveEffect) { if(IParticleEmitter *pEmitter = pEntity->GetParticleEmitter(m_wakeSlot)) { pEmitter->Activate(false); pEntity->FreeSlot(m_wakeSlot); m_wakeSlot = -1; } SpawnParams spawnParams; spawnParams.fSizeScale = spawnParams.fCountScale = 0.5f + 0.25f*speedRatio; spawnParams.fSizeScale += 0.4f*m_waveRandomMult; spawnParams.fCountScale += 0.4f*Random(); m_wakeSlot = pEntity->LoadParticleEmitter(m_wakeSlot, m_pWaveEffect, &spawnParams); } // handle splash sound PlaySound(eSID_Splash, 0.f, Vec3(0,5,1)); SetSoundParam(eSID_Splash, "intensity", 0.2f*speedRatio + 0.5f*m_waveRandomMult); if(m_rpmPitchDir == 0) { m_rpmPitchDir = -1; m_waveSoundPitch = 0.f; m_waveSoundAmount = 0.02f + m_waveRandomMult*0.08f; } } if(m_wakeSlot != -1) { // update emitter local pos to short above waterlevel Matrix34 tm; if(m_pSplashPos) m_pSplashPos->GetVehicleTM(tm); else tm.SetIdentity(); Vec3 pos = tm.GetTranslation(); pos.z = worldTMInv.TransformPoint(Vec3(wakePos.x,wakePos.y,wakeWaterLevel)).z + 0.2f; tm.SetTranslation(pos); pEntity->SetSlotLocalTM(m_wakeSlot, tm); #if ENABLE_VEHICLE_DEBUG if(IsProfilingMovement()) { Vec3 wPos = worldTM * tm.GetTranslation(); ColorB col(128, 128, 0, 200); gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(wPos, 0.4f, col); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(wPos, col, wPos+Vec3(0,0,1.5f), col); } #endif } m_lastWakePos = wakePos; }
bool d3d::DrawBasicScene(IDirect3DDevice9* device, float scale) { static IDirect3DVertexBuffer9* floor = 0; static IDirect3DTexture9* tex = 0; static ID3DXMesh* pillar = 0; HRESULT hr = 0; if( device == 0 ) { if( floor && tex && pillar ) { // they already exist, destroy them d3d::Release<IDirect3DVertexBuffer9*>(floor); d3d::Release<IDirect3DTexture9*>(tex); d3d::Release<ID3DXMesh*>(pillar); } } else if( !floor && !tex && !pillar ) { // they don't exist, create them device->CreateVertexBuffer( 6 * sizeof(d3d::Vertex), 0, d3d::Vertex::FVF, D3DPOOL_MANAGED, &floor, 0); Vertex* v = 0; floor->Lock(0, 0, (void**)&v, 0); v[0] = Vertex(-20.0f, -2.5f, -20.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); v[1] = Vertex(-20.0f, -2.5f, 20.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); v[2] = Vertex( 20.0f, -2.5f, 20.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); v[3] = Vertex(-20.0f, -2.5f, -20.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f); v[4] = Vertex( 20.0f, -2.5f, 20.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); v[5] = Vertex( 20.0f, -2.5f, -20.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f); floor->Unlock(); D3DXCreateCylinder(device, 0.5f, 0.5f, 5.0f, 20, 20, &pillar, 0); D3DXCreateTextureFromFile( device, "desert.bmp", &tex); } else { // // Pre-Render Setup // device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); D3DXVECTOR3 dir(0.707f, -0.707f, 0.707f); D3DXCOLOR col(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col); device->SetLight(0, &light); device->LightEnable(0, true); device->SetRenderState(D3DRS_NORMALIZENORMALS, true); device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Render // D3DXMATRIX T, R, P, S; D3DXMatrixScaling(&S, scale, scale, scale); // used to rotate cylinders to be parallel with world's y-axis D3DXMatrixRotationX(&R, -D3DX_PI * 0.5f); // draw floor D3DXMatrixIdentity(&T); T = T * S; device->SetTransform(D3DTS_WORLD, &T); device->SetMaterial(&d3d::WHITE_MTRL); device->SetTexture(0, tex); device->SetStreamSource(0, floor, 0, sizeof(Vertex)); device->SetFVF(Vertex::FVF); device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2); // draw pillars device->SetMaterial(&d3d::BLUE_MTRL); device->SetTexture(0, 0); for(int i = 0; i < 5; i++) { D3DXMatrixTranslation(&T, -5.0f, 0.0f, -15.0f + (i * 7.5f)); P = R * T * S; device->SetTransform(D3DTS_WORLD, &P); pillar->DrawSubset(0); D3DXMatrixTranslation(&T, 5.0f, 0.0f, -15.0f + (i * 7.5f)); P = R * T * S; device->SetTransform(D3DTS_WORLD, &P); pillar->DrawSubset(0); } } return true; }
/** Create the dual of a linear program. * The function can only dualize programs of the form * <code>Ax <= b, x >= 0</code>. The data in <code>primalVars</code> and * <code>dualRows</code> as well as in <code>primalRows</code> and * <code>dualVars</code> is in 1-to-1-correspondence. * @param primalObj Objective function of primal problem. * @param primalVars Variables in primal problem. * @param primalRows Rows in primal problem. * @param dualObj Objective function of dual will be stored here. * @param dualVars All dual variables will be stored here. * @param dualRows All dual rows will be stored here. */ void BendersOpt::makeDual(IloObjective const &primalObj, IloNumVarArray const &primalVars, IloRangeArray const &primalRows, IloObjective *dualObj, IloNumVarArray *dualVars, IloRangeArray *dualRows) { // To keep the code simple we only support problems // of the form Ax <= b, b >= 0 here. We leave it as a reader's // exercise to extend the function to something that can handle // any kind of linear model. for (IloInt j = 0; j < primalVars.getSize(); ++j) if ( primalVars[j].getLB() != 0 || primalVars[j].getUB() < IloInfinity ) { std::stringstream s; s << "Cannot dualize variable " << primalVars[j]; throw s.str(); } for (IloInt i = 0; i < primalRows.getSize(); ++i) if ( primalRows[i].getLB() > -IloInfinity || primalRows[i].getUB() >= IloInfinity ) { std::stringstream s; s << "Cannot dualize constraint " << primalRows[i]; std::cerr << s.str() << std::endl; throw s.str(); } // The dual of // min/max c^T x // Ax <= b // x >= 0 // is // max/min y^T b // y^T A <= c // y <= 0 // We scale y by -1 to get >= 0 IloEnv env = primalVars.getEnv(); IloObjective obj(env, 0.0, primalObj.getSense() == IloObjective::Minimize ? IloObjective::Maximize : IloObjective::Minimize); IloRangeArray rows(env); IloNumVarArray y(env); std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> > v2i; for (IloInt j = 0; j < primalVars.getSize(); ++j) { IloNumVar x = primalVars[j]; v2i.insert(std::map<IloNumVar,IloInt,ExtractableLess<IloNumVar> >::value_type(x, j)); rows.add(IloRange(env, -IloInfinity, 0, x.getName())); } for (IloExpr::LinearIterator it = primalObj.getLinearIterator(); it.ok(); ++it) rows[v2i[it.getVar()]].setUB(it.getCoef()); for (IloInt i = 0; i < primalRows.getSize(); ++i) { IloRange r = primalRows[i]; IloNumColumn col(env); col += obj(-r.getUB()); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) col += rows[v2i[it.getVar()]](-it.getCoef()); y.add(IloNumVar(col, 0, IloInfinity, IloNumVar::Float, r.getName())); } *dualObj = obj; *dualVars = y; *dualRows = rows; }
COLOR CColorCombiner::GetConstFactor(uint32_t colorFlag, uint32_t alphaFlag, uint32_t defaultColor) { // Allows a combine mode to select what TFACTOR should be uint32_t color = defaultColor; uint32_t alpha = defaultColor; switch (colorFlag & MUX_MASK) { case MUX_0: break; case MUX_FORCE_0: color = 0; break; case MUX_1: color = 0xFFFFFFFF; break; case MUX_PRIM: color = gRDP.primitiveColor; break; case MUX_ENV: color = gRDP.envColor; break; case MUX_LODFRAC: color = COLOR_RGBA(gRDP.LODFrac, gRDP.LODFrac, gRDP.LODFrac, gRDP.LODFrac); break; case MUX_PRIMLODFRAC: color = COLOR_RGBA(gRDP.primLODFrac, gRDP.primLODFrac, gRDP.primLODFrac, gRDP.primLODFrac); break; case MUX_PRIM_ALPHA: { IColor col(gRDP.primitiveColor); col.AlphaReplicate(); color = (COLOR)col; } break; case MUX_ENV_ALPHA: { IColor col(gRDP.envColor); col.AlphaReplicate(); color = (COLOR)col; } break; case MUX_K5: color = 0xFFFFFFFF; break; case MUX_UNK: color = defaultColor; if(options.enableHackForGames == HACK_FOR_CONKER) { color = 0xFFFFFFFF; } break; default: color = defaultColor; break; } if (colorFlag & MUX_COMPLEMENT) { color = 0xFFFFFFFF - color; } if (colorFlag & MUX_ALPHAREPLICATE) { color = color>>24; color = color | (color<<8) | (color <<16) | (color<<24); }
CollapsibleEffect::CollapsibleEffect(const QDomElement &effect, const QDomElement &original_effect, const ItemInfo &info, EffectMetaInfo *metaInfo, bool canMoveUp, bool lastEffect, QWidget * parent) : AbstractCollapsibleWidget(parent), m_paramWidget(NULL), m_effect(effect), m_itemInfo(info), m_original_effect(original_effect), m_isMovable(true), m_animation(NULL), m_regionEffect(false) { if (m_effect.attribute(QStringLiteral("tag")) == QLatin1String("region")) { m_regionEffect = true; decoframe->setObjectName(QStringLiteral("decoframegroup")); } filterWheelEvent = true; m_info.fromString(effect.attribute(QStringLiteral("kdenlive_info"))); //setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); buttonUp->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-up"))); QSize iconSize = buttonUp->iconSize(); buttonUp->setMaximumSize(iconSize); buttonDown->setMaximumSize(iconSize); menuButton->setMaximumSize(iconSize); enabledButton->setMaximumSize(iconSize); buttonDel->setMaximumSize(iconSize); buttonUp->setToolTip(i18n("Move effect up")); buttonDown->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-down"))); buttonDown->setToolTip(i18n("Move effect down")); buttonDel->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-deleffect"))); buttonDel->setToolTip(i18n("Delete effect")); buttonUp->setEnabled(canMoveUp); buttonDown->setEnabled(!lastEffect); if (m_effect.attribute(QStringLiteral("id")) == QLatin1String("speed")) { // Speed effect is a "pseudo" effect, cannot be moved buttonUp->setVisible(false); buttonDown->setVisible(false); m_isMovable = false; setAcceptDrops(false); } else { setAcceptDrops(true); } /*buttonReset->setIcon(KoIconUtils::themedIcon("view-refresh")); buttonReset->setToolTip(i18n("Reset effect"));*/ //checkAll->setToolTip(i18n("Enable/Disable all effects")); //buttonShowComments->setIcon(KoIconUtils::themedIcon("help-about")); //buttonShowComments->setToolTip(i18n("Show additional information for the parameters")); m_menu = new QMenu(this); m_menu->addAction(KoIconUtils::themedIcon(QStringLiteral("view-refresh")), i18n("Reset Effect"), this, SLOT(slotResetEffect())); m_menu->addAction(KoIconUtils::themedIcon(QStringLiteral("document-save")), i18n("Save Effect"), this, SLOT(slotSaveEffect())); QHBoxLayout *l = static_cast <QHBoxLayout *>(frame->layout()); m_colorIcon = new QLabel(this); l->insertWidget(0, m_colorIcon); m_colorIcon->setMinimumSize(iconSize); title = new QLabel(this); l->insertWidget(2, title); m_enabledButton = new KDualAction(i18n("Disable Effect"), i18n("Enable Effect"), this); m_enabledButton->setActiveIcon(KoIconUtils::themedIcon(QStringLiteral("hint"))); m_enabledButton->setInactiveIcon(KoIconUtils::themedIcon(QStringLiteral("visibility"))); enabledButton->setDefaultAction(m_enabledButton); m_groupAction = new QAction(KoIconUtils::themedIcon(QStringLiteral("folder-new")), i18n("Create Group"), this); connect(m_groupAction, SIGNAL(triggered(bool)), this, SLOT(slotCreateGroup())); QDomElement namenode = m_effect.firstChildElement(QStringLiteral("name")); if (namenode.isNull()) { // Warning, broken effect? //qDebug()<<"// Could not create effect"; return; } QString effectname = i18n(namenode.text().toUtf8().data()); if (m_regionEffect) effectname.append(':' + QUrl(EffectsList::parameter(m_effect, QStringLiteral("resource"))).fileName()); // Create color thumb QPixmap pix(iconSize); QColor col(m_effect.attribute(QStringLiteral("effectcolor"))); QFont ft = font(); ft.setBold(true); bool isAudio = m_effect.attribute(QStringLiteral("type")) == QLatin1String("audio"); if (isAudio) { pix.fill(Qt::transparent); } else { pix.fill(col); } QPainter p(&pix); if (isAudio) { p.setPen(Qt::NoPen); p.setBrush(col); p.drawEllipse(pix.rect()); p.setPen(QPen()); } p.setFont(ft); p.drawText(pix.rect(), Qt::AlignCenter, effectname.at(0)); p.end(); m_iconPix = pix; m_colorIcon->setPixmap(pix); title->setText(effectname); if (!m_regionEffect) { if (m_info.groupIndex == -1) m_menu->addAction(m_groupAction); m_menu->addAction(KoIconUtils::themedIcon(QStringLiteral("folder-new")), i18n("Create Region"), this, SLOT(slotCreateRegion())); } setupWidget(info, metaInfo); menuButton->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-menu"))); menuButton->setMenu(m_menu); if (m_effect.attribute(QStringLiteral("disable")) == QLatin1String("1")) { title->setEnabled(false); m_enabledButton->setActive(true); } else { m_enabledButton->setActive(false); } connect(collapseButton, SIGNAL(clicked()), this, SLOT(slotSwitch())); connect(m_enabledButton, SIGNAL(activeChangedByUser(bool)), this, SLOT(slotDisable(bool))); connect(buttonUp, SIGNAL(clicked()), this, SLOT(slotEffectUp())); connect(buttonDown, SIGNAL(clicked()), this, SLOT(slotEffectDown())); connect(buttonDel, SIGNAL(clicked()), this, SLOT(slotDeleteEffect())); Q_FOREACH( QSpinBox * sp, findChildren<QSpinBox*>() ) { sp->installEventFilter( this ); sp->setFocusPolicy( Qt::StrongFocus ); }
bool AsciiProcessor::ins_string( const char * buf, int fref, BuilderBase * build, const char * & next ) { int id = 0, lay = 0, fil = 0; RGBcolor col( 0, 0, 0 ); Point2d point; if ( ! get_obj_attr( buf, id, lay, col, fil, next ) ) { return CMD_ERR; } while ( true ) //accept more then one string! { if ( ! strskip( next, '(', next ) ) { return CMD_ERR; } if ( ! str2val( next, point.x, next ) ) { return CMD_ERR; } if ( ! strskip( next, ',', next ) ) { return CMD_ERR; } if ( ! str2val( next, point.y, next ) ) { return CMD_ERR; } if ( ! strskip( next, ',', next ) ) { return CMD_ERR; } buf = next; int offset; int res = get_string( buf, offset, next ); if ( res < 0 ) { return CMD_ERR; } if ( ! strskip( next, ')', next ) ) { return CMD_ERR; } VisualObject2d * string2d = new VisualString2d( id, lay, col, point, res, buf + offset ); build->set_cmd_insert_visobject( fref, string2d ); if ( strskip( next, DELIMITER_CHAR, next ) ) { break; } } return CMD_OK; }
bool parseReport(const QDomElement & elemSource, ORReportData & reportTarget) { if(elemSource.tagName() != "report") { qDebug("QDomElement passed to parseReport() was not <report> tag"); return FALSE; } double d = 0.0; bool valid = FALSE; QDomNodeList section = elemSource.childNodes(); for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++) { QDomElement elemThis = section.item(nodeCounter).toElement(); if(elemThis.tagName() == "title") reportTarget.title = elemThis.text(); else if(elemThis.tagName() == "name") reportTarget.name = elemThis.text(); else if(elemThis.tagName() == "description") reportTarget.description = elemThis.text(); else if(elemThis.tagName() == "parameter") { parseReportParameter(elemThis, reportTarget); } else if(elemThis.tagName() == "watermark") parseReportWatermark(elemThis, reportTarget.wmData); else if(elemThis.tagName() == "background") parseReportBackground(elemThis, reportTarget.bgData); else if(elemThis.tagName() == "size") { if(elemThis.firstChild().isText()) reportTarget.page.setPageSize(elemThis.firstChild().nodeValue()); else { //bad code! bad code! // this code doesn't check the elemts and assums they are what // they should be. QDomNode n1 = elemThis.firstChild(); QDomNode n2 = n1.nextSibling(); if(n1.nodeName() == "width") { reportTarget.page.setCustomWidth(n1.firstChild().nodeValue().toDouble() / 100.0); reportTarget.page.setCustomHeight(n2.firstChild().nodeValue().toDouble() / 100.0); } else { reportTarget.page.setCustomWidth(n2.firstChild().nodeValue().toDouble() / 100.0); reportTarget.page.setCustomHeight(n1.firstChild().nodeValue().toDouble() / 100.0); } reportTarget.page.setPageSize("Custom"); } } else if(elemThis.tagName() == "labeltype") reportTarget.page.setLabelType(elemThis.firstChild().nodeValue()); else if(elemThis.tagName() == "portrait") reportTarget.page.setPortrait(TRUE); else if(elemThis.tagName() == "landscape") reportTarget.page.setPortrait(FALSE); else if(elemThis.tagName() == "topmargin") { d = elemThis.text().toDouble(&valid); if(!valid || d < 0.0) { qDebug("Error converting topmargin value: %s",(const char*)elemThis.text()); d = 50.0; } reportTarget.page.setMarginTop((d / 100.0)); } else if(elemThis.tagName() == "bottommargin") { d = elemThis.text().toDouble(&valid); if(!valid || d < 0.0) { qDebug("Error converting bottommargin value: %s",(const char*)elemThis.text()); d = 50.0; } reportTarget.page.setMarginBottom((d / 100.0)); } else if(elemThis.tagName() == "leftmargin") { d = elemThis.text().toDouble(&valid); if(!valid || d < 0.0) { qDebug("Error converting leftmargin value: %s",(const char*)elemThis.text()); d = 50.0; } reportTarget.page.setMarginLeft(d/100.0); } else if(elemThis.tagName() == "rightmargin") { d = elemThis.text().toDouble(&valid); if(!valid || d < 0.0) { qDebug("Error converting rightmargin value: %s",(const char*)elemThis.text()); d = 50.0; } reportTarget.page.setMarginRight(d/100.0); } else if(elemThis.tagName() == "querysource") { // we need to read in the query sources QString qsname = elemThis.namedItem("name").toElement().text(); QString qsquery = elemThis.namedItem("sql").toElement().text(); reportTarget.queries.add(new QuerySource(qsname,qsquery)); } else if(elemThis.tagName() == "rpthead") { ORSectionData * sd = new ORSectionData(); if(parseReportSection(elemThis, *sd) == TRUE) { reportTarget.rpthead = sd; reportTarget.trackTotal += sd->trackTotal; } else delete sd; } else if(elemThis.tagName() == "rptfoot") { ORSectionData * sd = new ORSectionData(); if(parseReportSection(elemThis, *sd) == TRUE) { reportTarget.rptfoot = sd; reportTarget.trackTotal += sd->trackTotal; } else delete sd; } else if(elemThis.tagName() == "pghead") { ORSectionData * sd = new ORSectionData(); if(parseReportSection(elemThis, *sd) == TRUE) { if(sd->extra == "firstpage") reportTarget.pghead_first = sd; else if(sd->extra == "odd") reportTarget.pghead_odd = sd; else if(sd->extra == "even") reportTarget.pghead_even = sd; else if(sd->extra == "lastpage") reportTarget.pghead_last = sd; else if(sd->extra == QString::null) reportTarget.pghead_any = sd; else { qDebug("don't know which page this page header is for: %s",(const char*)sd->extra); delete sd; } reportTarget.trackTotal += sd->trackTotal; } else delete sd; } else if(elemThis.tagName() == "pgfoot") { ORSectionData * sd = new ORSectionData(); if(parseReportSection(elemThis, *sd) == TRUE) { if(sd->extra == "firstpage") reportTarget.pgfoot_first = sd; else if(sd->extra == "odd") reportTarget.pgfoot_odd = sd; else if(sd->extra == "even") reportTarget.pgfoot_even = sd; else if(sd->extra == "lastpage") reportTarget.pgfoot_last = sd; else if(sd->extra == QString::null) reportTarget.pgfoot_any = sd; else { qDebug("don't know which page this page footer is for: %s",(const char*)sd->extra); delete sd; } reportTarget.trackTotal += sd->trackTotal; } else delete sd; } else if(elemThis.tagName() == "section") { ORDetailSectionData * dsd = new ORDetailSectionData(); if(parseReportDetailSection(elemThis, *dsd) == TRUE) { reportTarget.sections.append(dsd); reportTarget.trackTotal += dsd->trackTotal; } else delete dsd; } else if(elemThis.tagName() == "colordef") { ORColorDefData coldef; if(parseReportColorDefData(elemThis, coldef) == TRUE) { QColor col(coldef.red, coldef.green, coldef.blue); reportTarget.color_map[coldef.name] = col; } } else qDebug("While parsing report encountered an unknown element: %s",(const char*)elemThis.tagName()); } return TRUE; }
bool AsciiProcessor::ins_string_grid( const char * buf, int fref, BuilderBase * build, const char * & next ) { int id = 0, lay = 0, fil = 0; RGBcolor col( 0, 0, 0 ); if ( ! get_obj_attr( buf, id, lay, col, fil, next ) ) { return CMD_ERR; } while ( true ) { double p_x, p_y, v1_x, v1_y, v2_x, v2_y, d3, d4, d5; int num_v1 = 1, num_v2 = 1; if ( ! strskip( next, '(', next ) ) { return CMD_ERR; } if ( get_max5_tuple( next, 2, p_x, p_y, d3, d4, d5, next ) != 2 ) { return CMD_ERR; } if ( get_max5_tuple( next, 2, v1_x, v1_y, d3, d4, d5, next ) != 2 ) { return CMD_ERR; } if ( strskip( next, ':', next ) ) { if ( ! str2val( next, num_v1, next ) ) { return CMD_ERR; } } if ( get_max5_tuple( next, 2, v2_x, v2_y, d3, d4, d5, next ) != 2 ) { return CMD_ERR; } if ( strskip( next, ':', next ) ) { if ( ! str2val( next, num_v2, next ) ) { return CMD_ERR; } } const double d1 = 1.0 / double( num_v1 ); const double d2 = 1.0 / double( num_v2 ); bool early_stop = false; for ( int i = 0; i < num_v2; ++i ) { Point2d point; point.x = p_x + i * v2_x * d2 ; point.y = p_y + i * v2_y * d2 ; for ( int j = 0; j < num_v1; j++ ) { int offset; if ( strskip( next, ')', next ) ) { early_stop = true; break; } buf = next; int res = get_string( buf, offset, next ); if ( res < 0 ) { return CMD_ERR; } VisualObject2d * string2d = new VisualString2d( id, lay, col, point, res, buf + offset ); build->set_cmd_insert_visobject( fref, string2d ); point.x += v1_x * d1; point.y += v1_y * d1; } if ( early_stop ) { break; } } if ( ! early_stop ) { if ( ! strskip( next, ')', next ) ) { return CMD_ERR; } } if ( strskip( next, DELIMITER_CHAR, next ) ) { break; } } return CMD_OK; }
void CTorpedoProjectile::Draw() { if (model) { // do not draw if a 3D model has been defined for us return; } SColor col(60, 60, 100, 255); float3 r = dir.cross(UpVector); if (r.SqLength() < 0.001f) { r = float3(RgtVector); } r.Normalize(); const float3 u = dir.cross(r); const float h = 12; const float w = 2; inArray = true; va->EnlargeArrays(32, 0, VA_SIZE_TC); va->AddVertexQTC(drawPos + (r * w), texx, texy, col); va->AddVertexQTC(drawPos + (u * w), texx, texy, col); va->AddVertexQTC(drawPos + (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (u * w), texx, texy, col); va->AddVertexQTC(drawPos - (r * w), texx, texy, col); va->AddVertexQTC(drawPos - (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos - (r * w), texx, texy, col); va->AddVertexQTC(drawPos - (u * w), texx, texy, col); va->AddVertexQTC(drawPos - (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos - (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos - (u * w), texx, texy, col); va->AddVertexQTC(drawPos + (r * w), texx, texy, col); va->AddVertexQTC(drawPos + (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos - (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos + (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos - (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos - (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos - (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos - (u * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (r * w) + (dir * h), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); va->AddVertexQTC(drawPos + (dir * h * 1.2f), texx, texy, col); }
void GraphNodeCtr::pca_box_ctr() { IndexType boxid = 0; for ( unordered_map<IndexType,set<IndexType>>::iterator iter=label_bucket.begin(); iter!=label_bucket.end();iter++ ) { IndexType frame_label = iter->first; set<IndexType>& members = iter->second; IndexType frame = get_frame_from_key(frame_label); IndexType k=members.size(); MatrixX3 coords(k,3); Sample& smp = SampleSet::get_instance()[frame]; int j=0; for ( set<IndexType>::iterator m_iter=members.begin(); m_iter!=members.end(); m_iter++,j++ ) { coords.row(j)<<smp[*m_iter].x(),smp[*m_iter].y(),smp[*m_iter].z(); } MatrixX3 vert_mean = coords.colwise().mean(); MatrixX3 Q(k, 3); for ( IndexType j=0; j<k;j++) { Q.row(j) = coords.row(j) - vert_mean; } Matrix33 sigma = Q.transpose() * Q; Eigen::EigenSolver<Matrix33> eigen_solver(sigma, Eigen::ComputeFullU | Eigen::ComputeFullV); auto evec = eigen_solver.eigenvectors(); auto eval = eigen_solver.eigenvalues(); PCABox *new_space = allocator_.allocate<PCABox>(); box_bucket[frame_label] = new(new_space) PCABox; Matrix33 evecMat; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { evecMat(j,i) = (evec.col(i))(j).real(); } } MatrixX3 newCoor = Q * evecMat; Matrix23 minmax; minmax.setZero(); for (int i = 0;i<3;i++) { minmax(0,i) = newCoor.col(i).minCoeff(); minmax(1,i) = newCoor.col(i).maxCoeff(); } PCABox *pbox = box_bucket[frame_label]; for (int i=0;i<3;i++) { pbox->center(i) = (vert_mean.row(0))(i); } pbox->minPoint = minmax.row(0); pbox->maxPoint = minmax.row(1); PointType dis = pbox->maxPoint - pbox->minPoint; pbox->volume = dis(0,0) *dis(1,0)*dis(2.0); pbox->diagLen = sqrt(dis(0,0)*dis(0,0) + dis(1,0)*dis(1,0) + dis(2,0)*dis(2,0)); pbox->vtxSize = k; //Logger<<"boxes"<<boxid++<<endl; //Logger<<"box volume"<<pbox->volume<<endl; //Logger<<"box length"<<pbox->diagLen<<endl; //Logger<<"size"<<members.size()<<endl; } }
bool ArkanoidRemakeSdl::LoadFiles() { //Load music mSdlApp.MusicPath() = "../../data/music/"; mSdlApp.LoadMusic("silent-night-disco"); //mSdlApp.LoadMusic("music2"); //Load sound effects mSdlApp.SoundsPath() = "../../data/sound/"; mSdlApp.LoadSound("ballhit"); mSdlApp.LoadSound("balllost"); mSdlApp.LoadSound("brickhit"); mSdlApp.LoadSound("brickdestroy"); mSdlApp.LoadSound("bonus1"); mSdlApp.LoadSound("bonus2"); mSdlApp.LoadSound("bonus3"); mSdlApp.LoadSound("bonuslost"); mSdlApp.LoadSound("level_complete"); mSdlApp.SetMusicVolume(mConfig.MusicVolume); mSdlApp.SetSoundsVolume(mConfig.SoundsVolume); mSdlApp.SwitchAudio(mConfig.Audio); //Load fonts mSdlApp.FontsPath() = "../../data/font/"; //Open the font if( !mSdlApp.LoadFont("default", "Action_Man.ttf", 24) ) { return false; } //Load images mSdlApp.ImagesPath() = "../../data/images/"; if (!mSdlApp.LoadSurface(mSnowfallSurf,"snowfall.jpg")) return false; //mSdlApp.LoadSurface(mSnowfallSurf,"snowfall.jpg"); mSdlApp.NewSurface(mBkgndSurf, mSdlApp.WinWidth(), mSdlApp.WinHeight()); //SetBackground("snowfield1.jpg"); //Define mPlayAreaSurf mSdlApp.NewSurface( mPlayAreaSurf, mPlayArea.Size().X, mPlayArea.Size().Y ); if (!mSdlApp.ExistsSurface(mPlayAreaSurf)) return false; mSdlApp.LoadSurface("snowflake", "snowflake.png"); mSdlApp.LoadSurface("snowflake2", "snowflake2.png"); mSdlApp.LoadSurface("snowflake_1", "snowflake_1.png"); mSdlApp.LoadSurface("snowflake_2", "snowflake_2.png"); mSdlApp.LoadSurface("snowflake_3", "snowflake_3.png"); mSdlApp.LoadSurface("snowflake_4", "snowflake_4.png"); mSdlApp.LoadSurface("xmasball", "xmasball.png"); mSdlApp.LoadSurface("gift", "gift.png"); mSdlApp.LoadSurface("gift_red", "gift_red.png"); mSdlApp.LoadSurface(mShipSurf,"ship.png"); mSdlApp.LoadSurface(mBallSurf,"ball.png"); mSdlApp.SetupSurfMatrix(mBlockMatrixName,"blocksmatrix.png",11,3); //If there was an error in loading the image //if(mShipSurf == nullptr || ball == nullptr) // return false; // Text boxes creation sdltk::ColorRGBA col(80, 255, 255,255); sdltk::ColorRGBA shadow_col(0, 0, 0, 255 ); mSdlApp.CreateText("Score","default",col,shadow_col,2); mBall.Size().X = mSdlApp.GetSurfWidth(mBallSurf); mBall.Size().Y = mSdlApp.GetSurfHeight(mBallSurf); mShip.Size().X = mSdlApp.GetSurfWidth(mShipSurf); mShip.Size().Y = mSdlApp.GetSurfHeight(mShipSurf); mBall.Origin().X = -mBall.HSizeX(); mBall.Origin().Y = -mBall.HSizeY(); mShip.Origin().X = -mShip.HSizeX(); mShip.Origin().Y = -mShip.HSizeY(); // for each bonus set its origin based on the surface size // (its position will be set using its center) for (int i=0; i<(int)mBonus.size()-1; ++i) { mBonus[i].Origin()=-mBonus[i].HSize(); } //If everything loaded fine return true; }
std::vector<rectangle_t> detect_rectangles(image_t& img,filter_func_t fn,size_t tolerance) { h_decomp_t hd; std::vector<rectangle_t> rects; rgb_color_t col(255,0,0); if(!process_image(img,fn,col)) return rects; if(!do_h_decomposition(img,hd,col)) return rects; std::vector<edge_detection_t> edges; printf("[processing] apply approximate H/V edge detection with tolerance %u\n",tolerance); for(size_t i=0;i<hd.blocks.size();i++) { const size_t edge_detection_min_w=50; const v_block_decomp_t& b=hd.blocks[i]; edge_detection_t ed=do_approx_edge_detection(b,tolerance,edge_detection_min_w); printf("[processing] block %u: filtering artecfacts...",i); filter_edge_detection(ed.left); filter_edge_detection(ed.right); printf("[processing] %u segment left/%u segment right\n",ed.left.size(),ed.right.size()); if(ed.left.size()==1 && ed.right.size()==1) { edges.push_back(ed); continue; } printf("[processing block %u: complex decomposition: splitting...",i); size_t left=0,right=0; size_t nb_pieces=0; while(left!=ed.left.size() && right!=ed.right.size()) { // update left if necessary while(left<ed.left.size() && ed.left[left].end.y<=ed.right[right].orig.y) left++; if(left==ed.left.size()) break; // update right while(right<ed.right.size() && ed.right[right].end.y<=ed.left[left].orig.y) right++; if(right==ed.right.size()) break; // add to list edge_detection_t new_ed; new_ed.left.push_back(ed.left[left]); new_ed.right.push_back(ed.right[right]); // normalize size_t uy=std::max(new_ed.left[0].orig.y,new_ed.right[0].orig.y); size_t dy=std::min(new_ed.left[0].end.y,new_ed.right[0].end.y); new_ed.left[0].orig.y=new_ed.right[0].orig.y=uy; new_ed.left[0].end.y=new_ed.right[0].end.y=dy; new_ed.left[0].len=new_ed.right[0].len=dy-uy+1; edges.push_back(new_ed); nb_pieces++; // find first end if(ed.left[left].end.y<ed.right[right].end.y) left++; else right++; } printf("[processing] got %u pieces\n",nb_pieces); } for(size_t i=0;i<edges.size();i++) { const edge_detection_t ed=edges[i]; if(ed.left.size()==1 && ed.right.size()==1) { size_t up_y=std::max(ed.left[0].orig.y,ed.right[0].orig.y); size_t down_y=std::min(ed.left[0].end.y,ed.right[0].end.y); rectangle_t r; r.x=ed.left[0].orig.x; r.y=up_y; r.h=down_y-up_y+1; r.w=ed.right[0].orig.x-ed.left[0].orig.x+1; // doing an approximation: the really diameter is not the visible diameter const size_t min_w=30; if(r.w<=min_w) continue; // doing an approximation: the really diameter is not the visible diameter float ratio=float(r.w)/float(r.h); const float expected_ratio=2.3; const float max_ratio_delta=0.7; float perfect_division=expected_ratio/ratio; long nearest=lround(perfect_division); float delta=fabs(perfect_division-nearest); printf("[processing] perfect_div=%f delta=%f\n",perfect_division,delta); // doing some calculus gives us the following formula: // for each rectangle to be within range, one must have: // delta<H/W*max_ratio_delta if(delta<(r.h*max_ratio_delta/r.w)) { r.h/=nearest; //printf("[main] ratio=%f\n",float(r.w)/r.h); for(long j=0;j<nearest;j++) { r.y=up_y+j*r.h; add_rectangle(rects,r); } } else { long H=r.h; long Y=r.y; r.h=r.w/expected_ratio; nearest=floor(H/r.h); for(long i=0;i<nearest;i++) { r.y=Y+H-i*r.h; add_rectangle(rects,r); } } } else { printf("[processing] got non-standard edge decomposition: %u left, %u right. Give up...\n",ed.left.size(),ed.right.size()); } } return rects; }
Location ScannerBufferSource::loc() const { return Location(file(), line(), col()); }