コード例 #1
0
ファイル: Rocface.C プロジェクト: xyuan/IMPACT
void Rocface::transfer( const COM::DataItem *src, COM::DataItem *trg,
			const Real alpha, const int order, 
			Real *tol, int *iter, bool load) {
  typedef Transfer_traits<Source_type, Target_type, conserv>  Traits;

  std::string n1 = src->window()->name();
  std::string n2 = trg->window()->name();

  std::string wn1, wn2;
  get_name( n1, n2, wn1); get_name( n2, n1, wn2);
  
  TRS_Windows::iterator it1 = _trs_windows.find( wn1);
  TRS_Windows::iterator it2 = _trs_windows.find( wn2);

  if ( it1 == _trs_windows.end() || it2 == _trs_windows.end()) {
    std::cerr << "ROCFACE::ERROR: The overlay of window \"" << n1 
	      << "\" and window \"" << n2 << "\" does not exist"
	      << std::endl;
    RFC_assertion( false); MPI_Abort( MPI_COMM_WORLD, -1);
  }

  if ( !it1->second->replicated()) {
    it1->second->replicate_metadata( *it2->second);
  }

  Target_type tf( trg);
  Source_type sf( src);

  RFC_Window_transfer *w1=it1->second, *w2=it2->second;
  typename Traits::Transfer_type trans( w1, w2);

  // Print min, max, and integral before transfer
  if ( _ctrl.verb) {
    if ( w2->comm_rank()==0) {
      if (conserv) 
	std::cout << "ROCFACE: Conservatively transferring "; 
      else
	std::cout << "ROCFACE: Interpolating "; 
      std::cout << " from " << w1->name()+"."+src->name() 
		<< " to " << w2->name()+"."+trg->name() << std::endl; 
    }
    Vector_n min_v( sf.dimension()), max_v(sf.dimension());
    trans.minmax( *w1, sf, min_v, max_v);
    
    Vector_n integral(sf.dimension(),0);
    trans.integrate( *w1, sf, integral, order);
    
    if ( w1->comm_rank()==0) {
      std::cout << "ROCFACE: Before transfer\nROCFACE:\tminimum:  " << min_v
		<< "\nROCFACE:\tmaximum:  " << max_v;
      if ( !load) 
	std::cout << "\nROCFACE:\tintegral: " << std::setprecision(10)
		  << integral;
      std::cout << std::endl;
    }
  }

  // Perform data transfer
  Traits::transfer( trans, sf, tf, alpha, order, tol, iter, _ctrl.verb, load);

  // Print min, max, and integral after transfer
  if ( _ctrl.verb) {
    Vector_n min_v( sf.dimension()), max_v(sf.dimension());	
    trans.minmax( *w2, tf, min_v, max_v);
    
    Vector_n integral(sf.dimension(),0);			
    trans.integrate( *w2, tf, integral, order);
    
    if ( w2->comm_rank()==0) {
      std::cout << "ROCFACE: After transfer\nROCFACE:\tminimum:  " << min_v
		<< "\nROCFACE:\tmaximum:  " << max_v;
      if ( !load) 
	std::cout << "\nROCFACE:\tintegral: " << std::setprecision(10)
		  << integral;
      std::cout << std::endl;
    }
  }

  // Reset the tags, which indicate which nodes/elements should receive values
  w2->set_tags( NULL);
}
コード例 #2
0
void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event )
{
    int         id = event.GetId();
    wxFileName  fn;

    switch( id )
    {
    case ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG:
        m_show_layer_manager_tools = ! m_show_layer_manager_tools;
        m_auimgr.GetPane( wxT( "m_LayersManagerToolBar" ) ).Show( m_show_layer_manager_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
                                m_show_layer_manager_tools ?
                                _("Hide &Layers Manager" ) : _("Show &Layers Manager" ));
        break;

    case ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR:
        m_show_microwave_tools  = ! m_show_microwave_tools;
        m_auimgr.GetPane( wxT( "m_microWaveToolBar" ) ).Show( m_show_microwave_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR,
                                m_show_microwave_tools ?
                                _( "Hide Microwave Toolbar" ): _( "Show Microwave Toolbar" ));
        break;


    case ID_PCB_LAYERS_SETUP:
        if( InvokeLayerSetup( this, GetBoard() ) )
        {
            LAYER_ID cur_layer = GetActiveLayer();

            // If after showing the dialog the user has removed the active layer,
            // then select a new active layer (front copper layer).
            if( !GetBoard()->GetEnabledLayers()[ cur_layer ] )
                cur_layer = F_Cu;

            SetActiveLayer( cur_layer );

            OnModify();
            ReCreateLayerBox();
            ReFillLayerWidget();

            if( IsGalCanvasActive() )
                static_cast<PCB_DRAW_PANEL_GAL*>( GetGalCanvas() )->SyncLayersVisibility( GetBoard() );
        }
        break;

    case ID_PCB_LIB_WIZARD:
    case ID_PCB_LIB_TABLE_EDIT:
        {
            bool tableChanged = false;
            int r = 0;

            if( id == ID_PCB_LIB_TABLE_EDIT )
                r = InvokePcbLibTableEditor( this, &GFootprintTable, Prj().PcbFootprintLibs() );
            else
                r = InvokeFootprintWizard( this, &GFootprintTable, Prj().PcbFootprintLibs() );

            if( r & 1 )
            {
                try
                {
                    FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() );

                    GFootprintTable.Format( &sf, 0 );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving the global footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText.GetData() )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            // If no board file is defined, do not save the project specific library table.  It
            // is kept in memory and created in the path when the new board is saved.
            if( (r & 2) && !GetBoard()->GetFileName().IsEmpty() )
            {
                wxString    tblName   = Prj().FootprintLibTblName();

                try
                {
                    Prj().PcbFootprintLibs()->Save( tblName );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving project specific footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            FOOTPRINT_VIEWER_FRAME* viewer;

            if( tableChanged && (viewer = (FOOTPRINT_VIEWER_FRAME*)Kiway().Player( FRAME_PCB_MODULE_VIEWER, false )) != NULL )
            {
                viewer->ReCreateLibraryList();
            }
        }
        break;

    case ID_PCB_3DSHAPELIB_WIZARD:
#ifdef BUILD_GITHUB_PLUGIN
        Invoke3DShapeLibsDownloaderWizard( this );
#endif
        break;

    case ID_PCB_MASK_CLEARANCE:
        {
            DIALOG_PADS_MASK_CLEARANCE dlg( this );

            if( dlg.ShowModal() == 1 && IsGalCanvasActive() )
            {
                for( MODULE* module = GetBoard()->m_Modules; module; module = module->Next() )
                    module->ViewUpdate();

                GetGalCanvas()->Refresh();
            }
        }
        break;

    case wxID_PREFERENCES:
        {
            DIALOG_GENERALOPTIONS dlg( this );
            dlg.ShowModal();
        }
        break;

    case ID_PCB_PAD_SETUP:
        InstallPadOptionsFrame( NULL );
        break;

    case ID_CONFIG_SAVE:
        SaveProjectSettings( true );
        break;

    case ID_CONFIG_READ:
        {
            fn = GetBoard()->GetFileName();
            fn.SetExt( ProjectFileExtension );

            wxFileDialog dlg( this, _( "Read Project File" ), fn.GetPath(),
                              fn.GetFullName(), ProjectFileWildcard,
                              wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR );

            if( dlg.ShowModal() == wxID_CANCEL )
                break;

            if( !wxFileExists( dlg.GetPath() ) )
            {
                wxString msg = wxString::Format( _(
                        "File %s not found" ),
                        GetChars( dlg.GetPath() )
                        );
                DisplayError( this, msg );
                break;
            }

            wxString pro_file = dlg.GetPath();

            Prj().ConfigLoad( Kiface().KifaceSearch(), GROUP_PCB, GetProjectFileParameters(), pro_file );
        }
        break;

    // Hotkey IDs
    case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG:
        ExportHotkeyConfigToFile( g_Board_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_IMPORT_CONFIG:
        ImportHotkeyConfigFromFile( g_Board_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_EDITOR:
        InstallHotkeyFrame( this, g_Board_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST:
        // Display current hotkey list for Pcbnew.
        DisplayHotkeyList( this, g_Board_Editor_Hokeys_Descr );
        break;

    default:
        DisplayError( this, wxT( "PCB_EDIT_FRAME::Process_Config error" ) );
    }
}
コード例 #3
0
ファイル: file_md5_skel.cpp プロジェクト: bilbil/enhance
std::pair<bool, std::shared_ptr<file_md5_skel::skel_frame> > file_md5_skel::process_skel_frame( file_md5_anim::frame const & f, file_md5_anim::bound const & bbox, std::list<file_md5_anim::hierarchy> const & hier, std::list<file_md5_anim::baseframe> const & base ){
    if( hier.size() != base.size() ){
	assert( false && "hierarchy and baseframe size not equal" );
	return { false, {} };
    }
    std::shared_ptr<skel_frame> sf( new skel_frame );
    sf->_joints.resize( hier.size() );
    
    auto it_hier = hier.begin();
    auto it_base = base.begin();
    int index_current_joint = 0;
    while( it_hier != hier.end() ){
	int frame_data_start_index = it_hier->_start_index;
	int flag = it_hier->_flags;
	//obtain rotation and position from base frame
	float sf_pos[3];
	float sf_rot[3];
	for( int i = 0; i < 3; ++i ){
	    sf_pos[i] = it_base->_pos[i];
	    sf_rot[i] = it_base->_orient[i];
	}
	int offset = 0;
	//update rotation and position from frame data if neccessary
	for( int i = 0; i < 3; ++i ){
	    if( flag & (1<<i) ){
		if( frame_data_start_index + offset >= f._data.size() ){
		    assert( false && "index access out of range" );
		    return { false, {} };
		}
		sf_pos[i] = f._data[ frame_data_start_index + offset ];
		++offset;
	    }
	}
	for( int i = 0; i < 3; ++i ){
	    if( flag & (8<<i) ){
		if( frame_data_start_index + offset >= f._data.size() ){
		    assert( false && "index access out of range" );
		    return { false, {} };
		}
		sf_rot[i] = f._data[ frame_data_start_index + offset ];
		++offset;
	    }
	}
	
	//compute rotation quaternion
	Quat sf_orient( sf_rot[0], sf_rot[1], sf_rot[2] );
	sf_orient.NormalizeQuatCurrent();

	int parent_joint_index = it_hier->_parent;

	std::shared_ptr<joint_frame> jf( new joint_frame );
	jf->_parent = parent_joint_index;
	jf->_name = it_hier->_name;

	if( parent_joint_index >= 0 ){
	    if( parent_joint_index >= sf->_joints.size() ){
		assert( false && "parent joint index out of range." );
		return { false, {} };
	    }
	    std::shared_ptr<joint_frame> parent_joint_frame = sf->_joints[ parent_joint_index ];
	    //chain transformation from parent joint

	    //update positions
	    Quat qpos( sf_pos[0], sf_pos[1], sf_pos[2], 0.0f );
	    Quat orient_inv = parent_joint_frame->_orient.Inverse();
	    orient_inv.NormalizeQuatCurrent();
	    Quat res = parent_joint_frame->_orient * qpos * orient_inv;
	    for( int i = 0; i < 3; ++i ){
		jf->_pos[i] = parent_joint_frame->_pos[i] + res._quat[i];
	    }

	    //update orientation
	    jf->_orient = parent_joint_frame->_orient * sf_orient;
	    jf->_orient.NormalizeQuatCurrent();
	}else{
	    //no parent, root joint
	    for( int i = 0; i < 3; ++i ){
		jf->_pos[i] = sf_pos[i];
	    }
	    jf->_orient = sf_orient;
	    jf->_orient.NormalizeQuatCurrent();
	}
	// sf->_joints.push_back( jf );
	sf->_joints[ index_current_joint ] = jf;
	++it_hier;
	++it_base;
	++index_current_joint;
    }
    for( int i = 0; i < 3; ++i ){
	sf->_bbox_lower[i] = bbox._min[i];
	sf->_bbox_upper[i] = bbox._max[i];
    }
    return { true, sf };
}
コード例 #4
0
void Foam::BlockLduMatrix<Type>::segregateB
(
    TypeField& sMul,
    const TypeField& x
) const
{
    typedef typename TypeCoeffField::linearType linearType;
    typedef typename TypeCoeffField::squareType squareType;

    typedef typename TypeCoeffField::linearTypeField linearTypeField;
    typedef typename TypeCoeffField::squareTypeField squareTypeField;

    const unallocLabelList& u = lduAddr().upperAddr();
    const unallocLabelList& l = lduAddr().lowerAddr();

    // Diagonal multiplication
    if (thereIsDiag())
    {
        if (diag().activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeDiag = this->diag().asSquare();
            linearTypeField lf(activeDiag.size());
            squareTypeField sf(activeDiag.size());

            // Expand and contract
            contractLinear(lf, activeDiag);
            expandLinear(sf, lf);

            sMul -= (activeDiag - sf) & x;
        }
    }

    // Lower multiplication

    if (thereIsLower())
    {
        if (lower().activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeLower = this->lower().asSquare();

            // Auxiliary variables used in expand/contract
            linearType lt;
            squareType st;

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                contractLinear(lt, activeLower[coeffI]);
                expandLinear(st, lt);

                sMul[u[coeffI]] -= (activeLower[coeffI] - st) & x[l[coeffI]];
            }
        }
    }

    // Upper multiplication

    if (thereIsUpper())
    {
        if (upper().activeType() == blockCoeffBase::SQUARE)
        {
            const squareTypeField& activeUpper = this->upper().asSquare();

            // Auxiliary variables used in expand/contract
            linearType lt;
            squareType st;

            for (register label coeffI = 0; coeffI < u.size(); coeffI++)
            {
                contractLinear(lt, activeUpper[coeffI]);
                expandLinear(st, lt);

                sMul[l[coeffI]] -= (activeUpper[coeffI] - st) & x[u[coeffI]];
            }

            // If the matrix is symmetric, the lower triangular product
            // is also needed
            if (symmetric())
            {
                for (register label coeffI = 0; coeffI < u.size(); coeffI++)
                {
                    // Use transpose upper coefficient
                    contractLinear(lt, activeUpper[coeffI]);
                    expandLinear(st, lt);
                    sMul[u[coeffI]] -=
                        (activeUpper[coeffI].T() - st) & x[l[coeffI]];
                }
            }
        }
    }
}
コード例 #5
0
int main(int argc, char* argv[])
{
    if (argc < 2) {
        printf("Usage: %s <program name>\n", argv[0]);
        exit(0);
    }
    filename = argv[1];
    FILE* fp = fopen(filename, "rb");
    if (fp == 0)
        error("opening");
    ram = (Byte*)malloc(0x10000);
    memset(ram, 0, 0x10000);
    if (ram == 0) {
        fprintf(stderr, "Out of memory\n");
        exit(1);
    }
    if (fseek(fp, 0, SEEK_END) != 0)
        error("seeking");
    length = ftell(fp);
    if (length == -1)
        error("telling");
    if (fseek(fp, 0, SEEK_SET) != 0)
        error("seeking");
    if (length > 0x10000 - 0x100) {
        fprintf(stderr, "%s is too long to be a .com file\n", filename);
        exit(1);
    }
    if (fread(&ram[0x100], length, 1, fp) != 1)
        error("reading");
    fclose(fp);

    Word segment = 0x1000;
    setAX(0x0000);
    setCX(0x00FF);
    setDX(segment);
    registers[3] = 0x0000;
    setSP(0xFFFE);
    registers[5] = 0x091C;
    setSI(0x0100);
    setDI(0xFFFE);
    for (int i = 0; i < 4; ++i)
        registers[8 + i] = segment;

    Byte* byteData = (Byte*)&registers[0];
    int bigEndian = (byteData[2] == 0 ? 1 : 0);
    int byteNumbers[8] = {0, 2, 4, 6, 1, 3, 5, 7};
    for (int i = 0 ; i < 8; ++i)
      byteRegisters[i] = &byteData[byteNumbers[i] ^ bigEndian];

    bool prefix = false;
    for (int i = 0; i < 1000000000; ++i) {
        if (!repeating) {
            if (!prefix) {
                segmentOverride = -1;
                rep = 0;
            }
            prefix = false;
            opcode = fetchByte();
        }
        wordSize = ((opcode & 1) != 0);
        bool sourceIsRM = ((opcode & 2) != 0);
        int operation = (opcode >> 3) & 7;
        bool jump;
        switch (opcode) {
            case 0x00: case 0x01: case 0x02: case 0x03:
            case 0x08: case 0x09: case 0x0a: case 0x0b:
            case 0x10: case 0x11: case 0x12: case 0x13:
            case 0x18: case 0x19: case 0x1a: case 0x1b:
            case 0x20: case 0x21: case 0x22: case 0x23:
            case 0x28: case 0x29: case 0x2a: case 0x2b:
            case 0x30: case 0x31: case 0x32: case 0x33:
            case 0x38: case 0x39: case 0x3a: case 0x3b:  // alu rmv,rmv
                data = readEA();
                if (!sourceIsRM) {
                    destination = data;
                    source = getReg();
                }
                else {
                    destination = getReg();
                    source = data;
                }
                aluOperation = operation;
                doALUOperation();
                if (aluOperation != 7) {
                    if (!sourceIsRM)
                        finishWriteEA(data);
                    else
                        setReg(data);
                }
                break;
            case 0x04: case 0x05: case 0x0c: case 0x0d:
            case 0x14: case 0x15: case 0x1c: case 0x1d:
            case 0x24: case 0x25: case 0x2c: case 0x2d:
            case 0x34: case 0x35: case 0x3c: case 0x3d:  // alu accum,i
                destination = getAccum();
                source = !wordSize ? fetchByte() : fetchWord();
                aluOperation = operation;
                doALUOperation();
                if (aluOperation != 7)
                    setAccum();
                break;
            case 0x06: case 0x0e: case 0x16: case 0x1e:  // PUSH segreg
                push(registers[operation + 8]);
                break;
            case 0x07: case 0x17: case 0x1f:  // POP segreg
                registers[operation + 8] = pop();
                break;
            case 0x26: case 0x2e: case 0x36: case 0x3e:  // segment override
                segmentOverride = operation;
                prefix = true;
                break;
            case 0x27: case 0x2f:  // DA
                if (af() || (al() & 0x0f) > 9) {
                    data = al() + (opcode == 0x27 ? 6 : -6);
                    setAL(data);
                    setAF(true);
                    if ((data & 0x100) != 0)
                        setCF(true);
                }
                setCF(cf() || al() > 0x9f);
                if (cf())
                    setAL(al() + (opcode == 0x27 ? 0x60 : -0x60));
                wordSize = false;
                data = al();
                setPZS();
                break;
            case 0x37: case 0x3f:  // AA
                if (af() || (al() & 0xf) > 9) {
                    setAL(al() + (opcode == 0x37 ? 6 : -6));
                    setAH(ah() + (opcode == 0x37 ? 1 : -1));
                    setCA();
                }
                else
                    clearCA();
                setAL(al() & 0x0f);
                break;
            case 0x40: case 0x41: case 0x42: case 0x43:
            case 0x44: case 0x45: case 0x46: case 0x47:
            case 0x48: case 0x49: case 0x4a: case 0x4b:
            case 0x4c: case 0x4d: case 0x4e: case 0x4f:  // incdec rw
                destination = rw();
                wordSize = true;
                setRW(incdec((opcode & 8) != 0));
                break;
            case 0x50: case 0x51: case 0x52: case 0x53:
            case 0x54: case 0x55: case 0x56: case 0x57:  // PUSH rw
                push(rw());
                break;
            case 0x58: case 0x59: case 0x5a: case 0x5b:
            case 0x5c: case 0x5d: case 0x5e: case 0x5f:  // POP rw
                setRW(pop());
                break;
            case 0x60: case 0x61: case 0x62: case 0x63:
            case 0x64: case 0x65: case 0x66: case 0x67:
            case 0x68: case 0x69: case 0x6a: case 0x6b:
            case 0x6c: case 0x6d: case 0x6e: case 0x6f:
            case 0xc0: case 0xc1: case 0xc8: case 0xc9:  // invalid
            case 0xcc: case 0xf0: case 0xf1: case 0xf4:  // INT 3, LOCK, HLT
            case 0x9b: case 0xce: case 0x0f:  // WAIT, INTO, POP CS
            case 0xd8: case 0xd9: case 0xda: case 0xdb:
            case 0xdc: case 0xdd: case 0xde: case 0xdf:  // escape
            case 0xe4: case 0xe5: case 0xe6: case 0xe7:
            case 0xec: case 0xed: case 0xee: case 0xef:  // IN, OUT
                fprintf(stderr, "Invalid opcode %02x", opcode);
                runtimeError("");
                break;
            case 0x70: case 0x71: case 0x72: case 0x73:
            case 0x74: case 0x75: case 0x76: case 0x77:
            case 0x78: case 0x79: case 0x7a: case 0x7b:
            case 0x7c: case 0x7d: case 0x7e: case 0x7f:  // Jcond cb
                switch (opcode & 0x0e) {
                    case 0x00: jump = of(); break;
                    case 0x02: jump = cf(); break;
                    case 0x04: jump = zf(); break;
                    case 0x06: jump = cf() || zf(); break;
                    case 0x08: jump = sf(); break;
                    case 0x0a: jump = pf(); break;
                    case 0x0c: jump = sf() != of(); break;
                    default:   jump = sf() != of() || zf(); break;
                }
                jumpShort(fetchByte(), jump == ((opcode & 1) == 0));
                break;
            case 0x80: case 0x81: case 0x82: case 0x83:  // alu rmv,iv
                destination = readEA();
                data = fetch(opcode == 0x81);
                if (opcode != 0x83)
                    source = data;
                else
                    source = signExtend(data);
                aluOperation = modRMReg();
                doALUOperation();
                if (aluOperation != 7)
                    finishWriteEA(data);
                break;
            case 0x84: case 0x85:  // TEST rmv,rv
                data = readEA();
                test(data, getReg());
                break;
            case 0x86: case 0x87:  // XCHG rmv,rv
                data = readEA();
                finishWriteEA(getReg());
                setReg(data);
                break;
            case 0x88: case 0x89:  // MOV rmv,rv
                ea();
                finishWriteEA(getReg());
                break;
            case 0x8a: case 0x8b:  // MOV rv,rmv
                setReg(readEA());
                break;
            case 0x8c:  // MOV rmw,segreg
                ea();
                wordSize = 1;
                finishWriteEA(registers[modRMReg() + 8]);
                break;
            case 0x8d:  // LEA
                address = ea();
                if (!useMemory)
                    runtimeError("LEA needs a memory address");
                setReg(address);
                break;
            case 0x8e:  // MOV segreg,rmw
                wordSize = 1;
                data = readEA();
                registers[modRMReg() + 8] = data;
                break;
            case 0x8f:  // POP rmw
                writeEA(pop());
                break;
            case 0x90: case 0x91: case 0x92: case 0x93:
            case 0x94: case 0x95: case 0x96: case 0x97:  // XCHG AX,rw
                data = ax();
                setAX(rw());
                setRW(data);
                break;
            case 0x98:  // CBW
                setAX(signExtend(al()));
                break;
            case 0x99:  // CWD
                setDX((ax() & 0x8000) == 0 ? 0x0000 : 0xffff);
                break;
            case 0x9a:  // CALL cp
                savedIP = fetchWord();
                savedCS = fetchWord();
                farCall();
                break;
            case 0x9c:  // PUSHF
                push((flags & 0x0fd7) | 0xf000);
                break;
            case 0x9d:  // POPF
                flags = pop() | 2;
                break;
            case 0x9e:  // SAHF
                flags = (flags & 0xff02) | ah();
                break;
            case 0x9f:  // LAHF
                setAH(flags & 0xd7);
                break;
            case 0xa0: case 0xa1:  // MOV accum,xv
                data = read(fetchWord());
                setAccum();
                break;
            case 0xa2: case 0xa3:  // MOV xv,accum
                write(getAccum(), fetchWord());
                break;
            case 0xa4: case 0xa5:  // MOVSv
                stoS(lodS());
                doRep();
                break;
            case 0xa6: case 0xa7:  // CMPSv
                lodDIS();
                source = data;
                sub();
                doRep();
                break;
            case 0xa8: case 0xa9:  // TEST accum,iv
                data = fetch(wordSize);
                test(getAccum(), data);
                break;
            case 0xaa: case 0xab:  // STOSv
                stoS(getAccum());
                doRep();
                break;
            case 0xac: case 0xad:  // LODSv
                data = lodS();
                setAccum();
                doRep();
                break;
            case 0xae: case 0xaf:  // SCASv
                lodDIS();
                destination = getAccum();
                source = data;
                sub();
                doRep();
                break;
            case 0xb0: case 0xb1: case 0xb2: case 0xb3:
            case 0xb4: case 0xb5: case 0xb6: case 0xb7:
                setRB(fetchByte());
                break;
            case 0xb8: case 0xb9: case 0xba: case 0xbb:
            case 0xbc: case 0xbd: case 0xbe: case 0xbf:  // MOV rv,iv
                setRW(fetchWord());
                break;
            case 0xc2: case 0xc3: case 0xca: case 0xcb:  // RET
                savedIP = pop();
                savedCS = (opcode & 8) == 0 ? cs() : pop();
                if (!wordSize)
                    setSP(sp() + fetchWord());
                farJump();
                break;
            case 0xc4: case 0xc5:  // LES/LDS
                ea();
                farLoad();
                *modRMRW() = savedIP;
                registers[8 + (!wordSize ? 0 : 3)] = savedCS;
                break;
            case 0xc6: case 0xc7:  // MOV rmv,iv
                ea();
                finishWriteEA(fetch(wordSize));
                break;
            case 0xcd:
                data = fetchByte();
                if (data != 0x21) {
                    fprintf(stderr, "Unknown interrupt 0x%02x", data);
                    runtimeError("");
                }
                switch (ah()) {
                    case 2:
                        printf("%c", dl());
                        break;
                    case 0x4c:
                        printf("*** Bytes: %i\n", length);
		        printf("*** Cycles: %i\n", ios);
                        printf("*** EXIT code %i\n", al());
                        exit(0);
                        break;
                    default:
                        fprintf(stderr, "Unknown DOS call 0x%02x", data);
                        runtimeError("");
                }
                break;
            case 0xcf:
                ip = pop();
                setCS(pop());
                flags = pop() | 2;
                break;
            case 0xd0: case 0xd1: case 0xd2: case 0xd3:  // rot rmv,n
                data = readEA();
                if ((opcode & 2) == 0)
                    source = 1;
                else
                    source = cl();
                while (source != 0) {
                    destination = data;
                    switch (modRMReg()) {
                        case 0:  // ROL
                            data <<= 1;
                            doCF();
                            data |= (cf() ? 1 : 0);
                            setOFRotate();
                            break;
                        case 1:  // ROR
                            setCF((data & 1) != 0);
                            data >>= 1;
                            if (cf())
                                data |= (!wordSize ? 0x80 : 0x8000);
                            setOFRotate();
                            break;
                        case 2:  // RCL
                            data = (data << 1) | (cf() ? 1 : 0);
                            doCF();
                            setOFRotate();
                            break;
                        case 3:  // RCR
                            data >>= 1;
                            if (cf())
                                data |= (!wordSize ? 0x80 : 0x8000);
                            setCF((destination & 1) != 0);
                            setOFRotate();
                            break;
                        case 4:  // SHL
                        case 6:
                            data <<= 1;
                            doCF();
                            setOFRotate();
                            setPZS();
                            break;
                        case 5:  // SHR
                            setCF((data & 1) != 0);
                            data >>= 1;
                            setOFRotate();
                            setAF(true);
                            setPZS();
                            break;
                        case 7:  // SAR
                            setCF((data & 1) != 0);
                            data >>= 1;
                            if (!wordSize)
                                data |= (destination & 0x80);
                            else
                                data |= (destination & 0x8000);
                            setOFRotate();
                            setAF(true);
                            setPZS();
                            break;
                    }
                    --source;
                }
                finishWriteEA(data);
                break;
            case 0xd4:  // AAM
                data = fetchByte();
                if (data == 0)
                    divideOverflow();
                setAH(al() / data);
                setAL(al() % data);
                wordSize = true;
                setPZS();
                break;
            case 0xd5:  // AAD
                data = fetchByte();
                setAL(al() + ah()*data);
                setAH(0);
                setPZS();
                break;
            case 0xd6:  // SALC
                setAL(cf() ? 0xff : 0x00);
                break;
            case 0xd7:  // XLATB
                setAL(readByte(bx() + al()));
                break;
            case 0xe0: case 0xe1: case 0xe2:  // LOOPc cb
                setCX(cx() - 1);
                jump = (cx() != 0);
                switch (opcode) {
                    case 0xe0: if (zf()) jump = false; break;
                    case 0xe1: if (!zf()) jump = false; break;
                }
                jumpShort(fetchByte(), jump);
                break;
            case 0xe3:  // JCXZ cb
                jumpShort(fetchByte(), cx() == 0);
                break;
            case 0xe8:  // CALL cw
                call(ip + fetchWord());
                break;
            case 0xe9:  // JMP cw
                ip += fetchWord();
                break;
            case 0xea:  // JMP cp
                savedIP = fetchWord();
                savedCS = fetchWord();
                farJump();
                break;
            case 0xeb:  // JMP cb
                jumpShort(fetchByte(), true);
                break;
            case 0xf2: case 0xf3:  // REP
                rep = opcode == 0xf2 ? 1 : 2;
                prefix = true;
                break;
            case 0xf5:  // CMC
                flags ^= 1;
                break;
            case 0xf6: case 0xf7:  // math rmv
                data = readEA();
                switch (modRMReg()) {
                    case 0: case 1:  // TEST rmv,iv
                        test(data, fetch(wordSize));
                        break;
                    case 2:  // NOT iv
                        finishWriteEA(~data);
                        break;
                    case 3:  // NEG iv
                        source = data;
                        destination = 0;
                        sub();
                        finishWriteEA(data);
                        break;
                    case 4: case 5:  // MUL rmv, IMUL rmv
                        source = data;
                        destination = getAccum();
                        data = destination;
                        setSF();
                        setPF();
                        data *= source;
                        setAX(data);
                        if (!wordSize) {
                            if (modRMReg() == 4)
                                setCF(ah() != 0);
                            else {
                                if ((source & 0x80) != 0)
                                    setAH(ah() - destination);
                                if ((destination & 0x80) != 0)
                                    setAH(ah() - source);
                                setCF(ah() ==
                                    ((al() & 0x80) == 0 ? 0 : 0xff));
                            }
                        }
                        else {
                            setDX(data >> 16);
                            if (modRMReg() == 4) {
                                data |= dx();
                                setCF(dx() != 0);
                            }
                            else {
                                if ((source & 0x8000) != 0)
                                    setDX(dx() - destination);
                                if ((destination & 0x8000) != 0)
                                    setDX(dx() - source);
                                data |= dx();
                                setCF(dx() ==
                                    ((ax() & 0x8000) == 0 ? 0 : 0xffff));
                            }
                        }
                        setZF();
                        setOF(cf());
                        break;
                    case 6: case 7:  // DIV rmv, IDIV rmv
                        source = data;
                        if (source == 0)
                            divideOverflow();
                        if (!wordSize) {
                            destination = ax();
                            if (modRMReg() == 6) {
                                div();
                                if (data > 0xff)
                                    divideOverflow();
                            }
                            else {
                                destination = ax();
                                if ((destination & 0x8000) != 0)
                                    destination |= 0xffff0000;
                                source = signExtend(source);
                                div();
                                if (data > 0x7f && data < 0xffffff80)
                                    divideOverflow();
                            }
                            setAH(remainder);
                            setAL(data);
                        }
                        else {
                            destination = (dx() << 16) + ax();
                            div();
                            if (modRMReg() == 6) {
                                if (data > 0xffff)
                                    divideOverflow();
                            }
                            else {
                                if (data > 0x7fff && data < 0xffff8000)
                                    divideOverflow();
                            }
                            setDX(remainder);
                            setAX(data);
                        }
                        break;
                }
                break;
            case 0xf8: case 0xf9:  // STC/CLC
                setCF(wordSize);
                break;
            case 0xfa: case 0xfb:  // STI/CLI
                setIF(wordSize);
                break;
            case 0xfc: case 0xfd:  // STD/CLD
                setDF(wordSize);
                break;
            case 0xfe: case 0xff:  // misc
                ea();
                if ((!wordSize && modRMReg() >= 2 && modRMReg() <= 6) ||
                    modRMReg() == 7) {
                    fprintf(stderr, "Invalid instruction %02x %02x", opcode,
                        modRM);
                    runtimeError("");
                }
                switch (modRMReg()) {
                    case 0: case 1:  // incdec rmv
                        destination = readEA2();
                        finishWriteEA(incdec(modRMReg() != 0));
                        break;
                    case 2:  // CALL rmv
                        call(readEA2());
                        break;
                    case 3:  // CALL mp
                        farLoad();
                        farCall();
                        break;
                    case 4:  // JMP rmw
                        ip = readEA2();
                        break;
                    case 5:  // JMP mp
                        farLoad();
                        farJump();
                        break;
                    case 6:  // PUSH rmw
                        push(readEA2());
                        break;
                }
                break;
        }
    }
    runtimeError("Timed out");
}
コード例 #6
0
/// Do one iteration.
bool LevenbergMarquardtMDMinimizer::iterate(size_t) {
  const bool debug = getProperty("Debug");
  const double muMax = getProperty("MuMax");
  const double absError = getProperty("AbsError");

  if (!m_leastSquares) {
    throw std::runtime_error("Cost function isn't set up.");
  }
  size_t n = m_leastSquares->nParams();

  if (n == 0) {
    m_errorString = "No parameters to fit.";
    g_log.information(m_errorString);
    return false;
  }

  if (m_mu > muMax) {
    // m_errorString = "Failed to converge, maximum mu reached";
    // g_log.warning() << m_errorString << std::endl;
    return false;
  }

  // calculate the first and second derivatives of the cost function.
  if (m_mu == 0.0 || m_rho > 0) {
    // calculate everything first time or 
    // if last iteration was good
    m_F = m_leastSquares->valDerivHessian();
  }
  // else if m_rho < 0 last iteration was bad: reuse m_der and m_hessian

  // Calculate damping to hessian
  if (m_mu == 0) // first iteration or accidental zero
  {
    m_mu = m_tau;
    m_nu = 2.0;
  }

  if (debug) {
    g_log.warning()
        << "==========================================================="
        << std::endl;
    g_log.warning() << "mu=" << m_mu << std::endl << std::endl;
  }

  if (m_D.empty()) {
    m_D.resize(n);
  }

  // copy the hessian
  GSLMatrix H(m_leastSquares->getHessian());
  GSLVector dd(m_leastSquares->getDeriv());

  // scaling factors
  std::vector<double> sf(n);

  for (size_t i = 0; i < n; ++i) {
    double d = fabs(dd.get(i));
    if (m_D[i] > d)
      d = m_D[i];
    m_D[i] = d;
    double tmp = H.get(i, i) + m_mu * d;
    H.set(i, i, tmp);
    sf[i] = sqrt(tmp);
    if (tmp == 0.0) {
      m_errorString = "Singular matrix.";
      g_log.information(m_errorString);
      return false;
    }
  }

  // apply scaling
  for (size_t i = 0; i < n; ++i) {
    double d = dd.get(i);
    dd.set(i, d / sf[i]);
    for (size_t j = i; j < n; ++j) {
      const double f = sf[i] * sf[j];
      double tmp = H.get(i, j);
      H.set(i, j, tmp / f);
      if (i != j) {
        tmp = H.get(j, i);
        H.set(j, i, tmp / f);
      }
    }
  }

  if (debug && m_rho > 0) {
    g_log.warning() << "Hessian:\n" << H;
    g_log.warning() << "Right-hand side:\n";
    for (size_t j = 0; j < n; ++j) {
      g_log.warning() << dd.get(j) << ' ';
    }
    g_log.warning() << std::endl;
    g_log.warning() << "Determinant=" << H.det() << std::endl;
  }

  // Parameter corrections
  GSLVector dx(n);
  // To find dx solve the system of linear equations   H * dx == -m_der
  dd *= -1.0;
  H.solve(dd, dx);

  if (debug) {
    g_log.warning() << "\nScaling factors:" << std::endl;
    for (size_t j = 0; j < n; ++j) {
      g_log.warning() << sf[j] << ' ';
    }
    g_log.warning() << std::endl;
    g_log.warning() << "Corrections:" << std::endl;
    for (size_t j = 0; j < n; ++j) {
      g_log.warning() << dx.get(j) << ' ';
    }
    g_log.warning() << std::endl << std::endl;
  }

  // restore scaling
  for (size_t i = 0; i < n; ++i) {
    double d = dx.get(i);
    dx.set(i, d / sf[i]);
    d = dd.get(i);
    dd.set(i, d * sf[i]);
  }

  // save previous state
  m_leastSquares->push();
  // Update the parameters of the cost function.
  for (size_t i = 0; i < n; ++i) {
    double d = m_leastSquares->getParameter(i) + dx.get(i);
    m_leastSquares->setParameter(i, d);
    if (debug) {
      g_log.warning() << "Parameter(" << i << ")=" << d << std::endl;
    }
  }
  m_leastSquares->getFittingFunction()->applyTies();

  // --- prepare for the next iteration --- //

  double dL;
  // der -> - der - 0.5 * hessian * dx
  gsl_blas_dgemv(CblasNoTrans, -0.5, m_leastSquares->getHessian().gsl(),
                 dx.gsl(), 1., dd.gsl());
  // calculate the linear part of the change in cost function
  // dL = - der * dx - 0.5 * dx * hessian * dx
  gsl_blas_ddot(dd.gsl(), dx.gsl(), &dL);

  double F1 = m_leastSquares->val();
  if (debug) {
    g_log.warning() << std::endl;
    g_log.warning() << "Old cost function " << m_F << std::endl;
    g_log.warning() << "New cost function " << F1 << std::endl;
    g_log.warning() << "Linear part " << dL << std::endl;
  }

  // Try the stop condition
  if (m_rho >= 0) {
    GSLVector p(n);
    m_leastSquares->getParameters(p);
    double dx_norm = gsl_blas_dnrm2(dx.gsl());
    if (dx_norm < absError) {
      if (debug) {
        g_log.warning() << "Successful fit, parameters changed by less than "
                        << absError << std::endl;
      }
      return false;
    }
    if (m_rho == 0) {
      if (m_F != F1) {
        this->m_errorString = "Failed to converge, rho == 0";
        g_log.warning() << m_errorString << std::endl;
      }
      if (debug) {
        g_log.warning() << "Successful fit, cost function didn't change."
                        << std::endl;
      }
      return false;
    }
  }

  if (fabs(dL) == 0.0) {
    if (m_F == F1)
      m_rho = 1.0;
    else
      m_rho = 0;
  } else {
    m_rho = (m_F - F1) / dL;
    if (m_rho == 0) {
      return false;
    }
  }
  if (debug) {
    g_log.warning() << "rho=" << m_rho << std::endl;
  }

  if (m_rho > 0) { // good progress, decrease m_mu but no more than by 1/3
    // rho = 1 - (2*rho - 1)^3
    m_rho = 2.0 * m_rho - 1.0;
    m_rho = 1.0 - m_rho * m_rho * m_rho;
    const double I3 = 1.0 / 3.0;
    if (m_rho > I3)
      m_rho = I3;
    if (m_rho < 0.0001)
      m_rho = 0.1;
    m_mu *= m_rho;
    m_nu = 2.0;
    m_F = F1;
    if (debug) {
      g_log.warning() << "Good iteration, accept new parameters." << std::endl;
      g_log.warning() << "rho=" << m_rho << std::endl;
    }
    // drop saved state, accept new parameters
    m_leastSquares->drop();
  } else { // bad iteration. increase m_mu and revert changes to parameters
    m_mu *= m_nu;
    m_nu *= 2.0;
    // undo parameter update
    m_leastSquares->pop();
    m_F = m_leastSquares->val();
    if (debug) {
      g_log.warning()
          << "Bad iteration, increase mu and revert changes to parameters."
          << std::endl;
    }
  }

  return true;
}
コード例 #7
0
ファイル: CJournal.cpp プロジェクト: Ivor23/coolfluid3
void CJournal::execute_signals (const boost::filesystem::path & filename)
{


  if (m_root.expired())
    throw IllegalCall(FromHere(), "Component \'" + name() + "\' has no root");

  boost::shared_ptr<XmlDoc> xmldoc = XML::parse_file(filename);
  XmlNode doc_node = Protocol::goto_doc_node(*xmldoc.get());
//  rapidxml::xml_node * signals_map = doc_node.content->first_node();
//  bool found_map = false;
  rapidxml::xml_node<>* node = nullptr;
//  rapidxml::xml_attribute<>* key_attr = nullptr;
  CRoot& root = Core::instance().root();
  const char * frame_tag = Protocol::Tags::node_frame();

  XmlNode signal_map = Map(doc_node).find_value( Protocol::Tags::key_signals() );

//  for( ; signals_map != nullptr ; signals_map = signals_map->next_sibling())
//  {
//    key_attr = signals_map->first_attribute("key");
//    found_map = key_attr != nullptr && std::strcmp(key_attr->value(), "signals") == 0;

//    if(found_map)
//      break;
//  }

  if( !signal_map.is_valid() )
    throw XmlError(FromHere(), "Could not find \'signals\' map.");

  node = signal_map.content->first_node( frame_tag );

  for( ; node != nullptr ; node = node->next_sibling(frame_tag) )
  {
    rapidxml::xml_attribute<>* type_attr = node->first_attribute("type");

    if(type_attr != nullptr && std::strcmp(type_attr->value(), "signal") == 0)
    {
      rapidxml::xml_attribute<>* target_attr = node->first_attribute("target");
      rapidxml::xml_attribute<>* receiver_attr = node->first_attribute("receiver");

      std::string target = target_attr != nullptr ? target_attr->value() : "";
      std::string receiver = receiver_attr != nullptr ? receiver_attr->value() : "";

      if(target.empty())
        CFwarn << "Warning: missing or empty target. Skipping this signal." << CFendl;

      if(receiver.empty())
        CFwarn << "Warning: missing or empty receiver. Skipping this signal." << CFendl;

      if(receiver == "//Root/Core") // server specific component
        continue;

      try
      {
        SignalFrame sf(node);
        root.retrieve_component(receiver)->call_signal(target, sf);
      }
      catch(Exception & e)
      {
        CFerror << e.what() << CFendl;
      }

    }
  }

}
コード例 #8
0
ファイル: run.cpp プロジェクト: jbarakat/ves_tapered
int main(){
	int    i, j, k, l;
	int    n    = 14;			// size of solution vector
	int    m    = 103;		// number of shooting points
	int    maxiter = 251;	// maximum number of iterations
	double tol = 1e-8;		// tolerance
	int    nrk;						// number of Runge-Kutta steps
	int    flag;					// error flag
	bool   info;					// boolean for file check

	int    redvol;				// reduced volume
	int    tubrad;				// tube radius at x = 0 (COM at t = 0)
	int    tapang;				// taper angle
	int    benmod;        // bending modulus
	int    compos;        // center-of-mass axial position

	// output directory
	string opath = "../output";

	// abscissa, source, and solution vectors
	vector<double> t(m), u(m,0.0), si(n*m), sm(n*m), sf(n*m);

	// timestep
	double ts, dts;
	
	// parameters
	double par[5];
	for (i = 0; i < 5; i++)
		par[i] = 0.0;
	
	double v    = par[0]; // reduced volume
	double kb   = par[1]; // bending modulus (scaled by dp*a^3)
	double alph = par[2]; // taper angle of tube wall
	double R0   = par[3]; // tube radius at center-of-mass axial position (scaled by a)
	double xcom = par[4]; // center-of-mass position 
	                      //   = time integral of center-of-mass translational speed
	
	vector<int> vecV ;
	vector<int> vecKb;
	vector<int> vecAl;
	vector<int> vecR0;
	
	// should have auxiliary functions to get the parameters, but for now just use the following
	// trial parameters:
	v    = 0.99;
	v    = 0.90;
	kb   = 1e-5;
	kb   = 1e2;
	alph = 0.0 ;
	R0   = 0.9116; // conf = 80 for v = 90
	xcom = 0.0 ;

	par[0] = v   ;
	par[1] = kb  ;
	par[2] = alph;
	par[3] = R0  ;
	par[4] = xcom;

	double tana = gsl_sf_sin(alph)/gsl_sf_cos(alph);

	// increments for first-order continuation
	double dp0, dp1, slope;
			
	// initialize
	nrk = 60;
	cout << "Initializing... " << endl;
	init(n, m, par, u.data(), t.data(), si.data());
	for (j = 0; j < m*n; j++){
		sm[j] = si[j];
	}
	cout << "Initialization complete." << endl;

	// multiple shooting method
	cout << "Shooting for v = " << v << ", R0 = " << R0 << ", kb = " << kb << "." << endl;
	mshoot(n, m, nrk, maxiter, tol, par, u.data(), t.data(), si.data(), sf.data(), flag);


//	for (i = 0; i < m; i++){
//		//cout << t[i] << endl;
//		cout << si[i*n + 10] << endl;
//	}


//	// check if file exists
//	fileCheck(v, conf, vecCa[i], info);
//	if (info){ // file exists
//		// update solution
//		readOutput(n, m, v, conf, vecCa[i], t.data(), si.data());
//		for (j = 0; j < m*n; j++){
//			sm[j] = si[j];
//		}
//	}



	// evolve in time
	// - recalculate u
	// - update parameters (specifically R0 and xcom)







	
//	// write to file
//	if (flag == 0)
//		writeSoln(n, m, v, conf, Ca, t.data(), sf.data(), opath);
//	
//	/* update next initial guess using
//	 * first-order continuation */
//	if (flag == 0){
//		if (i != vecCa.size() - 1){
//			if (i == 0) {
//				dp0 = vecCa[i  ] - 0;
//				dp1 = vecCa[i+1] - 0;
//			}
//			else {
//				dp0 = vecCa[i  ] - vecCa[i-1];
//				dp1 = vecCa[i+1] - vecCa[i-1];
//			}
//			slope = dp1/dp0;
//			for (j = 0; j < m*n; j++){
//				//si[j] = sm[j] + slope*(sf[j] - sm[j]);
//				si[j] = sm[j];
//				sm[j] = sf[j];
//			}
//		}
//	}

	return(0);
}
コード例 #9
0
ファイル: Tabs.cpp プロジェクト: jingyu9575/sumatrapdf
    // Paints the tabs that intersect the window's update rectangle.
    void Paint(HDC hdc, RECT& rc) {
        IntersectClipRect(hdc, rc.left, rc.top, rc.right, rc.bottom);

// paint the background
#if 0
        bool isTranslucentMode = inTitlebar && dwm::IsCompositionEnabled();
        if (isTranslucentMode) {
            PaintParentBackground(hwnd, hdc);
        } else {
            // note: not sure what color should be used here and painting
            // background works fine
            /*HBRUSH brush = CreateSolidBrush(colors.bar);
            FillRect(hdc, &rc, brush);
            DeleteObject(brush);*/
        }
#else
        PaintParentBackground(hwnd, hdc);
#endif
        // TODO: GDI+ doesn't seem to cope well with SetWorldTransform
        XFORM ctm = {1.0, 0, 0, 1.0, 0, 0};
        SetWorldTransform(hdc, &ctm);

        Graphics gfx(hdc);
        gfx.SetCompositingMode(CompositingModeSourceCopy);
        gfx.SetCompositingQuality(CompositingQualityHighQuality);
        gfx.SetSmoothingMode(SmoothingModeHighQuality);
        gfx.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
        gfx.SetPageUnit(UnitPixel);
        GraphicsPath shapes(data->Points, data->Types, data->Count);
        GraphicsPath shape;
        GraphicsPathIterator iterator(&shapes);

        SolidBrush br(Color(0, 0, 0));
        Pen pen(&br, 2.0f);

        Font f(hdc, GetDefaultGuiFont());
        // TODO: adjust these constant values for DPI?
        RectF layout((REAL)DpiScaleX(hwnd, 3), 1.0f, REAL(width - DpiScaleX(hwnd, 20)), (REAL)height);
        StringFormat sf(StringFormat::GenericDefault());
        sf.SetFormatFlags(StringFormatFlagsNoWrap);
        sf.SetLineAlignment(StringAlignmentCenter);
        sf.SetTrimming(StringTrimmingEllipsisCharacter);

        REAL yPosTab = inTitlebar ? 0.0f : REAL(ClientRect(hwnd).dy - height - 1);
        for (int i = 0; i < Count(); i++) {
            gfx.ResetTransform();
            gfx.TranslateTransform(1.f + (REAL)(width + 1) * i - (REAL)rc.left, yPosTab - (REAL)rc.top);

            if (!gfx.IsVisible(0, 0, width + 1, height + 1))
                continue;

            // Get the correct colors based on the state and the current theme
            COLORREF bgCol = GetAppColor(AppColor::TabBackgroundBg);
            COLORREF textCol = GetAppColor(AppColor::TabBackgroundText);
            COLORREF xColor = GetAppColor(AppColor::TabBackgroundCloseX);
            COLORREF circleColor = GetAppColor(AppColor::TabBackgroundCloseCircle);

            if (selectedTabIdx == i) {
                bgCol = GetAppColor(AppColor::TabSelectedBg);
                textCol = GetAppColor(AppColor::TabSelectedText);
                xColor = GetAppColor(AppColor::TabSelectedCloseX);
                circleColor = GetAppColor(AppColor::TabSelectedCloseCircle);
            } else if (highlighted == i) {
                bgCol = GetAppColor(AppColor::TabHighlightedBg);
                textCol = GetAppColor(AppColor::TabHighlightedText);
                xColor = GetAppColor(AppColor::TabHighlightedCloseX);
                circleColor = GetAppColor(AppColor::TabHighlightedCloseCircle);
            }
            if (xHighlighted == i) {
                xColor = GetAppColor(AppColor::TabHoveredCloseX);
                circleColor = GetAppColor(AppColor::TabHoveredCloseCircle);
            }
            if (xClicked == i) {
                xColor = GetAppColor(AppColor::TabClickedCloseX);
                circleColor = GetAppColor(AppColor::TabClickedCloseCircle);
            }

            // paint tab's body
            gfx.SetCompositingMode(CompositingModeSourceCopy);
            iterator.NextMarker(&shape);
            br.SetColor(ToColor(bgCol));
            Point points[4];
            shape.GetPathPoints(points, 4);
            Rect body(points[0].X, points[0].Y, points[2].X - points[0].X, points[2].Y - points[0].Y);
            body.Inflate(0, 0);
            gfx.SetClip(body);
            body.Inflate(5, 5);
            gfx.FillRectangle(&br, body);
            gfx.ResetClip();

            // draw tab's text
            gfx.SetCompositingMode(CompositingModeSourceOver);
            br.SetColor(ToColor(textCol));
            gfx.DrawString(text.at(i), -1, &f, layout, &sf, &br);

            // paint "x"'s circle
            iterator.NextMarker(&shape);
            bool closeCircleEnabled = true;
            if ((xClicked == i || xHighlighted == i) && closeCircleEnabled) {
                br.SetColor(ToColor(circleColor));
                gfx.FillPath(&br, &shape);
            }

            // paint "x"
            iterator.NextMarker(&shape);
            pen.SetColor(ToColor(xColor));
            gfx.DrawPath(&pen, &shape);
            iterator.Rewind();
        }
    }
コード例 #10
0
dogen::formatters::file class_implementation_formatter_stitch(
    formatters::entity_formatting_assistant& fa,
    const formattables::class_info& c) {

    {
        auto sbf(fa.make_scoped_boilerplate_formatter());
        if (!c.properties().empty()) {
fa.stream() << "namespace {" << std::endl;
        fa.add_helper_methods();
fa.stream() << std::endl;
fa.stream() << "}" << std::endl;
fa.stream() << std::endl;
        }

        {
            auto snf(fa.make_scoped_namespace_formatter());

            /*
             * Default constructor.
             */
            if (!c.is_parent()) {
fa.stream() << std::endl;
fa.stream() << c.name() << "_generator::" << c.name() << "_generator() : position_(0) { }" << std::endl;
            }

            /*
             * Populate method.
             */
            if (!c.is_immutable()) {
                bool no_args(c.properties().empty() && c.parents().empty());
                if (no_args) {
fa.stream() << std::endl;
fa.stream() << "void " << c.name() << "_generator::" << std::endl;
fa.stream() << "populate(const unsigned int /*position*/, result_type& /*v*/) {" << std::endl;
                } else {
fa.stream() << std::endl;
fa.stream() << "void " << c.name() << "_generator::" << std::endl;
fa.stream() << "populate(const unsigned int position, result_type& v) {" << std::endl;
                }

                for (const auto p : c.parents()) {
fa.stream() << "    " << p.qualified_name() << "_generator::populate(position, v);" << std::endl;
                }
                unsigned int i(0);
                for (const auto p : c.properties()) {
fa.stream() << "    v." << p.name() << "(create_" << p.type().complete_identifiable_name() << "(position + " << i << "));" << std::endl;
                    ++i;
                }
fa.stream() << "}" << std::endl;
            }

            /*
             * Create method.
             */
            if (!c.is_parent()) {
                 const bool no_arg(c.all_properties().empty());
fa.stream() << std::endl;
fa.stream() << c.name() << "_generator::result_type" << std::endl;
fa.stream() << c.name() << "_generator::create(const unsigned int" << (no_arg ? "/*position*/" : " position") << ") {" << std::endl;
                if (c.is_immutable()) {
fa.stream() << "    return " << c.name() << "(" << std::endl;
                    // FIXME: hack
                    if (c.properties().empty())
fa.stream() << std::endl;
                    else {
                        dogen::formatters::sequence_formatter sf(c.properties().size());
                        for (const auto p : c.properties()) {
fa.stream() << "        create_" << p.type().complete_identifiable_name() << "(position + " << sf.current_position() << ")" << sf.postfix() << std::endl;
                            sf.next();
                        }
                    }
fa.stream() << "        );" << std::endl;
                } else {
fa.stream() << "    " << c.name() << " r;" << std::endl;
                    if (!c.all_properties().empty())
fa.stream() << "    " << c.name() << "_generator::populate(position, r);" << std::endl;
fa.stream() << "    return r;" << std::endl;
                }
fa.stream() << "}" << std::endl;
            }

            /*
             * Create method ptr.
             */
fa.stream() << std::endl;
fa.stream() << c.name() << "_generator::result_type*" << std::endl;
fa.stream() << c.name() << "_generator::create_ptr(const unsigned int position) {" << std::endl;
            if (c.leaves().empty()) {
                if (c.is_immutable())
fa.stream() << "    return new " << c.name() << "(create(position));" << std::endl;
                else {
fa.stream() << "    " << c.name() << "* p = new " << c.name() << "();" << std::endl;
fa.stream() << "    " << c.name() << "_generator::populate(position, *p);" << std::endl;
fa.stream() << "    return p;" << std::endl;
                }
            } else {
                auto leaves(c.leaves());
                const auto front(leaves.front());
                leaves.pop_front();
                unsigned int i(0);
                unsigned int total(leaves.size());
                for (const auto l : leaves) {
fa.stream() << "    if ((position % " << total << ") == " << i++ << ")" << std::endl;
fa.stream() << "        return " << l << "_generator::create_ptr(position);" << std::endl;
                }
fa.stream() << "    return " << front << "_generator::create_ptr(position);" << std::endl;
            }
fa.stream() << "}" << std::endl;
            /*
             * Function operator
             */
             if (!c.is_parent()) {
fa.stream() << std::endl;
fa.stream() << c.name() << "_generator::result_type" << std::endl;
fa.stream() << c.name() << "_generator::operator()() {" << std::endl;
fa.stream() << "    return create(position_++);" << std::endl;
fa.stream() << "}" << std::endl;
            }
fa.stream() << std::endl;
        } // snf
    } // sbf
    return fa.make_file();
}
コード例 #11
0
ファイル: datatest.cpp プロジェクト: Andy-Amoy/cryptopp
void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
{
	std::string type = GetRequiredDatum(v, "AlgorithmType");
	std::string name = GetRequiredDatum(v, "Name");
	std::string test = GetRequiredDatum(v, "Test");
	std::string key = GetDecodedDatum(v, "Key");

	std::string plaintext = GetOptionalDecodedDatum(v, "Plaintext");
	std::string ciphertext = GetOptionalDecodedDatum(v, "Ciphertext");
	std::string header = GetOptionalDecodedDatum(v, "Header");
	std::string footer = GetOptionalDecodedDatum(v, "Footer");
	std::string mac = GetOptionalDecodedDatum(v, "MAC");

	TestDataNameValuePairs testDataPairs(v);
	CombinedNameValuePairs pairs(overrideParameters, testDataPairs);

	if (test == "Encrypt" || test == "EncryptXorDigest" || test == "NotVerify")
	{
		member_ptr<AuthenticatedSymmetricCipher> asc1, asc2;
		asc1.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str()));
		asc2.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str()));
		asc1->SetKey((const byte *)key.data(), key.size(), pairs);
		asc2->SetKey((const byte *)key.data(), key.size(), pairs);

		std::string encrypted, decrypted;
		AuthenticatedEncryptionFilter ef(*asc1, new StringSink(encrypted));
		bool macAtBegin = !mac.empty() && !GlobalRNG().GenerateBit();	// test both ways randomly
		AuthenticatedDecryptionFilter df(*asc2, new StringSink(decrypted), macAtBegin ? AuthenticatedDecryptionFilter::MAC_AT_BEGIN : 0);

		if (asc1->NeedsPrespecifiedDataLengths())
		{
			asc1->SpecifyDataLengths(header.size(), plaintext.size(), footer.size());
			asc2->SpecifyDataLengths(header.size(), plaintext.size(), footer.size());
		}

		StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer), sm(mac);

		if (macAtBegin)
			RandomizedTransfer(sm, df, true);
		sh.CopyTo(df, LWORD_MAX, AAD_CHANNEL);
		RandomizedTransfer(sc, df, true);
		sf.CopyTo(df, LWORD_MAX, AAD_CHANNEL);
		if (!macAtBegin)
			RandomizedTransfer(sm, df, true);
		df.MessageEnd();

		RandomizedTransfer(sh, ef, true, AAD_CHANNEL);
		RandomizedTransfer(sp, ef, true);
		RandomizedTransfer(sf, ef, true, AAD_CHANNEL);
		ef.MessageEnd();

		if (test == "Encrypt" && encrypted != ciphertext+mac)
		{
			std::cout << "incorrectly encrypted: ";
			StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout)));
			xx.Pump(2048); xx.Flush(false);
			std::cout << "\n";
			SignalTestFailure();
		}
		if (test == "Encrypt" && decrypted != plaintext)
		{
			std::cout << "incorrectly decrypted: ";
			StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout)));
			xx.Pump(256); xx.Flush(false);
			std::cout << "\n";
			SignalTestFailure();
		}

		if (ciphertext.size()+mac.size()-plaintext.size() != asc1->DigestSize())
		{
			std::cout << "bad MAC size\n";
			SignalTestFailure();
		}
		if (df.GetLastResult() != (test == "Encrypt"))
		{
			std::cout << "MAC incorrectly verified\n";
			SignalTestFailure();
		}
	}
	else
	{
		std::cout << "unexpected test name\n";
		SignalTestError();
	}
}
コード例 #12
0
ファイル: tile.cpp プロジェクト: jojoa1997/freeminer
bool TextureSource::generateImage(std::string part_of_name, video::IImage *& baseimg)
{
	video::IVideoDriver* driver = m_device->getVideoDriver();
	assert(driver);

	// Stuff starting with [ are special commands
	if(part_of_name.size() == 0 || part_of_name[0] != '[')
	{
		video::IImage *image = m_sourcecache.getOrLoad(part_of_name, m_device);

		if(image == NULL)
		{
			if(part_of_name != ""){
				errorstream<<"generateImage(): Could not load image \""
						<<part_of_name<<"\""<<" while building texture"<<std::endl;
				errorstream<<"generateImage(): Creating a dummy"
						<<" image for \""<<part_of_name<<"\""<<std::endl;
			}

			// Just create a dummy image
			//core::dimension2d<u32> dim(2,2);
			core::dimension2d<u32> dim(1,1);
			image = driver->createImage(video::ECF_A8R8G8B8, dim);
			assert(image);
			/*image->setPixel(0,0, video::SColor(255,255,0,0));
			image->setPixel(1,0, video::SColor(255,0,255,0));
			image->setPixel(0,1, video::SColor(255,0,0,255));
			image->setPixel(1,1, video::SColor(255,255,0,255));*/
			image->setPixel(0,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			/*image->setPixel(1,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(0,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(1,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));*/
		}

		// If base image is NULL, load as base.
		if(baseimg == NULL)
		{
			//infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
			/*
				Copy it this way to get an alpha channel.
				Otherwise images with alpha cannot be blitted on
				images that don't have alpha in the original file.
			*/
			core::dimension2d<u32> dim = image->getDimension();
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			image->copyTo(baseimg);
		}
		// Else blit on base.
		else
		{
			//infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
			// Size of the copied area
			core::dimension2d<u32> dim = image->getDimension();
			//core::dimension2d<u32> dim(16,16);
			// Position to copy the blitted to in the base image
			core::position2d<s32> pos_to(0,0);
			// Position to copy the blitted from in the blitted image
			core::position2d<s32> pos_from(0,0);
			// Blit
			/*image->copyToWithAlpha(baseimg, pos_to,
					core::rect<s32>(pos_from, dim),
					video::SColor(255,255,255,255),
					NULL);*/
			blit_with_alpha(image, baseimg, pos_from, pos_to, dim);
		}
		//cleanup
		image->drop();
	}
	else
	{
		// A special texture modification

		/*infostream<<"generateImage(): generating special "
				<<"modification \""<<part_of_name<<"\""
				<<std::endl;*/

		/*
			[crack:N:P
			[cracko:N:P
			Adds a cracking texture
			N = animation frame count, P = crack progression
		*/
		if(part_of_name.substr(0,6) == "[crack")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generateImage(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			// Crack image number and overlay option
			bool use_overlay = (part_of_name[6] == 'o');
			Strfnd sf(part_of_name);
			sf.next(":");
			s32 frame_count = stoi(sf.next(":"));
			s32 progression = stoi(sf.next(":"));

			/*
				Load crack image.

				It is an image with a number of cracking stages
				horizontally tiled.
			*/
			video::IImage *img_crack = m_sourcecache.getOrLoad(
					"crack_anylength.png", m_device);

			if(img_crack && progression >= 0)
			{
				draw_crack(img_crack, baseimg,
						use_overlay, frame_count,
						progression, driver);
				img_crack->drop();
			}
		}
		/*
			[combine:WxH:X,Y=filename:X,Y=filename2
			Creates a bigger texture from an amount of smaller ones
		*/
		else if(part_of_name.substr(0,8) == "[combine")
		{
			Strfnd sf(part_of_name);
			sf.next(":");
			u32 w0 = stoi(sf.next("x"));
			u32 h0 = stoi(sf.next(":"));
			infostream<<"combined w="<<w0<<" h="<<h0<<std::endl;
			core::dimension2d<u32> dim(w0,h0);
			if(baseimg == NULL)
			{
				baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
				baseimg->fill(video::SColor(0,0,0,0));
			}
			while(sf.atend() == false)
			{
				u32 x = stoi(sf.next(","));
				u32 y = stoi(sf.next("="));
				std::string filename = sf.next(":");
				infostream<<"Adding \""<<filename
						<<"\" to combined ("<<x<<","<<y<<")"
						<<std::endl;
				video::IImage *img = m_sourcecache.getOrLoad(filename, m_device);
				if(img)
				{
					core::dimension2d<u32> dim = img->getDimension();
					infostream<<"Size "<<dim.Width
							<<"x"<<dim.Height<<std::endl;
					core::position2d<s32> pos_base(x, y);
					video::IImage *img2 =
							driver->createImage(video::ECF_A8R8G8B8, dim);
					img->copyTo(img2);
					img->drop();
					/*img2->copyToWithAlpha(baseimg, pos_base,
							core::rect<s32>(v2s32(0,0), dim),
							video::SColor(255,255,255,255),
							NULL);*/
					blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim);
					img2->drop();
				}
				else
				{
					infostream<<"img==NULL"<<std::endl;
				}
			}
		}
		/*
			"[brighten"
		*/
		else if(part_of_name.substr(0,9) == "[brighten")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generateImage(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			brighten(baseimg);
		}
		/*
			"[noalpha"
			Make image completely opaque.
			Used for the leaves texture when in old leaves mode, so
			that the transparent parts don't look completely black
			when simple alpha channel is used for rendering.
		*/
		else if(part_of_name.substr(0,8) == "[noalpha")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generateImage(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			core::dimension2d<u32> dim = baseimg->getDimension();

			// Set alpha to full
			for(u32 y=0; y<dim.Height; y++)
			for(u32 x=0; x<dim.Width; x++)
			{
				video::SColor c = baseimg->getPixel(x,y);
				c.setAlpha(255);
				baseimg->setPixel(x,y,c);
			}
		}
		/*
			"[makealpha:R,G,B"
			Convert one color to transparent.
		*/
		else if(part_of_name.substr(0,11) == "[makealpha:")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generateImage(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			Strfnd sf(part_of_name.substr(11));
			u32 r1 = stoi(sf.next(","));
			u32 g1 = stoi(sf.next(","));
			u32 b1 = stoi(sf.next(""));
			std::string filename = sf.next("");

			core::dimension2d<u32> dim = baseimg->getDimension();

			/*video::IImage *oldbaseimg = baseimg;
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			oldbaseimg->copyTo(baseimg);
			oldbaseimg->drop();*/

			// Set alpha to full
			for(u32 y=0; y<dim.Height; y++)
			for(u32 x=0; x<dim.Width; x++)
			{
				video::SColor c = baseimg->getPixel(x,y);
				u32 r = c.getRed();
				u32 g = c.getGreen();
				u32 b = c.getBlue();
				if(!(r == r1 && g == g1 && b == b1))
					continue;
				c.setAlpha(0);
				baseimg->setPixel(x,y,c);
			}
		}
		/*
			"[transformN"
			Rotates and/or flips the image.

			N can be a number (between 0 and 7) or a transform name.
			Rotations are counter-clockwise.
			0  I      identity
			1  R90    rotate by 90 degrees
			2  R180   rotate by 180 degrees
			3  R270   rotate by 270 degrees
			4  FX     flip X
			5  FXR90  flip X then rotate by 90 degrees
			6  FY     flip Y
			7  FYR90  flip Y then rotate by 90 degrees

			Note: Transform names can be concatenated to produce
			their product (applies the first then the second).
			The resulting transform will be equivalent to one of the
			eight existing ones, though (see: dihedral group).
		*/
		else if(part_of_name.substr(0,10) == "[transform")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generateImage(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			u32 transform = parseImageTransform(part_of_name.substr(10));
			core::dimension2d<u32> dim = imageTransformDimension(
					transform, baseimg->getDimension());
			video::IImage *image = driver->createImage(
					baseimg->getColorFormat(), dim);
			assert(image);
			imageTransform(transform, baseimg, image);
			baseimg->drop();
			baseimg = image;
		}
		/*
			[inventorycube{topimage{leftimage{rightimage
			In every subimage, replace ^ with &.
			Create an "inventory cube".
			NOTE: This should be used only on its own.
			Example (a grass block (not actually used in game):
			"[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png"
		*/
		else if(part_of_name.substr(0,14) == "[inventorycube")
		{
			if(baseimg != NULL)
			{
				errorstream<<"generateImage(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			str_replace_char(part_of_name, '&', '^');
			Strfnd sf(part_of_name);
			sf.next("{");
			std::string imagename_top = sf.next("{");
			std::string imagename_left = sf.next("{");
			std::string imagename_right = sf.next("{");

			// Generate images for the faces of the cube
			video::IImage *img_top =
				generateImageFromScratch(imagename_top);
			video::IImage *img_left =
				generateImageFromScratch(imagename_left);
			video::IImage *img_right =
				generateImageFromScratch(imagename_right);
			assert(img_top && img_left && img_right);

			// Create textures from images
			video::ITexture *texture_top = driver->addTexture(
					(imagename_top + "__temp__").c_str(), img_top);
			video::ITexture *texture_left = driver->addTexture(
					(imagename_left + "__temp__").c_str(), img_left);
			video::ITexture *texture_right = driver->addTexture(
					(imagename_right + "__temp__").c_str(), img_right);
			assert(texture_top && texture_left && texture_right);

			// Drop images
			img_top->drop();
			img_left->drop();
			img_right->drop();

			/*
				Draw a cube mesh into a render target texture
			*/
			scene::IMesh* cube = createCubeMesh(v3f(1, 1, 1));
			setMeshColor(cube, video::SColor(255, 255, 255, 255));
			cube->getMeshBuffer(0)->getMaterial().setTexture(0, texture_top);
			cube->getMeshBuffer(1)->getMaterial().setTexture(0, texture_top);
			cube->getMeshBuffer(2)->getMaterial().setTexture(0, texture_right);
			cube->getMeshBuffer(3)->getMaterial().setTexture(0, texture_right);
			cube->getMeshBuffer(4)->getMaterial().setTexture(0, texture_left);
			cube->getMeshBuffer(5)->getMaterial().setTexture(0, texture_left);

			TextureFromMeshParams params;
			params.mesh = cube;
			params.dim.set(64, 64);
			params.rtt_texture_name = part_of_name + "_RTT";
			// We will delete the rtt texture ourselves
			params.delete_texture_on_shutdown = false;
			params.camera_position.set(0, 1.0, -1.5);
			params.camera_position.rotateXZBy(45);
			params.camera_lookat.set(0, 0, 0);
			// Set orthogonal projection
			params.camera_projection_matrix.buildProjectionMatrixOrthoLH(
					1.65, 1.65, 0, 100);

			params.ambient_light.set(1.0, 0.2, 0.2, 0.2);
			params.light_position.set(10, 100, -50);
			params.light_color.set(1.0, 0.5, 0.5, 0.5);
			params.light_radius = 1000;

			video::ITexture *rtt = generateTextureFromMesh(params);

			// Drop mesh
			cube->drop();

			// Free textures of images
			driver->removeTexture(texture_top);
			driver->removeTexture(texture_left);
			driver->removeTexture(texture_right);

			if(rtt == NULL)
			{
				baseimg = generateImageFromScratch(imagename_top);
				return true;
			}

			// Create image of render target
			video::IImage *image = driver->createImage(rtt, v2s32(0,0), params.dim);
			assert(image);

			// Cleanup texture
			driver->removeTexture(rtt);

			baseimg = driver->createImage(video::ECF_A8R8G8B8, params.dim);

			if(image)
			{
				image->copyTo(baseimg);
				image->drop();
			}
		}
		/*
			[lowpart:percent:filename
			Adds the lower part of a texture
		*/
		else if(part_of_name.substr(0,9) == "[lowpart:")
		{
			Strfnd sf(part_of_name);
			sf.next(":");
			u32 percent = stoi(sf.next(":"));
			std::string filename = sf.next(":");
			//infostream<<"power part "<<percent<<"%% of "<<filename<<std::endl;

			if(baseimg == NULL)
				baseimg = driver->createImage(video::ECF_A8R8G8B8, v2u32(16,16));
			video::IImage *img = m_sourcecache.getOrLoad(filename, m_device);
			if(img)
			{
				core::dimension2d<u32> dim = img->getDimension();
				core::position2d<s32> pos_base(0, 0);
				video::IImage *img2 =
						driver->createImage(video::ECF_A8R8G8B8, dim);
				img->copyTo(img2);
				img->drop();
				core::position2d<s32> clippos(0, 0);
				clippos.Y = dim.Height * (100-percent) / 100;
				core::dimension2d<u32> clipdim = dim;
				clipdim.Height = clipdim.Height * percent / 100 + 1;
				core::rect<s32> cliprect(clippos, clipdim);
				img2->copyToWithAlpha(baseimg, pos_base,
						core::rect<s32>(v2s32(0,0), dim),
						video::SColor(255,255,255,255),
						&cliprect);
				img2->drop();
			}
		}
		/*
			[verticalframe:N:I
			Crops a frame of a vertical animation.
			N = frame count, I = frame index
		*/
		else if(part_of_name.substr(0,15) == "[verticalframe:")
		{
			Strfnd sf(part_of_name);
			sf.next(":");
			u32 frame_count = stoi(sf.next(":"));
			u32 frame_index = stoi(sf.next(":"));

			if(baseimg == NULL){
				errorstream<<"generateImage(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			v2u32 frame_size = baseimg->getDimension();
			if (frame_count)
			frame_size.Y /= frame_count;

			video::IImage *img = driver->createImage(video::ECF_A8R8G8B8,
					frame_size);
			if(!img){
				errorstream<<"generateImage(): Could not create image "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			// Fill target image with transparency
			img->fill(video::SColor(0,0,0,0));

			core::dimension2d<u32> dim = frame_size;
			core::position2d<s32> pos_dst(0, 0);
			core::position2d<s32> pos_src(0, frame_index * frame_size.Y);
			baseimg->copyToWithAlpha(img, pos_dst,
					core::rect<s32>(pos_src, dim),
					video::SColor(255,255,255,255),
					NULL);
			// Replace baseimg
			baseimg->drop();
			baseimg = img;
		}
		else
		{
			errorstream<<"generateImage(): Invalid "
					" modification: \""<<part_of_name<<"\""<<std::endl;
		}
	}

	return true;
}
コード例 #13
0
ファイル: vsocc.cpp プロジェクト: 11235813/netgen
   void VisualSceneOCCGeometry :: BuildScene (int zoomall)
   {
     if (occgeometry -> changed == OCCGEOMETRYVISUALIZATIONFULLCHANGE)
       {
         occgeometry -> BuildVisualizationMesh (vispar.occdeflection);

         center = occgeometry -> Center();
         rad = occgeometry -> GetBoundingBox().Diam() / 2;

         if (vispar.occzoomtohighlightedentity)
         {
            bool hilite = false;
            bool hiliteonepoint = false;
            Bnd_Box bb;

            for (int i = 1; i <= occgeometry->fmap.Extent(); i++)
            if (occgeometry->fvispar[i-1].IsHighlighted())
            {
               hilite = true;
               BRepBndLib::Add (occgeometry->fmap(i), bb);
            }

            for (int i = 1; i <= occgeometry->emap.Extent(); i++)
            if (occgeometry->evispar[i-1].IsHighlighted())
            {
               hilite = true;
               BRepBndLib::Add (occgeometry->emap(i), bb);
            }

            for (int i = 1; i <= occgeometry->vmap.Extent(); i++)
            if (occgeometry->vvispar[i-1].IsHighlighted())
            {
               hiliteonepoint = true;
               BRepBndLib::Add (occgeometry->vmap(i), bb);
            }

            if (hilite || hiliteonepoint)
            {
               double x1,y1,z1,x2,y2,z2;
               bb.Get (x1,y1,z1,x2,y2,z2);
               Point<3> p1 = Point<3> (x1,y1,z1);
               Point<3> p2 = Point<3> (x2,y2,z2);
               Box<3> boundingbox(p1,p2);

               center = boundingbox.Center();
               if (hiliteonepoint)
               rad = occgeometry -> GetBoundingBox().Diam() / 100;
               else
               rad = boundingbox.Diam() / 2;
            }
         }

         CalcTransformationMatrices();
      }

      // Clear lists

      for (int i = 1; i <= linelists.Size(); i++)
      glDeleteLists (linelists.Elem(i), 1);
      linelists.SetSize(0);

      for (int i = 1; i <= trilists.Size(); i++)
      glDeleteLists (trilists.Elem(i), 1);
      trilists.SetSize(0);

      // Total wireframe

      linelists.Append (glGenLists (1));
      glNewList (linelists.Last(), GL_COMPILE);

      for (int i = 1; i <= occgeometry->emap.Extent(); i++)
      {
         TopoDS_Edge edge = TopoDS::Edge(occgeometry->emap(i));
         if (BRep_Tool::Degenerated(edge)) continue;
         if (occgeometry->evispar[i-1].IsHighlighted()) continue;

         Handle(Poly_PolygonOnTriangulation) aEdgePoly;
         Handle(Poly_Triangulation) T;
         TopLoc_Location aEdgeLoc;
         BRep_Tool::PolygonOnTriangulation(edge, aEdgePoly, T, aEdgeLoc);

         if(aEdgePoly.IsNull())
         {
            (*testout) << "visualizing edge " << occgeometry->emap.FindIndex (edge)
            << " without using the occ visualization triangulation" << endl;

            double s0, s1;
            Handle(Geom_Curve) c = BRep_Tool::Curve(edge, s0, s1);

            glBegin (GL_LINE_STRIP);
            for (int i = 0; i<=50; i++)
            {
               gp_Pnt p = c->Value (s0 + i*(s1-s0)/50.0);
               glVertex3f (p.X(),p.Y(),p.Z());
            }
            glEnd ();

            continue;
         }

         int nbnodes = aEdgePoly -> NbNodes();
         glBegin (GL_LINE_STRIP);
         for (int j = 1; j <= nbnodes; j++)
         {
            gp_Pnt p = (T -> Nodes())(aEdgePoly->Nodes()(j)).Transformed(aEdgeLoc);
            glVertex3f (p.X(), p.Y(), p.Z());
         }
         glEnd ();
      }

      glEndList ();

      // Highlighted edge list

      linelists.Append (glGenLists (1));
      glNewList (linelists.Last(), GL_COMPILE);

      for (int i = 1; i <= occgeometry->emap.Extent(); i++)
      if (occgeometry->evispar[i-1].IsHighlighted())
      {
         TopoDS_Edge edge = TopoDS::Edge(occgeometry->emap(i));
         if (BRep_Tool::Degenerated(edge)) continue;

         Handle(Poly_PolygonOnTriangulation) aEdgePoly;
         Handle(Poly_Triangulation) T;
         TopLoc_Location aEdgeLoc;
         BRep_Tool::PolygonOnTriangulation(edge, aEdgePoly, T, aEdgeLoc);

         if(aEdgePoly.IsNull())
         {
            (*testout) << "visualizing edge " << occgeometry->emap.FindIndex (edge)
            << " without using the occ visualization triangulation" << endl;

            double s0, s1;
            Handle(Geom_Curve) c = BRep_Tool::Curve(edge, s0, s1);

            glBegin (GL_LINE_STRIP);
            for (int i = 0; i<=50; i++)
            {
               gp_Pnt p = c->Value (s0 + i*(s1-s0)/50.0);
               glVertex3f (p.X(),p.Y(),p.Z());
            }
            glEnd ();

            continue;
         }

         int nbnodes = aEdgePoly -> NbNodes();
         glBegin (GL_LINE_STRIP);
         for (int j = 1; j <= nbnodes; j++)
         {
            gp_Pnt p = (T -> Nodes())(aEdgePoly->Nodes()(j)).Transformed(aEdgeLoc);
            glVertex3f (p.X(), p.Y(), p.Z());
         }
         glEnd ();
      }

      glEndList ();

      // display faces

      trilists.Append (glGenLists (1));
      glNewList (trilists.Last(), GL_COMPILE);

      for (int i = 1; i <= occgeometry->fmap.Extent(); i++)
      {
         if (!occgeometry->fvispar[i-1].IsVisible()) continue;

         glLoadName (i);
         float mat_col[4];
         mat_col[3] = 1;

         TopoDS_Face face = TopoDS::Face(occgeometry->fmap(i));

         if (!occgeometry->fvispar[i-1].IsHighlighted())
         {
            // Philippose - 30/01/2009
            // OpenCascade XDE Support
            Quantity_Color face_colour;
            // Philippose - 23/02/2009
            // Check to see if colours have been extracted first!!
            // Forum bug-fox (Jean-Yves - 23/02/2009)
            if(!(occgeometry->face_colours.IsNull())
               && (occgeometry->face_colours->GetColor(face,XCAFDoc_ColorSurf,face_colour)))
            {
               mat_col[0] = face_colour.Red();
               mat_col[1] = face_colour.Green();
               mat_col[2] = face_colour.Blue();
            }
            else
            {
               mat_col[0] = 0.0;
               mat_col[1] = 1.0;
               mat_col[2] = 0.0;
            }
         }
         else
         {
            mat_col[0] = 0.8;
            mat_col[1] = 0.2;
            mat_col[2] = 0.2;
         }

         glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_col);

         TopLoc_Location loc;
         Handle(Geom_Surface) surf = BRep_Tool::Surface (face);
         BRepAdaptor_Surface sf(face, Standard_False);
         BRepLProp_SLProps prop(sf, 1, 1e-5);
         Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation (face, loc);

         if (triangulation.IsNull())
         {
            cout << "cannot visualize face " << i << endl;
            occgeometry->fvispar[i-1].SetNotDrawable();
            continue;
         }

         gp_Pnt2d uv;
         gp_Pnt pnt;
         gp_Vec n;

         glBegin (GL_TRIANGLES);

         int ntriangles = triangulation -> NbTriangles();
         for (int j = 1; j <= ntriangles; j++)
         {
            Poly_Triangle triangle = (triangulation -> Triangles())(j);
            gp_Pnt p[3];
            for (int k = 1; k <= 3; k++)
            p[k-1] = (triangulation -> Nodes())(triangle(k)).Transformed(loc);

            for (int k = 1; k <= 3; k++)
            {
               uv = (triangulation -> UVNodes())(triangle(k));
               prop.SetParameters (uv.X(), uv.Y());

               //	      surf->D0 (uv.X(), uv.Y(), pnt);

               if (prop.IsNormalDefined())
               n = prop.Normal();
               else
               {
                  (*testout) << "Visualization of face " << i
                  << ": Normal vector not defined" << endl;
                  //		  n = gp_Vec (0,0,0);
                  gp_Vec a(p[0],p[1]);
                  gp_Vec b(p[0],p[2]);
                  n = b^a;
               }

               if (face.Orientation() == TopAbs_REVERSED) n *= -1;
               glNormal3f (n.X(), n.Y(), n.Z());
               glVertex3f (p[k-1].X(), p[k-1].Y(), p[k-1].Z());
            }
         }
         glEnd ();

      }
      glEndList ();

   }
コード例 #14
0
ファイル: sfconvert.cpp プロジェクト: lasconic/sftools
int main(int argc, char* argv[])
      {
      bool xml  = false;
      bool code = false;
      bool dump = false;
      bool compress = false;

      QList<int> presets;

      QTime t;
      t.start();
      fprintf(stderr, "%s: convert sound file\n", argv[0]);

      int c;
      while ((c = getopt(argc, argv, "xcp:dsz")) != EOF) {
            switch(c) {
                  case 'x':
                        xml = true;
                        break;
                  case 'c':
                        code = true;
                        break;
                  case 'p':
                        presets.append(atoi(optarg));
                        break;
                  case 'd':
                        dump = true;
                        break;
                  case 's':
                        smallSf = true;
                        break;
                  case 'z':
                        compress = true;
                        break;
                  default:
                        usage(argv[0]);
                        exit(1);
                  }
            }
      const char* pname = argv[0];

      argc -= optind;
      argv += optind;
      if (xml && (argc != 2)) {
            usage(pname);
            exit(2);
            }
      if (code && (argc != 1) || dump && argc != 1) {
            usage(pname);
            exit(3);
            }
      if (!xml && !code && !dump && !compress) {
            usage(pname);
            exit(4);
            }

      SoundFont sf(argv[0]);

      if (!sf.read()) {
            fprintf(stderr, "sf read error\n");
            exit(3);
            }

      if (code) {
            if (presets.isEmpty())
                  sf.writeCode();
            else
                  sf.writeCode(presets);
            }
      else if (dump)
            sf.dumpPresets();
      else if (compress) {
            QFile fo(argv[1]);
            if (!fo.open(QIODevice::WriteOnly)) {
                  fprintf(stderr, "cannot open <%s>\n", argv[2]);
                  exit(2);
                  }
            if (xml)
                  sf.writeXml(&fo);
            else
                  sf.write(&fo);
            fo.close();
            }
      qDebug("Soundfont converted in: %d ms", t.elapsed());
      return 0;
      }
コード例 #15
0
ファイル: UtilTransactions.cpp プロジェクト: 4T-Shirt/mysql
int 
UtilTransactions::selectCount(Ndb* pNdb, 
			      int parallelism,
			      int* count_rows,
			      NdbOperation::LockMode lm,
			      NdbConnection* pTrans){
  
  int                  retryAttempt = 0;
  const int            retryMax = 100;
  int                  check;
  NdbScanOperation     *pOp;

  if(!pTrans)
    pTrans = pNdb->startTransaction();
    
  while (true){

    if (retryAttempt >= retryMax){
      g_info << "ERROR: has retried this operation " << retryAttempt 
	     << " times, failing!" << endl;
      return NDBT_FAILED;
    }
    pOp = getScanOperation(pTrans);
    if (pOp == NULL) {
      ERR(pTrans->getNdbError());
      closeTransaction(pNdb);
      return NDBT_FAILED;
    }

    if( pOp->readTuples(lm) ) {
      ERR(pTrans->getNdbError());
      closeTransaction(pNdb);
      return NDBT_FAILED;
    }

    if(0){
      NdbScanFilter sf(pOp);
      sf.begin(NdbScanFilter::OR);
      sf.eq(2, (Uint32)30);
      sf.end();
    } else {
      check = pOp->interpret_exit_ok();
      if( check == -1 ) {
	ERR(pTrans->getNdbError());
	closeTransaction(pNdb);
	return NDBT_FAILED;
      }
    }
    
    
    check = pTrans->execute(NoCommit, AbortOnError);
    if( check == -1 ) {
      ERR(pTrans->getNdbError());
      closeTransaction(pNdb);
      return NDBT_FAILED;
    }

    int eof;
    int rows = 0;
    

    while((eof = pOp->nextResult()) == 0){
      rows++;
    }
    if (eof == -1) {
      const NdbError err = pTrans->getNdbError();
      
      if (err.status == NdbError::TemporaryError){
	closeTransaction(pNdb);
	NdbSleep_MilliSleep(50);
	retryAttempt++;
	continue;
      }
      ERR(err);
      closeTransaction(pNdb);
      return NDBT_FAILED;
    }
    
    closeTransaction(pNdb);
    
    if (count_rows != NULL){
      *count_rows = rows;
    }
    
    return NDBT_OK;
  }
  return NDBT_FAILED;
}
コード例 #16
0
ファイル: Arithmetic1.cpp プロジェクト: FuangCao/cavan
int compute1(long double &a,string s,int angle=0)//算术综合运算
{
    if(!check_b(s))
        return 0;
    Stack<long double> ss(20);
    Stack<char> sf(20);
    int i=0,j;
    string s1,s2;
    char c;
    long double b;
    while(IsUselessChar(s[i]))
        i++;
    if(s[i]=='-')
    {
        ss.PushStack(-1);
        sf.PushStack('*');
        i++;
    }
    else if(s[i]=='+')
        i++;
    while(s[i])
    {
        s2="\0";
        if(IsUselessChar(s[i]))
            i++;
        else if(IsBracket(s[i])==1)
        {
            if(i>0&&!IsOperator1(s[i-1]))
                if(!sf.PushStack('*'))
                    return 0;
            s2=GetBracketData(s,i);
            if(!compute1(a,s2,angle)||!ss.PushStack(a))
                return 0;
        }
        else if(IsOperator1(s[i]))
        {
            if(s[i]=='!')
            {
                if(!ss.PopStack(b)||!factorial(a,(int)b)||!ss.PushStack(a))
                    return 0;
                i++;
                continue;
            }
            while(sf.GetTopData(c))
            {
                if(PRI(s[i])>PRI(c))
                    break;
                if(!ss.PopStack(b)||!ss.PopStack(a)||!sf.PopStack(c)||!Account1(a,b,c)||!ss.PushStack(a))
                    return 0;
            }
            if(!sf.PushStack(s[i++]))
                return 0;
        }
        else if(IsData(s[i])==1)
        {
            while(IsData(s[i])==1)
                s2+=s[i++];
            if(!ss.PushStack(string_double(s2)))
                return 0;
        }
        else if(s[i]=='S')
        {
            if(i>0&&!IsOperator1(s[i-1]))
                if(!sf.PushStack('*'))
                    return 0;
            s2="\0";
            for(j=0; j<4&&s[i]; j++,i++)
                s2+=s[i];
            if(s2!="Sqrt"||IsBracket(s[i])!=1)
                return 0;
            s2=GetBracketData(s,i);
            s1="\0";
            for(j=0; s2[j]; j++)
            {
                if(IsBracket(s2[j])==1)
                    s1+="("+GetBracketData(s2,j)+")";
                if(s2[j]==',')
                {
                    j++;
                    break;
                }
                else
                    s1+=s2[j];
            }
            if(!compute1(a,s1,angle))
                return 0;
            s1="\0";
            for(; s2[j]; j++)
                s1+=s2[j];
            if(!compute1(b,s1,angle)||!Sqrt(a,b)||!ss.PushStack(a))
                return 0;
        }
        else if(s[i]>='a'&&s[i]<='z'||s[i]=='L')
        {
            s1="\0";
            if(i>0&&!IsOperator1(s[i-1]))
                if(!sf.PushStack('*'))
                    return 0;
            while(s[i]>='a'&&s[i]<='z'||s[i]=='L'||s[i]=='^')
            {
                s1+=s[i++];
                if(s[i-1]=='e'&&s[i]!='^')
                    s1+='^';
            }
            if(s[i-1]=='e')
                s2="1";
            else if(IsBracket(s[i])==1)
                s2=GetBracketData(s,i);
            else if(IsData(s[i])==1)
            {
                while(s[i])
                {
                    if(IsData(s[i])==1)
                        s2+=s[i++];
                    else
                        break;
                }
            }
            else if(s[i]=='P'||s[i+1]=='i')
                s2="Pi";
            else if(s[i]=='S')
            {
                for(j=0; j<4&&s[i]; j++,i++)
                    s2+=s[i];
                if(s2!="Sqrt"||IsBracket(s[i])!=1)
                    return 0;
                s2+="("+GetBracketData(s,i)+")";
            }
            else
                return 0;
            if(!compute1(a,s2,angle)||!compute3(b,s1,a,angle)||!ss.PushStack(b))
                return 0;
        }
        else if(s[i]=='P')
        {
            if(i>0&&!IsOperator1(s[i-1])&&!sf.PushStack('*')||!ss.PushStack(P))
                return 0;
            i+=2;
        }
        else
            return 0;
    }
    while(sf.PopStack(c))
        if(!ss.PopStack(b)||!ss.PopStack(a)||!Account1(a,b,c)||!ss.PushStack(a))
            return 0;
    if(!ss.PopStack(a)||ss.State()>=0)
        return 0;
    return 1;
}
コード例 #17
0
void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event )
{
    int         id = event.GetId();
    wxFileName  fn;

    switch( id )
    {
    case ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG:
        m_show_layer_manager_tools = ! m_show_layer_manager_tools;
        m_auimgr.GetPane( wxT( "m_LayersManagerToolBar" ) ).Show( m_show_layer_manager_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
                                m_show_layer_manager_tools ?
                                _("Hide &Layers Manager" ) : _("Show &Layers Manager" ));
        break;

    case ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR:
        m_show_microwave_tools  = ! m_show_microwave_tools;
        m_auimgr.GetPane( wxT( "m_microWaveToolBar" ) ).Show( m_show_microwave_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR,
                                m_show_microwave_tools ?
                                _( "Hide Microwave Toolbar" ): _( "Show Microwave Toolbar" ));
        break;


    case ID_PCB_LAYERS_SETUP:
        InstallDialogLayerSetup();
        break;

    case ID_PCB_LIB_TABLE_EDIT:
        {
            bool tableChanged = false;
            int r = InvokePcbLibTableEditor( this, &GFootprintTable, FootprintLibs() );

            if( r & 1 )
            {
                try
                {
                    FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() );

                    GFootprintTable.Format( &sf, 0 );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving the global footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText.GetData() )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            // If no board file is defined, do not save the project specific library table.  It
            // is kept in memory and created in the path when the new board is saved.
            if( (r & 2) && !GetBoard()->GetFileName().IsEmpty() )
            {
                wxString    tblName   = Prj().FootprintLibTblName();

                try
                {
                    FootprintLibs()->Save( tblName );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving project specific footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            FOOTPRINT_VIEWER_FRAME* viewer;

            if( tableChanged && (viewer = FOOTPRINT_VIEWER_FRAME::GetActiveFootprintViewer( this )) != NULL )
            {
                viewer->ReCreateLibraryList();
            }
        }
        break;

    case ID_PCB_MASK_CLEARANCE:
        {
            DIALOG_PADS_MASK_CLEARANCE dlg( this );
            dlg.ShowModal();
        }
        break;

    case wxID_PREFERENCES:
        {
            DIALOG_GENERALOPTIONS dlg( this );
            dlg.ShowModal();
        }
        break;

    case ID_PCB_PAD_SETUP:
        InstallPadOptionsFrame( NULL );
        break;

    case ID_CONFIG_SAVE:
        SaveProjectSettings( true );
        break;

    case ID_CONFIG_READ:
        {
            fn = GetBoard()->GetFileName();
            fn.SetExt( ProjectFileExtension );

            wxFileDialog dlg( this, _( "Read Project File" ), fn.GetPath(),
                              fn.GetFullName(), ProjectFileWildcard,
                              wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR );

            if( dlg.ShowModal() == wxID_CANCEL )
                break;

            if( !wxFileExists( dlg.GetPath() ) )
            {
                wxString msg;
                msg.Printf( _( "File %s not found" ), GetChars( dlg.GetPath() ) );
                DisplayError( this, msg );
                break;
            }

            LoadProjectSettings( dlg.GetPath() );
        }
        break;

    // Hotkey IDs
    case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG:
        ExportHotkeyConfigToFile( g_Board_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_IMPORT_CONFIG:
        ImportHotkeyConfigFromFile( g_Board_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_EDITOR:
        InstallHotkeyFrame( this, g_Board_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST:
        // Display current hotkey list for Pcbnew.
        DisplayHotkeyList( this, g_Board_Editor_Hokeys_Descr );
        break;

    // Macros IDs
    case ID_PREFRENCES_MACROS_SAVE:
        SaveMacros();
        break;

    case ID_PREFRENCES_MACROS_READ:
        ReadMacros();
        break;

    default:
        DisplayError( this, wxT( "PCB_EDIT_FRAME::Process_Config error" ) );
    }
}
コード例 #18
0
void UtenteBasic::userSearch(const DB& db, const string& user, QList<QString>& list)
{
    Utente* ut = db.findU(user);
    Utente::SearchFunctor sf(1);
    sf(ut, list);
}
コード例 #19
0
ファイル: popup_menu.cpp プロジェクト: FlibbleMr/neogfx
	void popup_menu::init()
	{
		iLayout.set_margins(neogfx::margins{});
		closed([this]()
		{
			if (iMenu.is_open())
				iMenu.close();
		});
		for (i_menu::item_index i = 0; i < iMenu.item_count(); ++i)
			iLayout.add_item(std::make_shared<menu_item_widget>(*this, iMenu, iMenu.item(i)));
		layout_items();
		iMenu.open();
		iSink += iMenu.item_added([this](i_menu::item_index aIndex)
		{
			iLayout.add_item(aIndex, std::make_shared<menu_item_widget>(*this, iMenu, iMenu.item(aIndex)));
			layout_items();
		});
		iSink += iMenu.item_removed([this](i_menu::item_index aIndex)
		{
			iLayout.remove_item(aIndex);
			layout_items();
		});
		iSink += iMenu.item_changed([this](i_menu::item_index)
		{
			layout_items();
		});
		iSink += iMenu.item_selected([this](i_menu_item& aMenuItem)
		{
			if (!app::instance().keyboard().is_keyboard_grabbed_by(*this))
				app::instance().keyboard().grab_keyboard(*this);
			if (iOpenSubMenu != nullptr)
			{
				if (aMenuItem.type() == i_menu_item::Action ||
					(aMenuItem.type() == i_menu_item::SubMenu && &iOpenSubMenu->menu() != &aMenuItem.sub_menu()))
				{
					iOpenSubMenu->menu().close();
				}
			}
			scroll_to(layout().get_widget<menu_item_widget>(iMenu.find_item(aMenuItem)));
			update();
		});
		iSink += iMenu.open_sub_menu([this](i_menu& aSubMenu)
		{
			if (!iOpeningSubMenu && aSubMenu.item_count() > 0)
			{
				neolib::scoped_flag sf(iOpeningSubMenu);
				auto& itemWidget = layout().get_widget<menu_item_widget>(iMenu.find_item(aSubMenu));
				close_sub_menu();
				iOpenSubMenu = std::make_unique<popup_menu>(*this, itemWidget.sub_menu_position(), aSubMenu);
				iSink2 += iOpenSubMenu->menu().closed([this]()
				{
					if (iOpenSubMenu != nullptr)
						iOpenSubMenu->close();
				});
				iSink2 += iOpenSubMenu->closed([this]()
				{
					close_sub_menu();
				});
			}
		});
		show();
	}
コード例 #20
0
void SETcom::SerializeCommon(bool w, CONFIGFILE & c)
{
	//  menu
	Param(c,w, "game.start_in_main", startInMain);
	Param(c,w, "game.in_menu", inMenu);				Param(c,w, "game.in_main", isMain);
	
	//  misc
	Param(c,w, "misc.autostart", autostart);		Param(c,w, "misc.ogredialog", ogre_dialog);
	Param(c,w, "misc.escquit", escquit);
	
	Param(c,w, "misc.language", language);			Param(c,w, "misc.mouse_capture", mouse_capture);
	Param(c,w, "misc.screenshot_png", screen_png);

	//  video
	Param(c,w, "video.windowx", windowx);			Param(c,w, "video.windowy", windowy);
	Param(c,w, "video.fullscreen", fullscreen);		Param(c,w, "video.vsync", vsync);

	Param(c,w, "video.fsaa", fsaa);
	Param(c,w, "video.buffer", buffer);				Param(c,w, "video.rendersystem", rendersystem);

	Param(c,w, "video.limit_fps", limit_fps);
	Param(c,w, "video.limit_fps_val", limit_fps_val);	Param(c,w, "video.limit_sleep", limit_sleep);


	//  graphics  ----
	Param(c,w, "graph_detail.preset", preset);
	Param(c,w, "graph_shadow.shader_mode", shader_mode);	Param(c,w, "graph_shadow.lightmap_size", lightmap_size);
	
	Param(c,w, "graph_detail.anisotropy", anisotropy);
	Param(c,w, "graph_detail.tex_filter", tex_filt);		Param(c,w, "graph_detail.tex_size", tex_size);
	Param(c,w, "graph_detail.ter_mtr", ter_mtr);			Param(c,w, "graph_detail.ter_tripl", ter_tripl);
	
	Param(c,w, "graph_detail.view_dist", view_distance);	Param(c,w, "graph_detail.ter_detail", terdetail);
	Param(c,w, "graph_detail.ter_dist", terdist);			Param(c,w, "graph_detail.road_dist", road_dist);
	
	//  water
	Param(c,w, "graph_reflect.water_reflect", water_reflect); Param(c,w, "graph_reflect.water_refract", water_refract);
	Param(c,w, "graph_reflect.water_rttsize", water_rttsize);
	
	//  shadow
	Param(c,w, "graph_shadow.dist", shadow_dist);			Param(c,w, "graph_shadow.size", shadow_size);
	Param(c,w, "graph_shadow.count",shadow_count);			Param(c,w, "graph_shadow.type", shadow_type);

	//  veget
	Param(c,w, "graph_veget.grass", grass);
	Param(c,w, "graph_veget.trees_dist", trees_dist);		Param(c,w, "graph_veget.grass_dist", grass_dist);
	Param(c,w, "graph_veget.use_imposters", use_imposters); Param(c,w, "graph_veget.imposters_only", imposters_only);


	//  hud
	Param(c,w, "hud_show.fps", show_fps);

	//  gui tracks  ---
	Param(c,w, "gui_tracks.view", tracks_view);		Param(c,w, "gui_tracks.filter", tracks_filter);
	Param(c,w, "gui_tracks.sort", tracks_sort);		Param(c,w, "gui_tracks.sortup", tracks_sortup);

	//  columns, filters
	std::string s;
	int i,v,ii,a;
	
	if (w)	//  write
		for (v=0; v < 2; ++v)
		{
			s = "";  ii = COL_VIS;
			for (i=0; i < ii; ++i)
			{
				s += iToStr(col_vis[v][i]);
				if (i < ii-1)  s += " ";
			}
			Param(c,w, "gui_tracks.columns"+iToStr(v), s);

			s = "";  ii = COL_FIL;
			for (i=0; i < ii; ++i)
			{
				s += iToStr(col_fil[v][i]);
				if (i < ii-1)  s += " ";
			}
			Param(c,w, "gui_tracks.filters"+iToStr(v), s);
		}
	else	//  read
		for (v=0; v < 2; ++v)
		{
			if (Param(c,w, "gui_tracks.columns"+iToStr(v), s))
			{	std::stringstream sc(s);
				for (i=0; i < COL_VIS; ++i)
				{	sc >> a;  col_vis[v][i] = a > 0;  }
			}

			if (Param(c,w, "gui_tracks.filters"+iToStr(v), s))
			{	std::stringstream sf(s);
				for (i=0; i < COL_FIL; ++i)
				{	sf >> a;  col_fil[v][i] = a;  }
		}	}
コード例 #21
0
ファイル: BRLFile.cpp プロジェクト: feelpp/debian-gmsh
////////////////////////////////////////////////////////////////////////////////
// Construct TopoDS from BRL-CAD data
////////////////////////////////////////////////////////////////////////////////
BRLTopo::BRLTopo(struct rt_arb_internal *arb)
{
    TopoDS_Vertex v[8];
    for(int i=0;i<8;i++)
        v[i]=BRepBuilderAPI_MakeVertex(
            gp_Pnt(
                scale*arb->pt[i][0],
                scale*arb->pt[i][1],
                scale*arb->pt[i][2]
            )
        );

    int arbn;
    if(!BRepTools::Compare(v[6],v[7]))
        arbn=8;
    else if(!BRepTools::Compare(v[4],v[5]))
        arbn=7;
    else if(!BRepTools::Compare(v[5],v[6]))
        arbn=6;
    else if(!BRepTools::Compare(v[0],v[3]))
        arbn=5;
    else
        arbn=4;

    switch(arbn) {
    case 8: {
        TopoDS_Edge e[12];
        for(int i=0;i<4;i++) { 
            e[i]=BRepBuilderAPI_MakeEdge(v[i],v[(i+1)%4]);
            e[i+4]=BRepBuilderAPI_MakeEdge(v[i+4],v[(i+1)%4+4]);
            e[i+8]=BRepBuilderAPI_MakeEdge(v[i],v[(i+4)%8]);
        }

        TopoDS_Wire w[6];
        w[0]=BRepBuilderAPI_MakeWire(e[0],e[1],e[2],e[3]);
        w[1]=BRepBuilderAPI_MakeWire(e[4],e[5],e[6],e[7]);
        w[2]=BRepBuilderAPI_MakeWire(e[0],e[9],e[4],e[8]);
        w[3]=BRepBuilderAPI_MakeWire(e[1],e[10],e[5],e[9]);
        w[4]=BRepBuilderAPI_MakeWire(e[2],e[11],e[6],e[10]);
        w[5]=BRepBuilderAPI_MakeWire(e[3],e[8],e[7],e[11]);

        BRep_Builder BB;
        TopoDS_Shell shell;
        BB.MakeShell(shell);
        for(int i=0;i<6;i++) {
            TopoDS_Face f=BRepBuilderAPI_MakeFace(w[i]);
            BB.Add(shell,i? f.Reversed():f);
        }
        TopoDS_Solid solid;
        BB.MakeSolid(solid);
        BB.Add(solid,shell);
        ShapeFix_Solid sf(solid);
        sf.Perform();
        shape=sf.Solid();
        } break;
    case 6: {
        TopoDS_Edge e[9];
        e[0]=BRepBuilderAPI_MakeEdge(v[0],v[1]);
        e[1]=BRepBuilderAPI_MakeEdge(v[1],v[2]);
        e[2]=BRepBuilderAPI_MakeEdge(v[2],v[3]);
        e[3]=BRepBuilderAPI_MakeEdge(v[3],v[0]);
        e[4]=BRepBuilderAPI_MakeEdge(v[0],v[4]);
        e[5]=BRepBuilderAPI_MakeEdge(v[1],v[4]);
        e[6]=BRepBuilderAPI_MakeEdge(v[2],v[6]);
        e[7]=BRepBuilderAPI_MakeEdge(v[3],v[6]);
        e[8]=BRepBuilderAPI_MakeEdge(v[4],v[6]);

        TopoDS_Wire w[5];
        w[0]=BRepBuilderAPI_MakeWire(e[0],e[1],e[2],e[3]);
        w[1]=BRepBuilderAPI_MakeWire(e[0],e[4],e[5]);
        w[2]=BRepBuilderAPI_MakeWire(e[2],e[6],e[7]);
        w[3]=BRepBuilderAPI_MakeWire(e[3],e[4],e[8],e[7]);
        w[4]=BRepBuilderAPI_MakeWire(e[1],e[5],e[8],e[6]);

        BRep_Builder BB;
#if 0
        TopoDS_Compound result;
        BB.MakeCompound(result);
        for(int i=0;i<5;i++) {
            BB.Add(result,BRepBuilderAPI_MakeFace(w[i]));
        }
        shape=result;
#else
        TopoDS_Shell shell;
        BB.MakeShell(shell);
        for(int i=0;i<5;i++) {
            TopoDS_Face f=BRepBuilderAPI_MakeFace(w[i]);
            BB.Add(shell,f); //i? f:f.Reversed());
        }
        TopoDS_Solid solid;
        BB.MakeSolid(solid);
        BB.Add(solid,shell);
        ShapeFix_Solid sf(solid);
        sf.Perform();
        shape=sf.Solid();
#endif
        } break;
    default:
        cerr << "Unhandled arb8 type n=" << arbn << '\n';
    }
}
コード例 #22
0
ファイル: Tabs.cpp プロジェクト: AnthonyLu-Ista/sumatrapdf
    // Paints the tabs that intersect the window's update rectangle.
    void Paint(HDC hdc, RECT &rc) {
        IntersectClipRect(hdc, rc.left, rc.top, rc.right, rc.bottom);

        // paint the background
        bool isTranslucentMode = inTitlebar && dwm::IsCompositionEnabled();
        if (isTranslucentMode)
            PaintParentBackground(hwnd, hdc);
        else {
            HBRUSH brush = CreateSolidBrush(color.bar);
            FillRect(hdc, &rc, brush);
            DeleteObject(brush);
        }

        // TODO: GDI+ doesn't seem to cope well with SetWorldTransform
        XFORM ctm = { 1.0, 0, 0, 1.0, 0, 0 };
        SetWorldTransform(hdc, &ctm);

        Graphics graphics(hdc);
        graphics.SetCompositingMode(CompositingModeSourceCopy);
        graphics.SetCompositingQuality(CompositingQualityHighQuality);
        graphics.SetSmoothingMode(SmoothingModeHighQuality);
        graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
        graphics.SetPageUnit(UnitPixel);
        GraphicsPath shapes(data->Points, data->Types, data->Count);
        GraphicsPath shape;
        GraphicsPathIterator iterator(&shapes);

        SolidBrush br(Color(0, 0, 0));
        Pen pen(&br, 2.0f);

        Font f(hdc, GetDefaultGuiFont());
        // TODO: adjust these constant values for DPI?
        RectF layout((REAL)DpiScaleX(hwnd,3), 1.0f, REAL(width - DpiScaleX(hwnd,20)), (REAL)height);
        StringFormat sf(StringFormat::GenericDefault());
        sf.SetFormatFlags(StringFormatFlagsNoWrap);
        sf.SetLineAlignment(StringAlignmentCenter);
        sf.SetTrimming(StringTrimmingEllipsisCharacter);

        REAL yPosTab = inTitlebar ? 0.0f : REAL(ClientRect(hwnd).dy - height - 1);
        for (int i = 0; i < Count(); i++) {
            graphics.ResetTransform();
            graphics.TranslateTransform(1.f + (REAL)(width + 1) * i - (REAL)rc.left, yPosTab - (REAL)rc.top);

            if (!graphics.IsVisible(0, 0, width + 1, height + 1))
                continue;

            // in firefox style we only paint current and highlighed tabs
            // all other tabs only show
            bool onlyText = g_FirefoxStyle && !((current == i) || (highlighted == i));
            if (onlyText) {
#if 0
                // we need to first paint the background with the same color as caption,
                // otherwise the text looks funny (because is transparent?)
                // TODO: what is the damn bg color of caption? bar is too light, outline is too dark
                Color bgColTmp;
                bgColTmp.SetFromCOLORREF(color.bar);
                {
                    SolidBrush bgBr(bgColTmp);
                    graphics.FillRectangle(&bgBr, layout);
                }
                bgColTmp.SetFromCOLORREF(color.outline);
                {
                    SolidBrush bgBr(bgColTmp);
                    graphics.FillRectangle(&bgBr, layout);
                }
#endif
                // TODO: this is a hack. If I use no background and cleartype, the
                // text looks funny (is bold).
                // CompositingModeSourceCopy doesn't work with clear type
                // another option is to draw background before drawing text, but
                // I can't figure out what is the actual color of caption
                graphics.SetTextRenderingHint(TextRenderingHintAntiAliasGridFit);
                graphics.SetCompositingMode(CompositingModeSourceCopy);
                //graphics.SetCompositingMode(CompositingModeSourceOver);
                br.SetColor(ToColor(color.text));
                graphics.DrawString(text.At(i), -1, &f, layout, &sf, &br);
                graphics.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
                continue;
            }

            COLORREF bgCol = color.background;;
            if (current == i) {
                bgCol = color.current;
            } else if (highlighted == i) {
                bgCol = color.highlight;
            }

            // ensure contrast between text and background color
            // TODO: adjust threshold (and try adjusting both current/background tabs)
            COLORREF textCol = color.text;
            float bgLight = GetLightness(bgCol), textLight = GetLightness(textCol);
            if (textLight < bgLight ? bgLight < 0x70 : bgLight > 0x90)
                textCol = textLight ? AdjustLightness(textCol, 255.0f / textLight - 1.0f) : RGB(255, 255, 255);
            if (fabs(textLight - bgLight) < 0x40)
                textCol = bgLight < 0x80 ? RGB(255, 255, 255) : RGB(0, 0, 0);

            // paint tab's body
            graphics.SetCompositingMode(CompositingModeSourceCopy);
            iterator.NextMarker(&shape);
            br.SetColor(ToColor(bgCol));
            graphics.FillPath(&br, &shape);

            // draw tab's text
            graphics.SetCompositingMode(CompositingModeSourceOver);
            br.SetColor(ToColor(textCol));
            graphics.DrawString(text.At(i), -1, &f, layout, &sf, &br);

            // paint "x"'s circle
            iterator.NextMarker(&shape);
            if (xClicked == i || xHighlighted == i) {
                br.SetColor(ToColor(i == xClicked ? color.x_click : color.x_highlight));
                graphics.FillPath(&br, &shape);
            }

            // paint "x"
            iterator.NextMarker(&shape);
            if (xClicked == i || xHighlighted == i)
                pen.SetColor(ToColor(color.x_line));
            else
                pen.SetColor(ToColor(color.outline));
            graphics.DrawPath(&pen, &shape);
            iterator.Rewind();
        }
    }
コード例 #23
0
ファイル: SeqPrefWin.cpp プロジェクト: dtbinh/Sequitur
BView* SeqPrefWin::NewFileView(BRect bounds, const BMessage& prefs) const
{
	BView*		v = new BView( bounds, FILE_STR, B_FOLLOW_ALL, 0 );
	if( !v ) return v;
	v->SetViewColor( Prefs().Color(AM_AUX_WINDOW_BG_C) );
	float		fh = view_font_height(v);
	float		bfh = bold_font_height();
	float		openH = bfh + 5 + fh + 5 + fh + 5 + fh;
	/* The Remember Open Songs preference.
	 */
	float		w = v->StringWidth("Remember open songs") + 25;
	BRect		f(bounds.left + 5, bounds.top + 5, bounds.left + 5 + w, bounds.top + 5 + fh);
	BCheckBox*	cb = new BCheckBox( f, REMEMBER_OPEN_STR, "Remember open songs", new BMessage(REMEMBER_OPEN_MSG) );
	if( cb ) {
		bool	b;
		if( prefs.FindBool(REMEBER_OPEN_SONGS_PREF, &b) != B_OK ) b = false;
		cb->SetValue( (b) ? B_CONTROL_ON : B_CONTROL_OFF );
		v->AddChild( cb );
	}
	/* The Skin preference.
	 */
	BMenu*		menu = new BMenu("skin_menu");
	BMessage	skinMsg(CHANGE_SKIN_MSG);
	BMenuItem*	item = new BMenuItem( "Default", new BMessage(CHANGE_SKIN_TO_DEFAULT_MSG) );
	item->SetMarked(true);
	menu->AddItem(item);
	menu->AddSeparatorItem();
	menu->SetLabelFromMarked(true);
	if( seq_make_skin_menu(menu, &skinMsg) == B_OK ) {
		const char*	label = "Choose skin:";
		f.Set(f.left, f.bottom + 8, bounds.right - 5, f.bottom + 8 + fh + 10);
		BMenuField*	field = new BMenuField(f, "skin_field", label, menu);
		if (field) {
			field->SetDivider( v->StringWidth(label) + 10 );
			v->AddChild(field);
		} else delete menu;
	} else delete menu;

	/* The Open New Songs preferences.
	 */
	f.Set(bounds.left + 5, f.bottom + 10, bounds.right - 5, f.bottom + 10 + openH + 10);
	BBox*		box = new BBox( f,
								"open_new_songs",
								B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP);
	if( box ) {
		box->SetLabel( "Open New Songs" );
		BRect		boxB = box->Bounds();
		BRect		sf(boxB.left + 5, boxB.top + 5 + bfh, boxB.right - 5, boxB.top + 5 + bfh + fh);
		const char*	choice;
		if( prefs.FindString(OPEN_NEW_SONG_PREF, &choice) != B_OK ) choice = 0;
		BRadioButton*	button = new BRadioButton( sf, OPEN_BLANK_STR, "Blank", new BMessage(OPEN_BLANK_MSG), B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP );
		if( button ) {
			if( choice && strcmp(choice, "blank") == 0 ) button->SetValue( B_CONTROL_ON );
			box->AddChild( button );
		}
		sf.OffsetBy( 0, 5 + fh );
		button = new BRadioButton( sf, OPEN_FOUR_STR, "With two channels of each device", new BMessage(OPEN_FOUR_MSG), B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP );
		if( button ) {
			if( choice && strcmp(choice, "channels") == 0 ) button->SetValue( B_CONTROL_ON );
			box->AddChild( button );
		}
		sf.OffsetBy( 0, 5 + fh );
		button = new BRadioButton( sf, OPEN_FILE_STR, "From file: <click to select>", new BMessage(OPEN_FILE_MSG), B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP );
		if( button ) {
			if( choice && strcmp(choice, "file") == 0 ) button->SetValue( B_CONTROL_ON );
			entry_ref	ref;
			if( prefs.FindRef(OPEN_NEW_SONG_FILE_PREF, &ref) == B_OK )
				button->SetLabel( label_for_open_new_from_file(&ref).String() );
			box->AddChild( button );
		}
		v->AddChild( box );
		f.OffsetBy(0, f.bottom - f.top + 10 );
	}
	/* The Open From Query preferences
	 */
	f.bottom = bounds.bottom - 27;
	box = new BBox( f, "open_from_query", B_FOLLOW_ALL);
	if( box ) {
		box->SetLabel("Open From Query");

		BRect			boxB = box->Bounds();
		BRect			tableF(boxB.left + 5, boxB.top + 5 + bfh, boxB.right - 5, boxB.bottom - 35);
		mOwqTable = new _OwqList( tableF, mPreferences );
		if( mOwqTable ) {
			mOwqTable->SetLatchWidth( 0 );
			box->AddChild( mOwqTable );
			mOwqTable->AddColumn( new BStringColumn(ON_STR, 40, 20, 100, B_TRUNCATE_END), 0 );
			mOwqTable->AddColumn( new BStringColumn(NAME_STR, 100, 20, 150, B_TRUNCATE_END), 1 );
			mOwqTable->AddColumn( new BStringColumn(QUERY_STR, 180, 20, 450, B_TRUNCATE_MIDDLE), 2 );
//			mOwqTable->AddColumn( new BStringColumn(SKIP_TOP_LEVEL_STR, 100, 20, 250, B_TRUNCATE_END), 3 );
			mOwqTable->SetSortColumn(mOwqTable->ColumnAt(1), false, true);
//			mOwqTable->SetSortColumn(mOwqTable->ColumnAt(), true, true);
			mOwqTable->SetSelectionMode( B_SINGLE_SELECTION_LIST );

			BRect		bF(tableF.left, tableF.bottom + 5, tableF.left + 55, tableF.Height() - 10);
			BButton*	add = new BButton( bF, "owq_add", "Add", new BMessage(OWQ_INVOKE_ADD), B_FOLLOW_LEFT | B_FOLLOW_BOTTOM );
			if( add ) box->AddChild( add );
			bF.OffsetBy( bF.Width() + 5, 0 );
			BButton*	change = new BButton( bF, "owq_change", "Change", new BMessage(OWQ_CHANGE), B_FOLLOW_LEFT | B_FOLLOW_BOTTOM );
			if( change ) {
				change->SetEnabled( false );
				box->AddChild( change );
			}
			bF.OffsetBy( bF.Width() + 5, 0 );
			BButton*	remove = new BButton( bF, "owq_remove", "Remove", new BMessage(OWQ_REMOVE), B_FOLLOW_LEFT | B_FOLLOW_BOTTOM );
			if( remove ) {
				remove->SetEnabled( false );
				box->AddChild( remove );
			}
			mOwqTable->SetButtons( add, change, remove );
		}
		v->AddChild( box );
	}
	return v;
}
コード例 #24
0
ファイル: til2img.cpp プロジェクト: asimonov-im/fheroes2
int main(int argc, char **argv)
{
    if(argc != 3)
    {
	std::cout << argv[0] << " [-d] infile.til extract_to_dir" << std::endl;

	return EXIT_SUCCESS;
    }

    std::fstream fd_data(argv[1], std::ios::in | std::ios::binary);

    if(fd_data.fail())
    {
	std::cout << "error open file: " << argv[1] << std::endl;

	return EXIT_SUCCESS;
    }

    std::string prefix(argv[2]);
    std::string shortname(argv[1]);
    
    if(shortname == "-d")
    {
    }

    shortname.replace(shortname.find("."), 4, "");
    
    prefix += SEPARATOR + shortname;

    if(0 != MKDIR(prefix.c_str()))
    {
	std::cout << "error mkdir: " << prefix << std::endl;

	return EXIT_SUCCESS;
    }

    fd_data.seekg(0, std::ios_base::end);
    u32 size = fd_data.tellg();
    fd_data.seekg(0, std::ios_base::beg);

    u16 count, width, height;
    
    fd_data.read(reinterpret_cast<char *>(&count), sizeof(u16));
    SwapLE16(count);

    fd_data.read(reinterpret_cast<char *>(&width), sizeof(u16));
    SwapLE16(width);

    fd_data.read(reinterpret_cast<char *>(&height), sizeof(u16));
    SwapLE16(height);

    char *body = new char[size];

    fd_data.read(body, size);

    SDL::Init();

    for(u16 cur = 0; cur < count; ++cur)
    {
	Surface sf(&body[width * height * cur], width, height, 1, false);
	std::string dstfile(prefix);

	dstfile += SEPARATOR;

	std::ostringstream stream;
        stream << cur;

        switch(stream.str().size())
        {
    	    case 1:
    		dstfile += "00" + stream.str();
    		break;

    	    case 2:
    		dstfile += "0" + stream.str();
    		break;

    	    default:
    		dstfile += stream.str();
    		break;
        }

#ifndef WITH_IMAGE
        dstfile += ".bmp";
#else
        dstfile += ".png";
#endif
        sf.Save(dstfile.c_str());
    }

    delete [] body;

    fd_data.close();

    std::cout << "expand to: " << prefix << std::endl;

    SDL::Quit();

    return EXIT_SUCCESS;
}
コード例 #25
0
ファイル: CCFGReader.cpp プロジェクト: XadillaX/xaengine
int CCFGReader::GetString(const char* key, const char* split, string out[], int maxcount)
{
    string value = GetString(key);
    XStringFunc sf(value);
    return sf.Split(split, out, maxcount);
}
コード例 #26
0
ファイル: dragdrop.cpp プロジェクト: littlemole/moe
std::vector<std::wstring> vectorFromDataObject(IDataObject* ido)
{
	//ODBGS("vectorFromDataObject");

	static UINT fssh = ::RegisterClipboardFormat(L"MOESSHDATATRANSFEROBJ");

	mol::format_etc				fde = mol::format_etc( fssh );
	format_etc_dropfile			fe;

	STGMEDIUM					sm;
	wchar_t*					fname   = 0;
	int							len		= 0;
	int							n		= 0;
	
	std::vector<std::wstring>	v;

	if (!ido)
		return v;
	
	if ( S_OK != ido->GetData( &fe, &sm ) )
	{
		
		if ( S_OK != ido->GetData(&fde,&sm) )
		{
			format_etc_shellpidl spidl;
			if ( S_OK != ido->GetData( &spidl, &sm ) )
			  return v;

			CIDA* cida = 0;
			mol::global glob(sm.hGlobal);
			cida = (CIDA*)glob.lock();

			LPCITEMIDLIST folder = molGetPIDLFolder(cida);		
			mol::io::ShellFolder sf( (LPITEMIDLIST)folder);
			std::wstring parent = mol::io::desktop().getDisplayNameOf((LPITEMIDLIST)folder);
			if ( sf )
			{
				int n = cida->cidl;
				for ( int i = 0; i < n; i++ )
				{
					LPCITEMIDLIST item = molGetPIDLItem(cida,i);
					//std::wstring s = mol::io::desktop().getDisplayNameOf((LPITEMIDLIST)item,SHGDN_FORPARSING);				
					//std::wstring s2 = sf.getDisplayNameOf((LPITEMIDLIST)item,SHGDN_INFOLDER);
					std::wstring s3 = sf.getDisplayNameOf((LPITEMIDLIST)item,SHGDN_FORPARSING);
					v.push_back(s3);
				}
			}
			glob.unLock();
			glob.detach();
			::ReleaseStgMedium(&sm);
			return v;
		}
	}

	if ( sm.tymed != TYMED_HGLOBAL )
		return v;

	mol::global glob(sm.hGlobal);
	HDROP hDrop = (HDROP) glob.lock();
	if ( hDrop )
	{
		n   = ::DragQueryFile( hDrop, 0xFFFFFFFF,0,0);
		int i = 0;
		while(true)
		{
			len = ::DragQueryFile( hDrop, i, 0, 0 );
			if (!len )
				break;

			mol::wbuff buf(len+1);
			::DragQueryFile( hDrop, i, buf, len+1 );
			v.push_back(buf.toString());
			i++;
		}
		glob.unLock();
	}
	glob.detach();
	::ReleaseStgMedium(&sm);
	return v;
}
コード例 #27
0
ファイル: main.c プロジェクト: kod3r/cpp-cheat
void m() {
    f();
    sf();
}
コード例 #28
0
ファイル: VideoTesting.cpp プロジェクト: 1234gary/SubZero
//==============================================================
void VideoTesting::run(int Type){
    //for (int i = 0; i < 2*33; i++) getNextFrame();
    cv::namedWindow("Orginal",CV_WINDOW_AUTOSIZE);
    cv::namedWindow("HSV Filtered",CV_WINDOW_AUTOSIZE);
    cv::namedWindow("Line Filtered",CV_WINDOW_AUTOSIZE);
    cv::namedWindow("Canny", CV_WINDOW_AUTOSIZE);

    if (Type == 2){
    cv::moveWindow("Orginal", 1400, 50);           //reading from photo
    cv::moveWindow("HSV Filtered", 1000, 50);
    cv::moveWindow("Line Filtered", 600, 50);
    cv::moveWindow("Canny", 100, 50);}
    else if (Type == 1){
    cv::moveWindow("Orginal", 1200, 50);           //reading from camera
    cv::moveWindow("HSV Filtered", 1200, 500);
    cv::moveWindow("Line Filtered", 600, 50);
    cv::moveWindow("Canny", 600, 500);}
    else if (Type == 0){
    cv::moveWindow("Orginal", 1400, 100);         //reading from video
    cv::moveWindow("HSV Filtered", 1400, 500);
    cv::moveWindow("Line Filtered", 800, 100);
    cv::moveWindow("Canny", 800, 500);}

    cv::Mat frame;
    cv::Mat filtered;
    cv::Mat filtered2;
    cv::Mat lineFiltered;
    cv::Mat contour;

    cv::namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
    int iLowH = 5;
    int iHighH = 105;
    int iLowS = 10;
    int iHighS = 59;
    int iLowV = 0;
    int iHighV = 237;
    int max = 1;
    //Create trackbars in "Control" window
    cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
    cvCreateTrackbar("HighH", "Control", &iHighH, 179);
    cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
    cvCreateTrackbar("HighS", "Control", &iHighS, 255);
    cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
    cvCreateTrackbar("HighV", "Control", &iHighV, 255);
    cvCreateTrackbar("max", "Control", &max, 130);

    //HSVFilter hf(25, 179, 0, 255, 0,255);
    LineFilter lf;
    ShapeFilter sf(1, 1);
    BlurFilter bf(2, 0.2f);
    BlurFilter bf2(1, 0.4f);
    if (Type == 0)
        frame = cv::imread("test_path.png");       //img
    cv::Scalar color = cv::Scalar(255, 0, 0);

    while (1){
        //contour = cv::Mat::zeros(frame.size(), CV_8UC3);
        if (Type == 2)
            frame = this->getNextFrame(); //video
        if (Type == 1)
            frame = getNextCameraFrame(); //webcam
        contour = frame.clone();
        if(frame.cols == 0)break;       //exit when there is no next fraame

        //filtered = hf.filter(&frame);
        filtered2 = HSVFilter(frame, iLowH, iHighH, iLowS, iHighS, iLowV, iHighV);
        filtered = HSVFilter(frame, iLowH, iHighH, iLowS, iHighS, iLowV, iHighV);
        //filtered = blur(filtered,max);
        //filtered = bf.filter(filtered2);
        //filtered = bf2.filter(filtered);
        lineFiltered = lf.filter(filtered, 0);
        //lineFiltered = Moments(filtered);

        //draw rectangle
        if (sf.findRect(filtered)){
            std::vector<cv::RotatedRect> rect = sf.getRect();
            for (cv::RotatedRect rekt: rect){
                cv::Point2f rect_points[4]; rekt.points( rect_points );
                for( int j = 0; j < 4; j++ )
                   line( contour, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );
                //delete rect;
                std::cout<<rekt.angle<<std::endl;
                cv::Point2f ps[4];
                rekt.points(ps);
                std::cout << ps[0] << " " << ps[1] << " " << ps[2] << " " << ps[3] << std::endl;
            }
        }

        //draw circle
        if (sf.findCirc(filtered)){
            auto rad = sf.getRad();
            auto cent = sf.getCenter();
            //radius
            for (unsigned int i = 0; i < rad.size(); i++){
                cv::circle(lineFiltered, cent[i], rad[i], cv::Scalar(255,0,0) );
            }
            //center
            for (unsigned int i = 0; i < rad.size(); i++){
                cv::circle(lineFiltered, cent[i], 2, cv::Scalar(0,255,0));
            }
        }

        //gets the mass center; testing purposes only
        auto t = sf.findMassCenter(filtered);
        for (cv::Point2f p: t){
            cv::circle(lineFiltered, p, 2, cv::Scalar(0,0,255));
        }

        imshow("Orginal", frame);
        imshow("HSV Filtered", filtered);
        imshow("Line Filtered", lineFiltered);
        imshow("Canny", contour);
        int key = cv::waitKey((33));        //wait for 33ms, ~= 30fps;
        //std::cout<<key<<std::endl;
        if (key == 27) break;               //if user press esc, break the loop
        else if(key == 98) cv::waitKey(0);  //"b" key, "pasues" play

        /*delete filtered;
        delete filtered2;
        delete lineFiltered;*/
    }
    cvReleaseCapture(&capture);
    //cap.release();
    std::cout << "End of video feed" << std::endl;
}
コード例 #29
0
void FOOTPRINT_EDIT_FRAME::ProcessPreferences( wxCommandEvent& event )
{
    int id = event.GetId();

    switch( id )
    {
    // Hotkey IDs
    case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG:
        ExportHotkeyConfigToFile( g_Module_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_IMPORT_CONFIG:
        ImportHotkeyConfigFromFile( g_Module_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_EDITOR:
        InstallHotkeyFrame( this, g_Module_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST:
        // Display current hotkey list for the footprint editor.
        DisplayHotkeyList( this, g_Module_Editor_Hokeys_Descr );
        break;

    case ID_PCB_LIB_WIZARD:
    case ID_PCB_LIB_TABLE_EDIT:
        {
            bool tableChanged = false;
            int r = 0;

            if( id == ID_PCB_LIB_TABLE_EDIT )
                r = InvokePcbLibTableEditor( this, &GFootprintTable, Prj().PcbFootprintLibs() );
            else
                r = InvokeFootprintWizard( this, &GFootprintTable, Prj().PcbFootprintLibs() );

            if( r & 1 )
            {
                try
                {
                    FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() );

                    GFootprintTable.Format( &sf, 0 );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving the global footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText.GetData() )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            if( r & 2 )
            {
                wxString tblName = Prj().FootprintLibTblName();

                try
                {
                    Prj().PcbFootprintLibs()->Save( tblName );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving project specific footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            FOOTPRINT_VIEWER_FRAME* viewer;
            viewer = (FOOTPRINT_VIEWER_FRAME*)Kiway().Player( FRAME_PCB_MODULE_VIEWER, false );

            if( tableChanged && viewer != NULL )
                viewer->ReCreateLibraryList();
        }
        break;

    case wxID_PREFERENCES:
        InvokeFPEditorPrefsDlg( this );
        break;

    default:
        DisplayError( this, wxT( "FOOTPRINT_EDIT_FRAME::ProcessPreferences error" ) );
    }
}
コード例 #30
0
ファイル: ProgressCtrlX.cpp プロジェクト: dalinhuang/dmibox
void CProgressCtrlX::DrawText(const CDrawInfo& info, const CRect &rcMax, const CRect &rcBar)
{
	if(!(info.dwStyle&PBS_TEXTMASK))
		return;
	BOOL fVert = info.dwStyle&PBS_VERTICAL;
	CDC *pDC = info.pDC;
	int nValue = 0;
	CString sFormat;
	GetWindowText(sFormat);
	switch(info.dwStyle&PBS_TEXTMASK)
	{
		case PBS_SHOW_PERCENT:
			if(sFormat.IsEmpty())
				sFormat = _T("%d%%");
			// retrieve current position and range
			nValue = (int)((float)(info.nCurPos-info.nLower) * 100 / ((info.nUpper-info.nLower == 0) ? 1 : info.nUpper-info.nLower));
			break;
		case PBS_SHOW_POSITION:
			if(sFormat.IsEmpty())
				sFormat = _T("%d");
			// retrieve current position
			nValue = info.nCurPos;
			break;
	}

	if (sFormat.IsEmpty())
		return;

	CFont* pFont = GetFont();
	CSelFont sf(pDC, pFont);
	CSelTextColor tc(pDC, m_clrTextOnBar);
	CSelBkMode bm(pDC, TRANSPARENT);
	CSelTextAlign	ta(pDC, TA_BOTTOM|TA_CENTER);
  CPoint ptOrg = pDC->GetWindowOrg();
	CString sText;
	sText.Format(sFormat, nValue);
	
	LONG grad = 0;
	if(pFont)
	{
		LOGFONT lf;
		pFont->GetLogFont(&lf);
		grad = lf.lfEscapement/10;
	}
	int x = 0, y = 0, dx = 0, dy = 0;
	CSize sizText = pDC->GetTextExtent(sText);
	if(grad == 0)         {	x = sizText.cx; y = sizText.cy; dx = 0; dy = sizText.cy;}
	else if(grad == 90)   {	x = sizText.cy; y = sizText.cx; dx = sizText.cy; dy = 0;}
	else if(grad == 180)  {	x = sizText.cx; y = sizText.cy; dx = 0; dy = -sizText.cy;}
	else if(grad == 270)  {	x = sizText.cy; y = sizText.cx; dx = -sizText.cy; dy = 0;}
	else ASSERT(0); // angle not supported
	CPoint pt = pDC->GetViewportOrg();
	if(info.dwStyle&PBS_TIED_TEXT)
	{
		CRect rcFill(ConvertToReal(info, rcBar));
		if((fVert ? y : x) <= rcBar.Width())
		{
			pDC->SetViewportOrg(rcFill.left + (rcFill.Width() + dx)/2, 
													rcFill.top + (rcFill.Height() + dy)/2);
			DrawClippedText(info, rcBar, sText, ptOrg);
		}
	}
	else
	{
		pDC->SetViewportOrg(info.rcClient.left + (info.rcClient.Width() + dx)/2, 
												info.rcClient.top + (info.rcClient.Height() + dy)/2);
		if(m_clrTextOnBar == m_clrTextOnBk)
			// if the same color for bar and background draw text once
			DrawClippedText(info, rcMax, sText, ptOrg);
		else
		{	
			// else, draw clipped parts of text
			
			// draw text on gradient
			if(rcBar.left != rcBar.right)
				DrawClippedText(info, rcBar, sText, ptOrg);

			// draw text out of gradient
			if(rcMax.right > rcBar.right)
			{
				tc.Select(m_clrTextOnBk);
				CRect rc(rcMax);
				rc.left = rcBar.right;
				DrawClippedText(info, rc, sText, ptOrg);
			}
			if(rcMax.left < rcBar.left)
			{
				tc.Select(m_clrTextOnBk);
				CRect rc(rcMax);
				rc.right = rcBar.left;
				DrawClippedText(info, rc, sText, ptOrg);
			}
		}
	}
	pDC->SetViewportOrg(pt);
}