Пример #1
0
Prop *Prop::AllocTextAlign(AlignAttr align)
{
    Prop p(PropTextAlign);
    p.textAlign = align;
    return UniqifyProp(p);
}
Пример #2
0
double MxSegment<DIM>::volumeFraction(const MxShape<DIM> & aShape, const MxDimVector<double, DIM> & midPt) const {

  MxDimVector<double, DIM> p1(midPt + 0.5 * len * dir);
  MxDimVector<double, DIM> p2(midPt - 0.5 * len * dir);
  double f1 = aShape.func(p1);
  double f2 = aShape.func(p2);
  int f1s = MxUtil::sign(f1);
  int f2s = MxUtil::sign(f2);

  if ((f1s == 1 and f2s != -1) or (f2s == 1 and f1s != -1)) {
    return 1;
  } else if ((f1s == -1 and f2s != 1) or (f2s == -1 and f1s != 1)) {
    return 0;
  } else if (f1s == 0 and f2s == 0) {
    return MxUtil::sign(aShape.func(midPt)) == 1 ? 1 : 0;
  } else {                                                                         // bracketing
    MxDimVector<double, DIM> p(MxUtil::rootFind<MxShape<DIM>, DIM>(aShape, p1, p2, 1.e-12, 20));
    if (f1s == 1)
      return (p - p1).norm() / len;
    else
      return (p - p2).norm() / len;
  }

#if 0
  if      ((f1 > MxUtil::dEps and f2 > -MxUtil::dEps) or 
           (f2 > MxUtil::dEps and f1 > -MxUtil::dEps)) return 1.0;     // one in, other in or on
  else if ((f1 < -MxUtil::dEps and f2 < MxUtil::dEps) or
           (f2 < -MxUtil::dEps and f1 < MxUtil::dEps)) return 0.0;     // one out, other out or on
  else if (fabs(f1) < MxUtil::dEps and fabs(f2) < MxUtil::dEps) {      // both on
    if (aShape.func(midPt) > MxUtil::dEps) return 1.0;
    else return 0.0;
  }
  else {                                                                         // bracketing
    MxDimVector<double, DIM> p(MxUtil::rootFind<MxShape<DIM>, DIM>(aShape, p1, p2, 1.e-12, 20));
    if (f1 > MxUtil::dEps)
      return (p - p1).norm() / len;
    else
      return (p - p2).norm() / len;
  }
#endif

#if 0
  if (f1 * f2 > 0.0) {
    if (f1 > 0.0)
      return 1.0;
    else
      return 0.0;
  }
  else if (f1 == 0.0 and f2 == 0.0) {
    if (aShape.func(midPt) > 0.0) return 1.0;
    else return 0.0;
  }
  else if (f1 * f2 == 0.0) {
    if (f1 > 0.0 or f2 > 0.0) return 1.0;
    else return 0.0;
  }
  else {
    MxDimVector<double, DIM> p(MxUtil::rootFind<MxShape<DIM>, DIM>(aShape, p1, p2, 1.e-12, 20));
    if (f1 > 0.0)
      return (p - p1).norm() / len;
    else
      return (p - p2).norm() / len;
  }
#endif

}
Пример #3
0
unsigned int IOFactory::findPlugins( const std::string &path )
{
	boost::filesystem::path p( path );

	if ( !exists( p ) ) {
		LOG( Runtime, warning ) << util::MSubject( p ) << " not found";
		return 0;
	}

	if ( !boost::filesystem::is_directory( p ) ) {
		LOG( Runtime, warning ) << util::MSubject( p ) << " is no directory";
		return 0;
	}

	LOG( Runtime, info )   << "Scanning " << util::MSubject( p ) << " for plugins";
	boost::regex pluginFilter( std::string( "^" ) + DL_PREFIX + "isisImageFormat_" + "[[:word:]]+" + DL_SUFFIX + "$", boost::regex::perl | boost::regex::icase );
	unsigned int ret = 0;

	for ( boost::filesystem::directory_iterator itr( p ); itr != boost::filesystem::directory_iterator(); ++itr ) {
		if ( boost::filesystem::is_directory( *itr ) )continue;

		if ( boost::regex_match( itr->path().filename().string(), pluginFilter ) ) {
			const std::string pluginName = itr->path().native();
#ifdef WIN32
			HINSTANCE handle = LoadLibrary( pluginName.c_str() );
#else
			void *handle = dlopen( pluginName.c_str(), RTLD_NOW );
#endif

			if ( handle ) {
#ifdef WIN32
				image_io::FileFormat* ( *factory_func )() = ( image_io::FileFormat * ( * )() )GetProcAddress( handle, "factory" );
#else
				image_io::FileFormat* ( *factory_func )() = ( image_io::FileFormat * ( * )() )dlsym( handle, "factory" );
#endif

				if ( factory_func ) {
					FileFormatPtr io_class( factory_func(), _internal::pluginDeleter( handle, pluginName ) );

					if ( registerFileFormat( io_class ) ) {
						io_class->plugin_file = pluginName;
						ret++;
					} else {
						LOG( Runtime, warning ) << "failed to register plugin " << util::MSubject( pluginName );
					}
				} else {
#ifdef WIN32
					LOG( Runtime, warning )
							<< "could not get format factory function from " << util::MSubject( pluginName );
					FreeLibrary( handle );
#else
					LOG( Runtime, warning )
							<< "could not get format factory function from " << util::MSubject( pluginName ) << ":" << util::MSubject( dlerror() );
					dlclose( handle );
#endif
				}
			} else
#ifdef WIN32
				LOG( Runtime, warning ) << "Could not load library " << util::MSubject( pluginName );

#else
				LOG( Runtime, warning ) << "Could not load library " << util::MSubject( pluginName ) << ":" <<  util::MSubject( dlerror() );
#endif
		} else {
			LOG( Runtime, verbose_info ) << "Ignoring " << *itr << " because it doesn't match " << pluginFilter.str();
		}
	}

	return ret;
}
Пример #4
0
void
StatsGauge::paintEvent( QPaintEvent* event )
{
    QPainter p( this );
    p.setRenderHint( QPainter::Antialiasing );
    p.setClipRect( event->rect() );

    QSize gaugeSize = m_sizeHint - QSize( 0, 40 );

    QPen pen( TomahawkStyle::NOW_PLAYING_ITEM.lighter() );
    pen.setWidth( 16 );
    p.setPen( pen );

    int fullCircle = 16 * 360;
    p.drawArc( QRect( 12, 12, gaugeSize.width() - 24, gaugeSize.height() - 24 ),
               4*360, (int)( -1.0 * (float)fullCircle * ( invertedAppearance() ? ( 1.0 - m_percentage ) : m_percentage ) ) );

    pen = QPen( TomahawkStyle::NOW_PLAYING_ITEM.darker() );
    pen.setWidth( 6 );
    p.setPen( pen );

    QBrush brush( QColor( "#252020" ) );
    p.setBrush( brush );
    p.drawEllipse( QRect( 28, 28, gaugeSize.width() - 56, gaugeSize.height() - 56 ) );

    pen = QPen( Qt::white );
    p.setPen( pen );
    QFont font = p.font();
    font.setWeight( QFont::Black );

    if ( value() <= 999 )
        font.setPixelSize( 60 );
    else
        font.setPixelSize( 44 );

    p.setFont( font );
    QRect textRect( 0, gaugeSize.height() / 2 - 14, gaugeSize.width(), 62 );
    p.drawText( textRect, Qt::AlignCenter, value() > 0 ? QString::number( value() ) : "-" );

    pen = QPen( QColor( "#8b8b8b" ) );
    p.setPen( pen );
    font = p.font();
    font.setWeight( QFont::Black );
    font.setPixelSize( 16 );
    p.setFont( font );

    textRect = QRect( 0, gaugeSize.height() / 2 - 32, gaugeSize.width(), 20 );
    p.drawText( textRect, Qt::AlignCenter, maximum() > 0 ? tr( "out of %1" ).arg( maximum() ) : "-" );

    if ( !m_text.isEmpty() )
    {
        pen = QPen( Qt::white );
        p.setPen( pen );
        font = p.font();
        font.setWeight( QFont::DemiBold );
        font.setPixelSize( 16 );
        p.setFont( font );

        QColor figColor( "#3e3e3e" );
        p.setBrush( figColor );

        QFontMetrics fm( font );
        int textWidth = fm.width( m_text );
        textRect = QRect( m_sizeHint.width() / 2 - ( textWidth / 2 + 12 ), m_sizeHint.height() - 32, textWidth + 24, 28 );

        TomahawkUtils::drawBackgroundAndNumbers( &p, m_text, textRect );
    }
}
void ContextTile::paintEvent(QPaintEvent *) {
	QStyleOption o;
	o.initFrom(this);
	QPainter p(this);
	style()->drawPrimitive(QStyle::PE_Widget, &o, &p, this);
}
Пример #6
0
void DiagramCanvas::paint_all( QRect& r )
{
    int i;
    QPainter p( &buffer );
    QPen pen;
    QBrush brush;
    QPointArray a;
    QColor color;
    QRegion mask, crossing_disk;
    set<double>::iterator dbl_it;

    for ( i=0; i<crossingList.size(); ++i )
    {
        Crossing *c = crossingList[i];

        c->under->underpasses.insert( c->under->underpasses.end(), c->position_on_understrand );
    }

    for ( i=0; i<edgeList.size(); ++i )
    {
        Edge *e = edgeList[i];

        pen.setWidth( e->thickness );
        pen.setColor( CANVAS );
        p.setPen( pen );

        QPoint v, v1, v2, p1, p2 ;

        p1 = e->vertex[begin]->position;
        p2 = e->vertex[end]->position;
        p.drawLine( p1, p2 );
/*
      if (e->edge_type==singular)
        {

                v = p1 - p2;
                v1.setX( v.x() - v.y() );
                v1.setY( v.x() + v.y() );
                v2.setX( v.x() + v.y() );
                v2.setY( -v.x() + v.y() );

                v1 = 5 * v1 / sqrt( double (v1.x() * v1.x() + v1.y() * v1.y()) );
                v2 = 5 * v2 / sqrt( double (v2.x() * v2.x() + v2.y() * v2.y()) );
                v  = v / 2;
                pen.setWidth( ARROW );
                p.setPen( pen );
                p.drawLine( p2+v, p2+v1+v );
                p.drawLine( p2+v, p2+v2+v );
        }
*/
    }

    for ( i=0; i<edgeList.size(); ++i )
    {
        Edge *e = edgeList[i];

        color = (e->edge_type == drilled) ? DRILLED : colorList[e->arc_id % 18 ];

        pen.setWidth( e->thickness );
        pen.setColor( color );
        p.setPen( pen );

        brush.setColor( color );
        brush.setStyle( SolidPattern );
        p.setBrush( brush );

        if ( e->underpasses.size() > 0 )
        {
            p.setClipping( TRUE );
            mask = QRegion( 0, 0, width(), height(), QRegion::Rectangle );

            for ( dbl_it=e->underpasses.begin(); dbl_it!=e->underpasses.end(); ++dbl_it )
            {
                QPoint center = time_to_point( e, *dbl_it );
                crossing_disk = QRegion( center.x()-7, center.y()-7, 14, 14 , QRegion::Ellipse );
                mask -= crossing_disk;
            }

            p.setClipRegion( mask );
            QPoint v, v1, v2, p1, p2 ;

            p1 = e->vertex[begin]->position;
            p2 = e->vertex[end]->position;
            p.drawLine( p1, p2 );
/*
            if (e->edge_type==singular)
            {
                v = p1 - p2;
                v1.setX( v.x() - v.y() );
                v1.setY( v.x() + v.y() );
                v2.setX( v.x() + v.y() );
                v2.setY( -v.x() + v.y() );

                v1 = 5 * v1 / sqrt( double (v1.x() * v1.x() + v1.y() * v1.y()) );
                v2 = 5 * v2 / sqrt( double (v2.x() * v2.x() + v2.y() * v2.y()) );
                v  = v / 2;
                pen.setWidth( ARROW );
                p.setPen( pen );
                p.drawLine( p2+v, p2+v1+v );
                p.drawLine( p2+v, p2+v2+v );
            }
*/
            p.setClipping( FALSE );
        }

        else
        {
            QPoint v, v1, v2, p1, p2 ;

            p1 = e->vertex[begin]->position;
            p2 = e->vertex[end]->position;
            p.drawLine( p1, p2 );
/*
            if (e->edge_type==singular)
            {
                v = p1 - p2;
                v1.setX( v.x() - v.y() );
                v1.setY( v.x() + v.y() );
                v2.setX( v.x() + v.y() );
                v2.setY( -v.x() + v.y() );

                v1 = 5 * v1 / sqrt( double (v1.x() * v1.x() + v1.y() * v1.y()) );
                v2 = 5 * v2 / sqrt( double (v2.x() * v2.x() + v2.y() * v2.y()) );
                v  = v / 2;
                pen.setWidth( ARROW );
                p.setPen( pen );
                p.drawLine( p2+v, p2+v1+v );
                p.drawLine( p2+v, p2+v2+v );
            }
*/
        }

        e->underpasses.clear();
    }

    p.end();

    bitBlt( this, r.x(), r.y(), &buffer, r.x(), r.y(), r.width(), r.height() );

}
Пример #7
0
Файл: win.cpp Проект: roybai/poe
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static int  cxChar, cxCaps, cyChar, cyClient, iVscrollPos ;
    HDC         hdc ;    
    int         i, y ;    
    PAINTSTRUCT ps ;
//    TCHAR       szBuffer[10] ;    
    TEXTMETRIC  tm ;    
	static int LoadDLLTag=0;
	static int poehackTag=0;
	static BOOL	show_flag=TRUE;

	switch (message)    
    {
	case WM_LBUTTONDOWN:
		if(LoadDLLTag==1)
		{
			show_flag=!show_flag;
	        InvalidateRect (hwnd, NULL, TRUE) ;
			return 0;
		}
		LoadDLLTag=1;
		PoeIntercept(hwnd);
		/*
		typedef void(*pExecute)(DWORD);
		pExecute p;
		p=(pExecute)GetProcAddress(poehackModule,"Execute");
		if(p)
			p((DWORD)hwnd);
		*/
		return 0;
	case WM_RBUTTONDOWN: 
		if(poehackTag==1){
			return 0;
		}
		char dllFullName[10240];
		GetCurrentDirectory(255, dllFullName);
		strcpy(dllFullName, "c:\\bot\\d3\\poehack.dll");
		
		poehackModule = LoadLibrary(dllFullName);
		if(!poehackModule) _showinfo("poehack load failed: %s",dllFullName);
		else
		{
			_showinfo("poehack loaded");
			poehackTag=1;
		}
		if(!_PassValueAddr)
			_PassValueAddr=(pPassValue)GetProcAddress(poehackModule,"PassValue");
		_showinfo("_PassValueAddr %x",_PassValueAddr);		
		return 0;
	case WM_MBUTTONDOWN:		
		if(poehackTag==0) return 0;

		_value.id = DO_UNLOAD;
		if(_PassValueAddr) _PassValueAddr(&_value);

		/*
		typedef void(*pUnload)();
		pUnload p;
		p=(pUnload)GetProcAddress(poehackModule,"Unload");
		if(p) p();
		*/
		FreeLibrary(poehackModule);
		poehackModule=NULL;
		_PassValueAddr=NULL;
		_showinfo("poehack unloaded");
		poehackTag=0;
		return 0;
	case WM_CREATE:
		hdc = GetDC (hwnd) ;
	    GetTextMetrics (hdc, &tm) ;
		cxChar = tm.tmAveCharWidth ;
	    cxCaps = (tm.tmPitchAndFamily & 1 ? 3 : 2) * cxChar / 2 ;
		cyChar = tm.tmHeight + tm.tmExternalLeading ;

	    ReleaseDC (hwnd, hdc) ;
		SetScrollRange (hwnd, SB_VERT, 0, NUMLINES - 1, FALSE) ;
	    SetScrollPos   (hwnd, SB_VERT, iVscrollPos, TRUE) ;
		_window_up=TRUE;
        return 0 ;

    case WM_SIZE:
        cyClient = HIWORD (lParam) ;
        return 0 ;

    case WM_VSCROLL:
        switch (LOWORD (wParam))
          {
			case SB_LINEUP:
          iVscrollPos -= 1 ;
        break ;
     
    case SB_LINEDOWN:
        iVscrollPos += 1 ;
        break ;

    case SB_PAGEUP:
        iVscrollPos -= cyClient / cyChar ;
        break ;
     
    case SB_PAGEDOWN:
        iVscrollPos += cyClient / cyChar ;
        break ;
     
    case SB_THUMBPOSITION:
        iVscrollPos = HIWORD (wParam) ;
        break ;
     
    default :
        break ;
          }

    iVscrollPos = max (0, min (iVscrollPos, NUMLINES - 1)) ;
    if (iVscrollPos != GetScrollPos (hwnd, SB_VERT))
          {
        SetScrollPos (hwnd, SB_VERT, iVscrollPos, TRUE) ;
        InvalidateRect (hwnd, NULL, TRUE) ;
          }
        return 0 ;
    case WM_PAINT:
		if(show_flag)
		{
	        hdc = BeginPaint (hwnd, &ps) ;
		    for (i = 0 ; i < NUMLINES ; i++)
			{
				int len=   strlen (display_buf[i].text) ;
				if(len==0) continue;
		        y = cyChar * (i - iVscrollPos) ;
			    TextOut (hdc, 0, y,
				    display_buf[i].text,
					strlen (display_buf[i].text)) ;
			}
			EndPaint (hwnd, &ps) ;
		}
		else
		{
		typedef void(*pDrawMap)(HWND);
		pDrawMap p;
		p=(pDrawMap)GetProcAddress(poehackModule,"DrawMap");
		if(p) p(hwnd);
		}
        return 0 ;

    case WM_DESTROY:
  		_window_up=FALSE;
		PostQuitMessage (0) ;
        return 0 ;
     }
 
	return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Пример #8
0
bool Bass::executeInstruction(Instruction& i) {
  activeInstruction = &i;
  string s = i.statement;
  evaluateDefines(s);

  if(s.match("macro ?*(*) {") || s.match("global macro ?*(*) {")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    s.trim<1>("macro ", ") {");
    lstring p = s.split<1>("(");
    bool scoped = p(0).beginsWith("scope ");
    p(0).ltrim<1>("scope ");
    lstring a = p(1).empty() ? lstring{} : p(1).qsplit(",").strip();
    setMacro(p(0), a, ip, scoped, local);
    ip = i.ip;
    return true;
  }

  if(s.match("define ?*(*)") || s.match("global define ?*(*)")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    lstring p = s.trim<1>("define ", ")").split<1>("(");
    setDefine(p(0), p(1), local);
    return true;
  }

  if(s.match("evaluate ?*(*)") || s.match("global evaluate ?*(*)")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    lstring p = s.trim<1>("evaluate ", ")").split<1>("(");
    setDefine(p(0), evaluate(p(1)), local);
    return true;
  }

  if(s.match("variable ?*(*)") || s.match("global variable ?*(*)")) {
    bool local = s.beginsWith("global ") == false;
    s.ltrim<1>("global ");
    lstring p = s.trim<1>("variable ", ")").split<1>("(");
    setVariable(p(0), evaluate(p(1)), local);
    return true;
  }

  if(s.match("if ?* {")) {
    s.trim<1>("if ", " {").strip();
    bool match = evaluate(s, Evaluation::Strict);
    ifStack.append(match);
    if(match == false) {
      ip = i.ip;
    }
    return true;
  }

  if(s.match("} else if ?* {")) {
    if(ifStack.last()) {
      ip = i.ip;
    } else {
      s.trim<1>("} else if ", " {").strip();
      bool match = evaluate(s, Evaluation::Strict);
      ifStack.last() = match;
      if(match == false) {
        ip = i.ip;
      }
    }
    return true;
  }

  if(s.match("} else {")) {
    if(ifStack.last()) {
      ip = i.ip;
    } else {
      ifStack.last() = true;
    }
    return true;
  }

  if(s.match("} endif")) {
    ifStack.removeLast();
    return true;
  }

  if(s.match("while ?* {")) {
    s.trim<1>("while ", " {").strip();
    bool match = evaluate(s, Evaluation::Strict);
    if(match == false) ip = i.ip;
    return true;
  }

  if(s.match("} endwhile")) {
    ip = i.ip;
    return true;
  }

  if(s.match("?*(*)")) {
    lstring p = string{s}.rtrim<1>(")").split<1>("(");
    lstring a = p(1).empty() ? lstring{} : p(1).qsplit(",").strip();
    string name = {p(0), ":", a.size()};  //arity overloading
    if(auto macro = findMacro({name})) {
      struct Parameter {
        enum class Type : unsigned { Define, Variable } type;
        string name;
        string value;
      };

      vector<Parameter> parameters;
      for(unsigned n = 0; n < a.size(); n++) {
        lstring p = macro().parameters(n).split<1>(" ").strip();
        if(p.size() == 1) p.prepend("define");

        if(p(0) == "define") parameters.append({Parameter::Type::Define, p(1), a(n)});
        else if(p(0) == "string") parameters.append({Parameter::Type::Define, p(1), text(a(n))});
        else if(p(0) == "evaluate") parameters.append({Parameter::Type::Define, p(1), evaluate(a(n))});
        else if(p(0) == "variable") parameters.append({Parameter::Type::Variable, p(1), evaluate(a(n))});
        else error("unsupported parameter type: ", p(0));
      }

      StackFrame frame;
      stackFrame.append(frame);
      stackFrame.last().ip = ip;
      stackFrame.last().scoped = macro().scoped;

      if(macro().scoped) {
        scope.append(p(0));
      }

      setDefine("#", {"_", macroInvocationCounter++}, true);
      for(auto& parameter : parameters) {
        if(parameter.type == Parameter::Type::Define) setDefine(parameter.name, parameter.value, true);
        if(parameter.type == Parameter::Type::Variable) setVariable(parameter.name, integer(parameter.value), true);
      }

      ip = macro().ip;
      return true;
    }
  }

  if(s.match("} endmacro")) {
    ip = stackFrame.last().ip;
    if(stackFrame.last().scoped) scope.removeLast();
    stackFrame.removeLast();
    return true;
  }

  if(assemble(s)) {
    return true;
  }

  evaluate(s);
  return true;
}
Пример #9
0
void AGXContinuousTrack::createTrackConstraint()
{
    AGXLinkPtr agxFootLinkStart = _feet[0];
    AGXLinkPtr agxFootLinkEnd = _feet[_feet.size() - 1];

    // Connect footLinkStart and footLinkEnd with Hinge
    // Create Hinge with world coordination
    LinkPtr link = agxFootLinkStart->getOrgLink();
    const Vector3& a = link->a();                       // local
    const Vector3 aw = link->attitude() * a;            // world
    const Vector3& p = link->p();                       // world
    AGXHingeDesc hd;
    hd.frameAxis = agx::Vec3(aw(0), aw(1), aw(2));
    hd.frameCenter = agx::Vec3(p(0), p(1), p(2));
    hd.rigidBodyA = agxFootLinkStart->getAGXRigidBody();
    hd.rigidBodyB = agxFootLinkEnd->getAGXRigidBody();
    hd.motor.enable = false;
    hd.lock.enable = false;
    hd.range.enable = false;
    agx::ConstraintRef constraint = AGXObjectFactory::createConstraint(hd);
    link->setJointType(Link::ROTATIONAL_JOINT);
    agxFootLinkStart->setAGXConstraint(constraint);
    getAGXBody()->getAGXScene()->getSimulation()->add(constraint);

    // Create PlaneJoint to prvent the track falling off
    // Create joint with parent(example:chasis) coordination 
    const Vector3& b = link->b();
    const agx::Vec3 a0 = agx::Vec3(a(0), a(1), a(2));   // Rotate axis of track. local
    const agx::Vec3& b0 = agx::Vec3(b(0), b(1), b(2));  // Vector from parent to footLinkStart
    const agx::Vec3& p0 = (a0 * b0) * a0;             // Middle position of track(projection vector of b0 to a0). local
    agx::Vec3 nx = agx::Vec3::Z_AXIS().cross(a0);       // Check a0 is parallel to Z. X-Y consists plane joint.
    agx::OrthoMatrix3x3 rotation;
    if (nx.normalize() > 1.0e-6) {
        nx.normal();
        rotation.setColumn(0, nx);
        agx::Vec3 ny = a0.cross(nx);
        ny.normal();
        rotation.setColumn(1, ny);
        rotation.setColumn(2, a0);
    }
    agx::AffineMatrix4x4 af(rotation, p0);
    AGXPlaneJointDesc pd;
    pd.frameB = AGXObjectFactory::createFrame();
    pd.frameB->setMatrix(af);
    pd.rigidBodyB = agxFootLinkStart->getAGXParentLink()->getAGXRigidBody();

    // Generate collision group name to disable collision between tracks
    std::stringstream trackCollsionGroupName;
    trackCollsionGroupName.str("");
    trackCollsionGroupName << "SelfCollisionContinuousTrack" << agx::UuidGenerator().generate().str() << std::flush;
    getAGXBody()->addCollisionGroupNameToDisableCollision(trackCollsionGroupName.str());

    for (int i = 0; i < (int)_feet.size(); ++i) {
        AGXLinkPtr agxLink = _feet[i];
        // Add plane joint
        pd.frameA = AGXObjectFactory::createFrame();
        pd.rigidBodyA = agxLink->getAGXRigidBody();
        agx::PlaneJointRef pj = AGXObjectFactory::createConstraintPlaneJoint(pd);
        getAGXBody()->getAGXScene()->getSimulation()->add((agx::ConstraintRef)pj);

        // Force enable collision between other links
        agxLink->getAGXGeometry()->removeGroup(getAGXBody()->getCollisionGroupName());
        // Disable collision between tracks
        agxLink->getAGXGeometry()->addGroup(trackCollsionGroupName.str());
    }
}
int main(int argc, char *argv[]) {
	bool error = false;
	uint8_t buffer[256];
	uint16_t bufferSize = 256;
	StreamParser p(streamReader, buffer, bufferSize, handlers, 1, NULL);
	
	while(p.parse() >= 0);
	
	int16_t theInt = 400;
	float theFloat = 213423.23466432;
	uint16_t functionID = 1;
	
	char *stri = (char *)"hello world";
	
	uint8_t indexTable[] = { Object::T_UINT16, Object::T_INT16, Object::T_STRING, Object::T_FLOAT, Object::T_INT32, Object::T_INT64, (uint8_t)(strlen(stri) + 1) };
	Object o(indexTable, 6);
	
	uint8_t dataBuffer[o.getDataSize()];
	o.setDataBuffer(dataBuffer);
	
	o.uint16At(0, functionID); //function id
	o.int16At(1, theInt); //payload argument
	o.strAt(2, stri, strlen(stri) + 1);
	if(!o.floatAt(3, theFloat)) {
		printf("Failed to set float value\n");
	}
	o.int32At(4, 345589619);
	o.int64At(5, 9384760934765065ll);
	
	if(o.int64At(5) != 9384760934765065ll) {
		printf("Retrieved int64 does not equal actual A:%lld, R:%lld\n", (long long int)9384760934765065ll, (long long int)o.int64At(5));
	}
	
	if(o.int32At(4) != 345589619) {
		printf("Retrieved int32 does not equal actual\n");
	}
	
	if(o.floatAt(3) != theFloat) {
		printf("Retrieved float does not equal actual A:%f, R:%f\n", theFloat, o.floatAt(3));
	}
	
	if(o.int16At(1) != theInt) {
		printf("Retrieved int does not equal actual A:%d R:%d\n", theInt, o.int16At(1));
	}
	
	StreamParser::PacketHeader ph = StreamParser::makePacket(16, o.getSize());
	
	printf("generated packet: ");
	printHex(&ph, sizeof(ph));
	o.writeTo(writer, NULL);
	printf("\n");
	
	
	testBuffer = ((uint8_t *)(&ph));
	testBufferSize = sizeof(StreamParser::PacketHeader);
	testBufferIndex = 0;
	
	printf("rpc call: ");
	if(rpc.call(10, "cCds", -10, 10, 320, "hello world") <= 0) {
		printf("error doing rpc call");
	}
	printf("\n");
	
	if(error) {
		printf("FAIELD: Object & RPC buffer tests\n");
	} else {
		printf("PASSED: Object & RPC buffer tests\n");
	}

	printf("Calling socket tests\n");
	socketTest();
	printf("PASSED: Socket Tests\n");

}
Пример #11
0
//! called if an event happened.
bool MainMenu::onEvent(const NEvent& event)
{
	if (isEnabled())
	{
		switch(event.EventType)
		{
		case sEventGui:
			switch(event.GuiEvent.EventType)
			{
			case guiElementFocusLost:
				if (event.GuiEvent.Caller == this && !isMyChild(event.GuiEvent.Element))
				{
					closeAllSubMenus_();
					setHoverIndex_( -1 );
				}
				break;
			case guiElementFocused:
				if (event.GuiEvent.Caller == this )
				{
					bringToFront();
				}
				break;
			default:
				break;
			}
			break;
		case sEventMouse:
			switch(event.MouseEvent.Event)
			{
			case mouseLbtnPressed:
			{
				if (!getEnvironment()->hasFocus(this))
				{
					getEnvironment()->setFocus(this);
				}

    	  bringToFront();

				Point p(event.MouseEvent.getPosition() );
				bool shouldCloseSubMenu = hasOpenSubMenu_();
				if (!getAbsoluteClippingRect().isPointInside(p))
				{
					shouldCloseSubMenu = false;
				}
				isHighlighted_( event.MouseEvent.getPosition(), true);
				if ( shouldCloseSubMenu )
				{
          getEnvironment()->removeFocus(this);
				}

				return true;
			}

			case mouseLbtnRelease:
			{
        Point p(event.MouseEvent.getPosition() );
				if (!getAbsoluteClippingRect().isPointInside(p))
				{
					int t = sendClick_(p);
					if ((t==0 || t==1) && isFocused())
						removeFocus();
				}

			  return true;
			}

      case mouseMoved:
      {
				if (getEnvironment()->hasFocus(this) && getHoveredIndex() >= 0)
				{
				  int oldHighLighted = getHoveredIndex();
					isHighlighted_( event.MouseEvent.getPosition(), true);
					if ( getHoveredIndex() < 0 )
          {
            setHoverIndex_( oldHighLighted );   // keep last hightlight active when moving outside the area
          }
				}
				return true;
      }

      default:
			break;
			}
		break;
		
    default:
		break;
		}
	}

	return Widget::onEvent(event);
}
Пример #12
0
void toPieChart::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    paintChart(&p, QRect(0, 0, width(), height()));
}
Пример #13
0
int main()
{
    GetPsig p("test");
}
Пример #14
0
void Particle::setThreeMomentum(const double px, const double py, const double pz)
{
  ThreeVector p(px, py, pz);
  this->setThreeMomentum(p);
}
Пример #15
0
// fix shadowing problem in OS X
void MainWindow::paintEvent( QPaintEvent *event)
{
    QPainter p( this );
    p.setCompositionMode( QPainter::CompositionMode_Clear );
    p.fillRect( this->rect(), Qt::transparent );
}
Пример #16
0
int main(int argc, char **argv)
{
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
    if(argc<3){
        std::cout<<"This node is intend to use offline"<<std::endl<<"provide a logfile (produced with the dumpernode) and the output calibration file you want"<<std::endl;
        std::cout<<"example:"<<std::endl<<"offlineCalibration <input log filename> <output calibration filename>"<<std::endl;
        return 0;
    }
    float c0,c1,c2,c3=0;
    c0=1.0f;
    if(argc==7){
        c3=atof(argv[3]);
        c2=atof(argv[4]);
        c1=atof(argv[5]);
        c0=atof(argv[6]);
        std::cout<<"polynomial coeffs: d^3*"<<c3<<" + d^2*"<<c2<<" + d*"<<c1<<" + "<<c0<<std::endl;
    }
    std::fstream log;
    log.open(argv[1]);
    string topic;
    int height;
    int width;
    log >> topic;
    log >> height;
    log >> width;
    Matrix3f k;
    log >> k(0,0);
    log >> k(0,1);
    log >> k(0,2);
    log >> k(1,0);
    log >> k(1,1);
    log >> k(1,2);
    log >> k(2,0);
    log >> k(2,1);
    log >> k(2,2);
    string filename;
    //calibrationMatrix c(480,640,8000,4,8);
    int rows =480;
    int cols = 640;
    calibrationMatrix c(rows,cols,8000,4,16);
    //calibrationMatrix c(rows,cols,8000,4,64);
    while(!log.eof()){
        log>>filename;
        std::cout<< "opening "<<filename<<"\r"<<std::flush;
        cv::Mat data = cv::imread(filename,cv::IMREAD_ANYDEPTH);
        pointCloud p(data,k);
        //VOXELIZER
        pcl::PointCloud<pcl::PointXYZ>* pcl;
        pcl=p.pclCloud();
        calibration::voxelize(pcl,pcl,20);
        pointCloud p2(pcl);
        //CENTER SQUARE CLOUD
        pcl::PointCloud<pcl::PointXYZ>* square= new pcl::PointCloud<pcl::PointXYZ>();
        calibration::computeCenterSquareCloud(data,k,square,cols/10,rows/10,c0,c1,c2,c3); //100 100
        pointCloud p3(square);
        //CENTER PLANE
        Eigen::Vector4f centerModel;
        calibration::computerCenterPlane(square,centerModel,40);
        std::cout.flush();
        planeCloud centerPlaneCloud;
        centerPlaneCloud.model=centerModel;
        Eigen::Vector4f center;
        pcl::compute3DCentroid(*square,center);
        //std::cout<<"CENTROID DISTANCE: "<<center[2]<<" ( "<<center.transpose()<<" )"<<std::endl;
        centerPlaneCloud.com=center.head(3);
        //NORMALS
        pcl::PointCloud<pcl::Normal>* normals= new pcl::PointCloud<pcl::Normal>();
        calibration::computeNormals(p2.pclCloud(),normals,100);
        //REJECTION
        Eigen::Vector3f ref;
        std::vector<bool> valid;
        ref<<centerModel[0],centerModel[1],centerModel[2];
        pcl::PointCloud<pcl::PointXYZ> outFromNormalRejection;
        pcl::PointCloud<pcl::PointXYZ>* tmpCloud =p2.pclCloud();
        calibration::pointrejection(&ref,0.7f,tmpCloud,normals,&outFromNormalRejection,&valid);

        //pointCloud outFromNormalRejectionCloud(&outFromNormalRejection);
        //ERROR PER POINT
        pcl::PointCloud<pcl::PointXYZ> error;
        calibration::computeErrorPerPoint(tmpCloud,&error,center.head(3),ref,&valid);
        //std::cout<<"error cloud has "<<error.size()<<" points"<<std::endl;
        //std::cout<<"voxel cloud has "<<p2.pclCloud()->size()<<" points"<<std::endl;
        pcl::PointCloud<pcl::PointXYZ>* cloudToCalibrate=p2.pclCloud();
        //COMPUTE CALIBRATION MATRIX
        std::cout.flush();
        calibration::computeCalibrationMatrix(*cloudToCalibrate,error,k,&valid,c);
        std::cout.flush();
        //CALIBRATE POINT CLOUD
        pcl::PointCloud<pcl::PointXYZ> fixedCloud;
        calibration::calibratePointCloudWithMultipliers(*cloudToCalibrate,fixedCloud,c,k);
        std::cout.flush();

        error.clear();
        valid.clear();
        error.clear();
        cloudToCalibrate->clear();
        delete cloudToCalibrate;
        tmpCloud->clear();
        delete tmpCloud;
        p2.cloud.clear();
        normals->clear();
        outFromNormalRejection.clear();
        valid.clear();
        delete normals;
        delete square;
        pcl->clear();
        delete pcl;
    }
    std::cout<<std::endl<<"saving "<<std::endl;
    c.dumpSensorImages();
    c.serialize(argv[2]);
    char nn[500];
    std::cout<<"saving nn"<<std::endl;
    sprintf(nn,"NN_%s",argv[2]);
    //c.serializeNN(nn);
    //calibrationMatrix* cc = c.downsample(2,2);
    //cc->serialize(argv[2]);

}
Пример #17
0
/// Process queued scripts
void Map::ScriptsProcess()
{
    if (m_scriptSchedule.empty())
        return;

    ///- Process overdue queued scripts
    ScriptScheduleMap::iterator iter = m_scriptSchedule.begin();
    // ok as multimap is a *sorted* associative container
    while (!m_scriptSchedule.empty() && (iter->first <= sWorld->GetGameTime()))
    {
        ScriptAction const& step = iter->second;

        Object* source = NULL;
        if (step.sourceGUID)
        {
            switch (GUID_HIPART(step.sourceGUID))
            {
                case HIGHGUID_ITEM: // as well as HIGHGUID_CONTAINER
                    if (Player* player = HashMapHolder<Player>::Find(step.ownerGUID))
                        source = player->GetItemByGuid(step.sourceGUID);
                    break;
                case HIGHGUID_UNIT:
                case HIGHGUID_VEHICLE:
                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_PET:
                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_PLAYER:
                    source = HashMapHolder<Player>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_GAMEOBJECT:
                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_CORPSE:
                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_MO_TRANSPORT:
                    for (MapManager::TransportSet::iterator iter = sMapMgr->m_Transports.begin(); iter != sMapMgr->m_Transports.end(); ++iter)
                    {
                        if ((*iter)->GetGUID() == step.sourceGUID)
                        {
                            source = *iter;
                            break;
                        }
                    }
                    break;
                default:
                    sLog->outError("%s source with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).",
                        step.script->GetDebugInfo().c_str(), step.sourceGUID, GUID_HIPART(step.sourceGUID));
                    break;
            }
        }

        Object* target = NULL;
        if (step.targetGUID)
        {
            switch (GUID_HIPART(step.targetGUID))
            {
                case HIGHGUID_UNIT:
                case HIGHGUID_VEHICLE:
                    target = HashMapHolder<Creature>::Find(step.targetGUID);
                    break;
                case HIGHGUID_PET:
                    target = HashMapHolder<Pet>::Find(step.targetGUID);
                    break;
                case HIGHGUID_PLAYER:                       // empty GUID case also
                    target = HashMapHolder<Player>::Find(step.targetGUID);
                    break;
                case HIGHGUID_GAMEOBJECT:
                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
                    break;
                case HIGHGUID_CORPSE:
                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
                    break;
                default:
                    sLog->outError("%s target with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).",
                        step.script->GetDebugInfo().c_str(), step.targetGUID, GUID_HIPART(step.targetGUID));
                    break;
            }
        }

        switch (step.script->command)
        {
            case SCRIPT_COMMAND_TALK:
                if (step.script->Talk.ChatType > CHAT_TYPE_WHISPER && step.script->Talk.ChatType != CHAT_MSG_RAID_BOSS_WHISPER)
                {
                    sLog->outError("%s invalid chat type (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->Talk.ChatType);
                    break;
                }
                if (step.script->Talk.Flags & SF_TALK_USE_PLAYER)
                {
                    if (Player* pSource = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                    {
                        LocaleConstant loc_idx = pSource->GetSession()->GetSessionDbLocaleIndex();
                        std::string text(sObjectMgr->GetTrinityString(step.script->Talk.TextID, loc_idx));

                        switch (step.script->Talk.ChatType)
                        {
                            case CHAT_TYPE_SAY:
                                pSource->Say(text, LANG_UNIVERSAL);
                                break;
                            case CHAT_TYPE_YELL:
                                pSource->Yell(text, LANG_UNIVERSAL);
                                break;
                            case CHAT_TYPE_TEXT_EMOTE:
                            case CHAT_TYPE_BOSS_EMOTE:
                                pSource->TextEmote(text);
                                break;
                            case CHAT_TYPE_WHISPER:
                            case CHAT_MSG_RAID_BOSS_WHISPER:
                            {
                                uint64 targetGUID = target ? target->GetGUID() : 0;
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    sLog->outError("%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    pSource->Whisper(text, LANG_UNIVERSAL, targetGUID);
                                break;
                            }
                            default:
                                break;                              // must be already checked at load
                        }
                    }
                }
                else
                {
                    // Source or target must be Creature.
                    if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                    {
                        uint64 targetGUID = target ? target->GetGUID() : 0;
                        switch (step.script->Talk.ChatType)
                        {
                            case CHAT_TYPE_SAY:
                                cSource->Say(step.script->Talk.TextID, LANG_UNIVERSAL, targetGUID);
                                break;
                            case CHAT_TYPE_YELL:
                                cSource->Yell(step.script->Talk.TextID, LANG_UNIVERSAL, targetGUID);
                                break;
                            case CHAT_TYPE_TEXT_EMOTE:
                                cSource->TextEmote(step.script->Talk.TextID, targetGUID);
                                break;
                            case CHAT_TYPE_BOSS_EMOTE:
                                cSource->MonsterTextEmote(step.script->Talk.TextID, targetGUID, true);
                                break;
                            case CHAT_TYPE_WHISPER:
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    sLog->outError("%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    cSource->Whisper(step.script->Talk.TextID, targetGUID);
                                break;
                            case CHAT_MSG_RAID_BOSS_WHISPER:
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    sLog->outError("%s attempt to raidbosswhisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    cSource->MonsterWhisper(step.script->Talk.TextID, targetGUID, true);
                                break;
                            default:
                                break;                              // must be already checked at load
                        }
                    }
                }
                break;

            case SCRIPT_COMMAND_EMOTE:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    if (step.script->Emote.Flags & SF_EMOTE_USE_STATE)
                        cSource->SetUInt32Value(UNIT_NPC_EMOTESTATE, step.script->Emote.EmoteID);
                    else
                        cSource->HandleEmoteCommand(step.script->Emote.EmoteID);
                }
                break;

            case SCRIPT_COMMAND_FIELD_SET:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FieldSet.FieldID <= OBJECT_FIELD_ENTRY || step.script->FieldSet.FieldID >= cSource->GetValuesCount())
                        sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FieldSet.FieldID,
                            cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                        cSource->SetUInt32Value(step.script->FieldSet.FieldID, step.script->FieldSet.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_MOVE_TO:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    cSource->SendMonsterMoveWithSpeed(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ, step.script->MoveTo.TravelTime);
                    cSource->GetMap()->CreatureRelocation(cSource, step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ, 0);
                }
                break;

            case SCRIPT_COMMAND_FLAG_SET:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY || step.script->FlagToggle.FieldID >= cSource->GetValuesCount())
                        sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID,
                            source->GetValuesCount(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                    else
                        cSource->SetFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_FLAG_REMOVE:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY || step.script->FlagToggle.FieldID >= cSource->GetValuesCount())
                        sLog->outError("%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID,
                            source->GetValuesCount(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                    else
                        cSource->RemoveFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_TELEPORT_TO:
                if (step.script->TeleportTo.Flags & SF_TELEPORT_USE_CREATURE)
                {
                    // Source or target must be Creature.
                    if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script, true))
                        cSource->NearTeleportTo(step.script->TeleportTo.DestX, step.script->TeleportTo.DestY, step.script->TeleportTo.DestZ, step.script->TeleportTo.Orientation);
                }
                else
                {
                    // Source or target must be Player.
                    if (Player* pSource = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                        pSource->TeleportTo(step.script->TeleportTo.MapID, step.script->TeleportTo.DestX, step.script->TeleportTo.DestY, step.script->TeleportTo.DestZ, step.script->TeleportTo.Orientation);
                }
                break;

            case SCRIPT_COMMAND_QUEST_EXPLORED:
            {
                if (!source)
                {
                    sLog->outError("%s source object is NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }
                if (!target)
                {
                    sLog->outError("%s target object is NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }

                // when script called for item spell casting then target == (unit or GO) and source is player
                WorldObject* worldObject;
                Player* plrTarget = target->ToPlayer();
                if (plrTarget)
                {
                    if (source->GetTypeId() != TYPEID_UNIT && source->GetTypeId() != TYPEID_GAMEOBJECT && source->GetTypeId() != TYPEID_PLAYER)
                    {
                        sLog->outError("%s source is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                        break;
                    }
                    worldObject = dynamic_cast<WorldObject*>(source);
                }
                else
                {
                    plrTarget = source->ToPlayer();
                    if (plrTarget)
                    {
                        if (target->GetTypeId() != TYPEID_UNIT && target->GetTypeId() != TYPEID_GAMEOBJECT && target->GetTypeId() != TYPEID_PLAYER)
                        {
                            sLog->outError("%s target is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                                step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                            break;
                        }
                        worldObject =  dynamic_cast<WorldObject*>(target);
                    }
                    else
                    {
                        sLog->outError("%s neither source nor target is player (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow(),
                            target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                        break;
                    }
                }

                // quest id and flags checked at script loading
                if ((worldObject->GetTypeId() != TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
                    (step.script->QuestExplored.Distance == 0 || worldObject->IsWithinDistInMap(plrTarget, float(step.script->QuestExplored.Distance))))
                    plrTarget->AreaExploredOrEventHappens(step.script->QuestExplored.QuestID);
                else
                    plrTarget->FailQuest(step.script->QuestExplored.QuestID);

                break;
            }

            case SCRIPT_COMMAND_KILL_CREDIT:
                // Source or target must be Player.
                if (Player* pSource = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                {
                    if (step.script->KillCredit.Flags & SF_KILLCREDIT_REWARD_GROUP)
                        pSource->RewardPlayerAndGroupAtEvent(step.script->KillCredit.CreatureEntry, pSource);
                    else
                        pSource->KilledMonsterCredit(step.script->KillCredit.CreatureEntry, 0);
                }
                break;

            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
                if (!step.script->RespawnGameobject.GOGuid)
                {
                    sLog->outError("%s gameobject guid (datalong) is not specified.", step.script->GetDebugInfo().c_str());
                    break;
                }

                // Source or target must be WorldObject.
                if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script))
                {
                    GameObject* pGO = _FindGameObject(pSummoner, step.script->RespawnGameobject.GOGuid);
                    if (!pGO)
                    {
                        sLog->outError("%s gameobject was not found (guid: %u).", step.script->GetDebugInfo().c_str(), step.script->RespawnGameobject.GOGuid);
                        break;
                    }

                    if (pGO->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_DOOR        ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_BUTTON      ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_TRAP)
                    {
                        sLog->outError("%s can not be used with gameobject of type %u (guid: %u).",
                            step.script->GetDebugInfo().c_str(), uint32(pGO->GetGoType()), step.script->RespawnGameobject.GOGuid);
                        break;
                    }

                    // Check that GO is not spawned
                    if (!pGO->isSpawned())
                    {
                        int32 nTimeToDespawn = std::max(5, int32(step.script->RespawnGameobject.DespawnDelay));
                        pGO->SetLootState(GO_READY);
                        pGO->SetRespawnTime(nTimeToDespawn);

                        pGO->GetMap()->AddToMap(pGO);
                    }
                }
                break;

            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
            {
                // Source must be WorldObject.
                if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script))
                {
                    if (!step.script->TempSummonCreature.CreatureEntry)
                        sLog->outError("%s creature entry (datalong) is not specified.", step.script->GetDebugInfo().c_str());
                    else
                    {
                        float x = step.script->TempSummonCreature.PosX;
                        float y = step.script->TempSummonCreature.PosY;
                        float z = step.script->TempSummonCreature.PosZ;
                        float o = step.script->TempSummonCreature.Orientation;

                        if (!pSummoner->SummonCreature(step.script->TempSummonCreature.CreatureEntry, x, y, z, o, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, step.script->TempSummonCreature.DespawnDelay))
                            sLog->outError("%s creature was not spawned (entry: %u).", step.script->GetDebugInfo().c_str(), step.script->TempSummonCreature.CreatureEntry);
                    }
                }
                break;
            }

            case SCRIPT_COMMAND_OPEN_DOOR:
            case SCRIPT_COMMAND_CLOSE_DOOR:
                _ScriptProcessDoor(source, target, step.script);
                break;

            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
                // Source must be Unit.
                if (Unit* pSource = _GetScriptUnit(source, true, step.script))
                {
                    // Target must be GameObject.
                    if (!target)
                    {
                        sLog->outError("%s target object is NULL.", step.script->GetDebugInfo().c_str());
                        break;
                    }

                    if (target->GetTypeId() != TYPEID_GAMEOBJECT)
                    {
                        sLog->outError("%s target object is not gameobject (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                        break;
                    }

                    if (GameObject* pGO = target->ToGameObject())
                        pGO->Use(pSource);
                }
                break;

            case SCRIPT_COMMAND_REMOVE_AURA:
            {
                // Source (datalong2 != 0) or target (datalong2 == 0) must be Unit.
                bool bReverse = step.script->RemoveAura.Flags & SF_REMOVEAURA_REVERSE;
                if (Unit* pTarget = _GetScriptUnit(bReverse ? source : target, bReverse, step.script))
                    pTarget->RemoveAurasDueToSpell(step.script->RemoveAura.SpellID);
                break;
            }

            case SCRIPT_COMMAND_CAST_SPELL:
            {
                // TODO: Allow gameobjects to be targets and casters
                if (!source && !target)
                {
                    sLog->outError("%s source and target objects are NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }

                Unit* uSource = NULL;
                Unit* uTarget = NULL;
                // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s
                switch (step.script->CastSpell.Flags)
                {
                    case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = target ? target->ToUnit() : NULL;
                        break;
                    case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = uSource;
                        break;
                    case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target
                        uSource = target ? target->ToUnit() : NULL;
                        uTarget = uSource;
                        break;
                    case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source
                        uSource = target ? target->ToUnit() : NULL;
                        uTarget = source ? source->ToUnit() : NULL;
                        break;
                    case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : NULL;
                        break;
                }

                if (!uSource || !uSource->isType(TYPEMASK_UNIT))
                {
                    sLog->outError("%s no source unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID);
                    break;
                }

                if (!uTarget || !uTarget->isType(TYPEMASK_UNIT))
                {
                    sLog->outError("%s no target unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID);
                    break;
                }

                bool triggered = (step.script->CastSpell.Flags != 4) ?
                    step.script->CastSpell.CreatureEntry & SF_CASTSPELL_TRIGGERED :
                    step.script->CastSpell.CreatureEntry < 0;
                uSource->CastSpell(uTarget, step.script->CastSpell.SpellID, triggered);
                break;
            }

            case SCRIPT_COMMAND_PLAY_SOUND:
                // Source must be WorldObject.
                if (WorldObject* pSource = _GetScriptWorldObject(source, true, step.script))
                {
                    // PlaySound.Flags bitmask: 0/1=anyone/target
                    Player* pTarget = NULL;
                    if (step.script->PlaySound.Flags & SF_PLAYSOUND_TARGET_PLAYER)
                    {
                        // Target must be Player.
                        pTarget = _GetScriptPlayer(target, false, step.script);
                        if (!pTarget)
                            break;
                    }

                    // PlaySound.Flags bitmask: 0/2=without/with distance dependent
                    if (step.script->PlaySound.Flags & SF_PLAYSOUND_DISTANCE_SOUND)
                        pSource->PlayDistanceSound(step.script->PlaySound.SoundID, pTarget);
                    else
                        pSource->PlayDirectSound(step.script->PlaySound.SoundID, pTarget);
                }
                break;

            case SCRIPT_COMMAND_CREATE_ITEM:
                // Target or source must be Player.
                if (Player* pReceiver = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                {
                    ItemPosCountVec dest;
                    InventoryResult msg = pReceiver->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, step.script->CreateItem.ItemEntry, step.script->CreateItem.Amount);
                    if (msg == EQUIP_ERR_OK)
                    {
                        if (Item* item = pReceiver->StoreNewItem(dest, step.script->CreateItem.ItemEntry, true))
                            pReceiver->SendNewItem(item, step.script->CreateItem.Amount, false, true);
                    }
                    else
                        pReceiver->SendEquipError(msg, NULL, NULL, step.script->CreateItem.ItemEntry);
                }
                break;

            case SCRIPT_COMMAND_DESPAWN_SELF:
                // Target or source must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script, true))
                    cSource->DespawnOrUnsummon(step.script->DespawnSelf.DespawnDelay);
                break;

            case SCRIPT_COMMAND_LOAD_PATH:
                // Source must be Unit.
                if (Unit* pSource = _GetScriptUnit(source, true, step.script))
                {
                    if (!sWaypointMgr->GetPath(step.script->LoadPath.PathID))
                        sLog->outError("%s source object has an invalid path (%u), skipping.", step.script->GetDebugInfo().c_str(), step.script->LoadPath.PathID);
                    else
                        pSource->GetMotionMaster()->MovePath(step.script->LoadPath.PathID, step.script->LoadPath.IsRepeatable);
                }
                break;

            case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT:
            {
                if (!step.script->CallScript.CreatureEntry)
                {
                    sLog->outError("%s creature entry is not specified, skipping.", step.script->GetDebugInfo().c_str());
                    break;
                }
                if (!step.script->CallScript.ScriptID)
                {
                    sLog->outError("%s script id is not specified, skipping.", step.script->GetDebugInfo().c_str());
                    break;
                }

                Creature* cTarget = NULL;
                if (source) //using grid searcher
                {
                    WorldObject* wSource = dynamic_cast <WorldObject*> (source);

                    CellCoord p(Trinity::ComputeCellCoord(wSource->GetPositionX(), wSource->GetPositionY()));
                    Cell cell(p);

                    Trinity::CreatureWithDbGUIDCheck target_check(wSource, step.script->CallScript.CreatureEntry);
                    Trinity::CreatureSearcher<Trinity::CreatureWithDbGUIDCheck> checker(wSource, cTarget, target_check);

                    TypeContainerVisitor<Trinity::CreatureSearcher <Trinity::CreatureWithDbGUIDCheck>, GridTypeMapContainer > unit_checker(checker);
                    cell.Visit(p, unit_checker, *wSource->GetMap(), *wSource, wSource->GetGridActivationRange());
                }
                else //check hashmap holders
                {
                    if (CreatureData const* data = sObjectMgr->GetCreatureData(step.script->CallScript.CreatureEntry))
                        cTarget = ObjectAccessor::GetObjectInWorld<Creature>(data->mapid, data->posX, data->posY, MAKE_NEW_GUID(step.script->CallScript.CreatureEntry, data->id, HIGHGUID_UNIT), cTarget);
                }

                if (!cTarget)
                {
                    sLog->outError("%s target was not found (entry: %u)", step.script->GetDebugInfo().c_str(), step.script->CallScript.CreatureEntry);
                    break;
                }

                //Lets choose our ScriptMap map
                ScriptMapMap* datamap = GetScriptsMapByType(ScriptsType(step.script->CallScript.ScriptType));
                //if no scriptmap present...
                if (!datamap)
                {
                    sLog->outError("%s unknown scriptmap (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->CallScript.ScriptType);
                    break;
                }

                // Insert script into schedule but do not start it
                ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, NULL);
                break;
            }

            case SCRIPT_COMMAND_KILL:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    if (cSource->isDead())
                        sLog->outError("%s creature is already dead (Entry: %u, GUID: %u)",
                            step.script->GetDebugInfo().c_str(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                    {
                        cSource->setDeathState(JUST_DIED);
                        if (step.script->Kill.RemoveCorpse == 1)
                            cSource->RemoveCorpse();
                    }
                }
                break;

            case SCRIPT_COMMAND_ORIENTATION:
                // Source must be Unit.
                if (Unit* pSource = _GetScriptUnit(source, true, step.script))
                {
                    if (step.script->Orientation.Flags& SF_ORIENTATION_FACE_TARGET)
                    {
                        // Target must be Unit.
                        Unit* pTarget = _GetScriptUnit(target, false, step.script);
                        if (!pTarget)
                            break;

                        pSource->SetInFront(pTarget);
                    }
                    else
                        pSource->SetOrientation(step.script->Orientation.Orientation);

                    pSource->SendMovementFlagUpdate();
                }
                break;

            case SCRIPT_COMMAND_EQUIP:
                // Source must be Creature.
                if (Creature* cSource = _GetScriptCreature(source, true, step.script))
                    cSource->LoadEquipment(step.script->Equip.EquipmentID);
                break;

            case SCRIPT_COMMAND_MODEL:
                // Source must be Creature.
                if (Creature* cSource = _GetScriptCreature(source, true, step.script))
                    cSource->SetDisplayId(step.script->Model.ModelID);
                break;

            case SCRIPT_COMMAND_CLOSE_GOSSIP:
                // Source must be Player.
                if (Player* pSource = _GetScriptPlayer(source, true, step.script))
                    pSource->PlayerTalkClass->SendCloseGossip();
                break;

            case SCRIPT_COMMAND_PLAYMOVIE:
                // Source must be Player.
                if (Player* pSource = _GetScriptPlayer(source, true, step.script))
                    pSource->SendMovieStart(step.script->PlayMovie.MovieID);
                break;

            default:
                sLog->outError("Unknown script command %s.", step.script->GetDebugInfo().c_str());
                break;
        }

        m_scriptSchedule.erase(iter);
        iter = m_scriptSchedule.begin();
        sScriptMgr->DecreaseScheduledScriptCount();
    }
}
Пример #18
0
// Draw
void
TestView::Draw(BRect updateRect)
{
	if (fCopyBitsJustCalled) {
		printf("TestView::Draw(%.1f, %.1f, %.1f, %.1f) after CopyBits()\n",
			   updateRect.left, updateRect.top, updateRect.right, updateRect.bottom);
		fCopyBitsJustCalled = false;
	}

	// background
//	SetHighColor(ui_color(B_PANEL_BACKGROUND_COLOR));
//	FillRect(updateRect);

	BRect r(Bounds());

	// draw some pattern with lines
	float width = r.Width();
	float height = r.Height();
	int32 lineCount = 20;
	SetPenSize(2.0);
	for (int32 i = 0; i < lineCount; i++) {
		SetHighColor(255, (255 / lineCount) * i, 255 - (255 / lineCount) * i);
		StrokeLine(BPoint(r.left + (width / lineCount) * i, r.top),
				   BPoint(r.left, r.top + (height / lineCount) * i));
		StrokeLine(BPoint(r.right - (width / lineCount) * i, r.bottom),
				   BPoint(r.right, r.bottom - (height / lineCount) * i));
	}
	StrokeLine(BPoint(r.left, r.bottom), BPoint(r.right, r.top));

	// source and dest rect
	SetPenSize(1.0);

	SetHighColor(0, 255, 0, 255);
	StrokeRect(fSourceRect);

	SetHighColor(0, 0, 255, 255);
	StrokeRect(fDestRect);

	// text
	SetHighColor(128, 0, 50, 255);

	const char* message = "Left-Click and drag";
	width = StringWidth(message);
	BPoint p(r.left + r.Width() / 2.0 - width / 2.0,
			 r.top + r.Height() / 2.0 - 50.0);

	DrawString(message, p);

	message = "to set source rect!";
	width = StringWidth(message);
	p.x = r.left + r.Width() / 2.0 - width / 2.0;
	p.y += 20;

	DrawString(message, p);

	message = "Right-Click and drag";
	width = StringWidth(message);
	p.x = r.left + r.Width() / 2.0 - width / 2.0;
	p.y += 30.0;

	DrawString(message, p);

	message = "to set destination rect!";
	width = StringWidth(message);
	p.x = r.left + r.Width() / 2.0 - width / 2.0;
	p.y += 20;

	DrawString(message, p);
}
Пример #19
0
Position Game::getFreePosition(){
    Position p(0, 0);
    while (! this->map->isFree(p)) p = Position(qrand()%this->map->getSize(), qrand()%this->map->getSize());
    return p;
}
Пример #20
0
void PairsTab::addPair() {
    FEMPair* p(TruncationWizard::exec(this));
    delete p;
}
Пример #21
0
HGLOBAL WINAPI DLLExport UpdateEditStructure(mv __far *mV, OLDEDITDATA * AnyEdPtr)
{
		//Version 1 -> 3
		if (AnyEdPtr->eHeader.extVersion < 2)
		{
			LPEDATA NewEdPtr=0;
			OLDEDITDATA* OldEdPtr = AnyEdPtr;
			NewEdPtr = (EDITDATA*)GlobalAlloc(GPTR,sizeof(EDITDATA));
			memcpy(&NewEdPtr->eHeader, &OldEdPtr->eHeader, sizeof(extHeader));
			NewEdPtr->eHeader.extSize = sizeof(EDITDATA);    // Update the EDITDATA structure size
			NewEdPtr->eHeader.extVersion = 3;
			p(nWidth); p(nHeight);
			p(textColor); p(backColor);
			p(dwAlignFlags); p(dwFlags);
			memcpy(&NewEdPtr->textFont, &OldEdPtr->textFont, sizeof(LOGFONT));
			memcpy(&NewEdPtr->opts, &OldEdPtr->opts, sizeof(bool)*4);
			NewEdPtr->iconH = 16;
			NewEdPtr->iconW = 16;
			NewEdPtr->maxIcon = 256;
			NewEdPtr->buttonStyle = 0;
			NewEdPtr->tabDir = 0;
			NewEdPtr->lineMode = 0;
			NewEdPtr->tabMode = 0;
			NewEdPtr->sText[0] = 0;

			for (int i=0;i<16;i++)
				NewEdPtr->wImages[i] = 0;
			NewEdPtr->nImages = 0;

			return (HGLOBAL)NewEdPtr;
		}
		//Version 2 -> 3
		else if (AnyEdPtr->eHeader.extVersion == 2)
		{
			LPEDATA NewEdPtr=0;
			OLDEDITDATA2* OldEdPtr = (OLDEDITDATA2*)AnyEdPtr;
			NewEdPtr = (EDITDATA*)GlobalAlloc(GPTR,sizeof(EDITDATA));
			memcpy(&NewEdPtr->eHeader, &OldEdPtr->eHeader, sizeof(extHeader));
			NewEdPtr->eHeader.extSize = sizeof(EDITDATA);    // Update the EDITDATA structure size
			NewEdPtr->eHeader.extVersion = 3;
			p(nWidth); p(nHeight);
			p(textColor); p(backColor);
			p(dwAlignFlags); p(dwFlags);
			memcpy(&NewEdPtr->textFont, &OldEdPtr->textFont, sizeof(LOGFONT));
			memcpy(&NewEdPtr->opts, &OldEdPtr->opts, sizeof(bool)*4);
			p(iconH); p(iconW);
			p(maxIcon);
			p(buttonStyle);
			p(tabDir);
			p(lineMode);
			p(tabMode);
			NewEdPtr->sText[0] = 0;

			for (int i=0;i<16;i++)
				NewEdPtr->wImages[i] = 0;
			NewEdPtr->nImages = 0;

			return (HGLOBAL)NewEdPtr;
		}
#if defined(UNICODE) && !defined(RUN_ONLY) //If data is in ASCII format
		//Version 3 -> 4 (ASCII -> Unicode)
		else if (AnyEdPtr->eHeader.extVersion == 3)
		{
			//Initialise EDITDATAs
			EDITDATAA* OldEdPtr = (EDITDATAA*)AnyEdPtr;
			EDITDATAW* NewEdPtr = (EDITDATAW*)GlobalAlloc(GPTR,sizeof(EDITDATAW));
			
			// Copy eHeader
			memcpy(&NewEdPtr->eHeader, &OldEdPtr->eHeader, sizeof(extHeader));
			NewEdPtr->eHeader.extSize = sizeof(EDITDATAW);    // Update the EDITDATA structure size
			NewEdPtr->eHeader.extVersion = 4;

			// Copy until the LogFont structure
			p(nWidth); p(nHeight);
			p(textColor); p(backColor);
			p(dwAlignFlags); p(dwFlags);

			// Copy all similarities between LOGFONTA and LOGFONTW
			p(textFont.lfHeight); p(textFont.lfWidth);
			p(textFont.lfEscapement); p(textFont.lfOrientation);
			p(textFont.lfWeight); p(textFont.lfItalic);
			p(textFont.lfUnderline); p(textFont.lfStrikeOut);
			p(textFont.lfCharSet); p(textFont.lfOutPrecision);
			p(textFont.lfClipPrecision); p(textFont.lfQuality);
			p(textFont.lfPitchAndFamily);
			
			// LOGFONTA has char [] so
			MultiByteToWideChar(mvGetAppCodePage(mV, mV->mvEditApp), 0, OldEdPtr->textFont.lfFaceName, LF_FACESIZE, NewEdPtr->textFont.lfFaceName, LF_FACESIZE);
					
			//Continue with other properties
			memcpy(&NewEdPtr->opts, &OldEdPtr->opts, sizeof(bool)*4);
			p(iconH); p(iconW);
			p(maxIcon);
			p(buttonStyle);
			p(tabDir);
			p(lineMode);
			p(tabMode);
			for (int i=0;i<16;i++)
				p(wImages[i]);
			p(nImages);
			
			// Copy final char [], sText
			MultiByteToWideChar(mvGetAppCodePage(mV, mV->mvEditApp), 0, OldEdPtr->sText, sizeof(OldEdPtr->sText), NewEdPtr->sText, sizeof(NewEdPtr->sText));
			
			// Done
			return (HGLOBAL)NewEdPtr;
		}
#elif !defined(UNICODE) && !defined(RUN_ONLY) //If old data is Unicode, but running ASCII MMF2...
		//Version 4 -> 3 (Unicode -> ASCII)
		else if (AnyEdPtr->eHeader.extVersion == 4)
		{
			//None of that long copying thing. Let's do memory copying.
			//First declare the two pointers.
			EDITDATAW* OldEdPtr = (EDITDATAW*)AnyEdPtr;
			EDITDATAA* NewEdPtr = (EDITDATAA*)GlobalAlloc(GPTR,sizeof(EDITDATAA));
			
			// Copy eHeader
			memcpy(&NewEdPtr->eHeader, &OldEdPtr->eHeader, sizeof(extHeader));
			NewEdPtr->eHeader.extSize = sizeof(EDITDATAA);    // Update the EDITDATA structure size
			NewEdPtr->eHeader.extVersion = 3;

			// Copy until the LogFont structure
			p(nWidth); p(nHeight);
			p(textColor); p(backColor);
			p(dwAlignFlags); p(dwFlags);

			// Copy all similarities between LOGFONTA and LOGFONTW
			p(textFont.lfHeight); p(textFont.lfWidth);
			p(textFont.lfEscapement); p(textFont.lfOrientation);
			p(textFont.lfWeight); p(textFont.lfItalic);
			p(textFont.lfUnderline); p(textFont.lfStrikeOut);
			p(textFont.lfCharSet); p(textFont.lfOutPrecision);
			p(textFont.lfClipPrecision); p(textFont.lfQuality);
			p(textFont.lfPitchAndFamily);
			
			// LOGFONTA has char [] so
			WideCharToMultiByte(mvGetAppCodePage(mV, mV->mvEditApp), 0, OldEdPtr->textFont.lfFaceName, LF_FACESIZE, NewEdPtr->textFont.lfFaceName, LF_FACESIZE,NULL,NULL);
					
			//Continue with other properties
			memcpy(&NewEdPtr->opts, &OldEdPtr->opts, sizeof(bool)*4);
			p(iconH); p(iconW);
			p(maxIcon);
			p(buttonStyle);
			p(tabDir);
			p(lineMode);
			p(tabMode);
			for (int i=0;i<16;i++)
				p(wImages[i]);
			p(nImages);
			
			// Copy final char [], sText
			WideCharToMultiByte(mvGetAppCodePage(mV, mV->mvEditApp), 0, OldEdPtr->textFont.lfFaceName, LF_FACESIZE, NewEdPtr->textFont.lfFaceName, LF_FACESIZE,NULL,NULL);
			
			return (HGLOBAL)NewEdPtr;
		}
#endif
	return NULL;
}
Пример #22
0
void TransactionView::paintEvent(QPaintEvent* evt) {
  QStyleOption opt;
  opt.init(this);
  QPainter p(this);
  style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
Пример #23
0
void PoolMgr::LoadFromDB()
{
    // Pool templates
    {
        uint32 oldMSTime = getMSTime();

        QueryResult result = WorldDatabase.Query("SELECT entry, max_limit FROM pool_template");
        if (!result)
        {
            mPoolTemplate.clear();
            TC_LOG_INFO("server.loading", ">> Loaded 0 object pools. DB table `pool_template` is empty.");
            return;
        }

        uint32 count = 0;
        do
        {
            Field* fields = result->Fetch();

            uint32 pool_id = fields[0].GetUInt32();

            PoolTemplateData& pPoolTemplate = mPoolTemplate[pool_id];
            pPoolTemplate.MaxLimit  = fields[1].GetUInt32();

            ++count;
        }
        while (result->NextRow());

        TC_LOG_INFO("server.loading", ">> Loaded %u objects pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
    }

    // Creatures

    TC_LOG_INFO("server.loading", "Loading Creatures Pooling Data...");
    {
        uint32 oldMSTime = getMSTime();

        //                                                 1       2         3
        QueryResult result = WorldDatabase.Query("SELECT guid, pool_entry, chance FROM pool_creature");

        if (!result)
        {
            TC_LOG_INFO("server.loading", ">> Loaded 0 creatures in  pools. DB table `pool_creature` is empty.");
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();

                uint64 guid = fields[0].GetUInt64();
                uint32 pool_id = fields[1].GetUInt32();
                float chance   = fields[2].GetFloat();

                CreatureData const* data = sObjectMgr->GetCreatureData(guid);
                if (!data)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_creature` has a non existing creature spawn (GUID: " UI64FMTD ") defined for pool id (%u), skipped.", guid, pool_id);
                    continue;
                }
                if (pool_id > max_pool_id)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_creature` pool id (%u) is out of range compared to max pool id in `pool_template`, skipped.", pool_id);
                    continue;
                }
                if (chance < 0 || chance > 100)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_creature` has an invalid chance (%f) for creature guid (" UI64FMTD ") in pool id (%u), skipped.", chance, guid, pool_id);
                    continue;
                }
                PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id];
                PoolObject plObject = PoolObject(guid, chance);
                PoolGroup<Creature>& cregroup = mPoolCreatureGroups[pool_id];
                cregroup.SetPoolId(pool_id);
                cregroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
                SearchPair p(guid, pool_id);
                mCreatureSearchMap.insert(p);

                ++count;
            }
            while (result->NextRow());

            TC_LOG_INFO("server.loading", ">> Loaded %u creatures in pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
        }
    }

    // Gameobjects

    TC_LOG_INFO("server.loading", "Loading Gameobject Pooling Data...");
    {
        uint32 oldMSTime = getMSTime();

        //                                                 1        2         3
        QueryResult result = WorldDatabase.Query("SELECT guid, pool_entry, chance FROM pool_gameobject");

        if (!result)
        {
            TC_LOG_INFO("server.loading", ">> Loaded 0 gameobjects in  pools. DB table `pool_gameobject` is empty.");
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();

                uint64 guid = fields[0].GetUInt64();
                uint32 pool_id = fields[1].GetUInt32();
                float chance   = fields[2].GetFloat();

                GameObjectData const* data = sObjectMgr->GetGOData(guid);
                if (!data)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_gameobject` has a non existing gameobject spawn (GUID: " UI64FMTD ") defined for pool id (%u), skipped.", guid, pool_id);
                    continue;
                }

                GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(data->id);
                if (goinfo->type != GAMEOBJECT_TYPE_CHEST &&
                    goinfo->type != GAMEOBJECT_TYPE_FISHINGHOLE &&
                    goinfo->type != GAMEOBJECT_TYPE_GATHERING_NODE &&
                    goinfo->type != GAMEOBJECT_TYPE_GOOBER)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_gameobject` has a not lootable gameobject spawn (GUID: " UI64FMTD ", type: %u) defined for pool id (%u), skipped.", guid, goinfo->type, pool_id);
                    continue;
                }

                if (pool_id > max_pool_id)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_gameobject` pool id (%u) is out of range compared to max pool id in `pool_template`, skipped.", pool_id);
                    continue;
                }

                if (chance < 0 || chance > 100)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_gameobject` has an invalid chance (%f) for gameobject guid (" UI64FMTD ") in pool id (%u), skipped.", chance, guid, pool_id);
                    continue;
                }

                PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id];
                PoolObject plObject = PoolObject(guid, chance);
                PoolGroup<GameObject>& gogroup = mPoolGameobjectGroups[pool_id];
                gogroup.SetPoolId(pool_id);
                gogroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
                SearchPair p(guid, pool_id);
                mGameobjectSearchMap.insert(p);

                ++count;
            }
            while (result->NextRow());

            TC_LOG_INFO("server.loading", ">> Loaded %u gameobject in pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
        }
    }

    // Pool of pools

    TC_LOG_INFO("server.loading", "Loading Mother Pooling Data...");
    {
        uint32 oldMSTime = getMSTime();

        //                                                  1        2            3
        QueryResult result = WorldDatabase.Query("SELECT pool_id, mother_pool, chance FROM pool_pool");

        if (!result)
        {
            TC_LOG_INFO("server.loading", ">> Loaded 0 pools in pools");
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();

                uint32 child_pool_id  = fields[0].GetUInt32();
                uint32 mother_pool_id = fields[1].GetUInt32();
                float chance          = fields[2].GetFloat();

                if (mother_pool_id > max_pool_id)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_pool` mother_pool id (%u) is out of range compared to max pool id in `pool_template`, skipped.", mother_pool_id);
                    continue;
                }
                if (child_pool_id > max_pool_id)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_pool` included pool_id (%u) is out of range compared to max pool id in `pool_template`, skipped.", child_pool_id);
                    continue;
                }
                if (mother_pool_id == child_pool_id)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_pool` pool_id (%u) includes itself, dead-lock detected, skipped.", child_pool_id);
                    continue;
                }
                if (chance < 0 || chance > 100)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_pool` has an invalid chance (%f) for pool id (%u) in mother pool id (%u), skipped.", chance, child_pool_id, mother_pool_id);
                    continue;
                }
                PoolTemplateData* pPoolTemplateMother = &mPoolTemplate[mother_pool_id];
                PoolObject plObject = PoolObject(child_pool_id, chance);
                PoolGroup<Pool>& plgroup = mPoolPoolGroups[mother_pool_id];
                plgroup.SetPoolId(mother_pool_id);
                plgroup.AddEntry(plObject, pPoolTemplateMother->MaxLimit);
                SearchPair p(child_pool_id, mother_pool_id);
                mPoolSearchMap.insert(p);

                ++count;
            }
            while (result->NextRow());

            // Now check for circular reference
            for (uint32 i=0; i < max_pool_id; ++i)
            {
                std::set<uint32> checkedPools;
                for (SearchMap::iterator poolItr = mPoolSearchMap.find(i); poolItr != mPoolSearchMap.end(); poolItr = mPoolSearchMap.find(poolItr->second))
                {
                    checkedPools.insert(poolItr->first);
                    if (checkedPools.find(poolItr->second) != checkedPools.end())
                    {
                        std::ostringstream ss;
                        ss<< "The pool(s) ";
                        for (std::set<uint32>::const_iterator itr=checkedPools.begin(); itr != checkedPools.end(); ++itr)
                            ss << *itr << ' ';
                        ss << "create(s) a circular reference, which can cause the server to freeze.\nRemoving the last link between mother pool "
                            << poolItr->first << " and child pool " << poolItr->second;
                        TC_LOG_ERROR("sql.sql", "%s", ss.str().c_str());
                        mPoolPoolGroups[poolItr->second].RemoveOneRelation(poolItr->first);
                        mPoolSearchMap.erase(poolItr);
                        --count;
                        break;
                    }
                }
            }

            TC_LOG_INFO("server.loading", ">> Loaded %u pools in mother pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
        }
    }

    TC_LOG_INFO("server.loading", "Loading Quest Pooling Data...");
    {
        uint32 oldMSTime = getMSTime();

        PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_QUEST_POOLS);
        PreparedQueryResult result = WorldDatabase.Query(stmt);

        if (!result)
        {
            TC_LOG_INFO("server.loading", ">> Loaded 0 quests in pools");
        }
        else
        {
            PooledQuestRelationBounds creBounds;
            PooledQuestRelationBounds goBounds;

            enum eQuestTypes
            {
                QUEST_NONE   = 0,
                QUEST_DAILY  = 1,
                QUEST_WEEKLY = 2
            };

            std::map<uint32, int32> poolTypeMap;
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();

                uint32 entry   = fields[0].GetUInt32();
                uint32 pool_id = fields[1].GetUInt32();

                Quest const* quest = sObjectMgr->GetQuestTemplate(entry);
                if (!quest)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_quest` has a non existing quest template (Entry: %u) defined for pool id (%u), skipped.", entry, pool_id);
                    continue;
                }

                if (pool_id > max_pool_id)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_quest` pool id (%u) is out of range compared to max pool id in `pool_template`, skipped.", pool_id);
                    continue;
                }

                if (!quest->IsDailyOrWeekly())
                {
                    TC_LOG_ERROR("sql.sql", "`pool_quest` has an quest (%u) which is not daily or weekly in pool id (%u), use ExclusiveGroup instead, skipped.", entry, pool_id);
                    continue;
                }

                if (poolTypeMap[pool_id] == QUEST_NONE)
                    poolTypeMap[pool_id] = quest->IsDaily() ? QUEST_DAILY : QUEST_WEEKLY;

                int32 currType = quest->IsDaily() ? QUEST_DAILY : QUEST_WEEKLY;

                if (poolTypeMap[pool_id] != currType)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_quest` quest %u is %s but pool (%u) is specified for %s, mixing not allowed, skipped.",
                                     entry, currType == QUEST_DAILY ? "QUEST_DAILY" : "QUEST_WEEKLY", pool_id, poolTypeMap[pool_id] == QUEST_DAILY ? "QUEST_DAILY" : "QUEST_WEEKLY");
                    continue;
                }

                creBounds = mQuestCreatureRelation.equal_range(entry);
                goBounds = mQuestGORelation.equal_range(entry);

                if (creBounds.first == creBounds.second && goBounds.first == goBounds.second)
                {
                    TC_LOG_ERROR("sql.sql", "`pool_quest` lists entry (%u) as member of pool (%u) but is not started anywhere, skipped.", entry, pool_id);
                    continue;
                }

                PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id];
                PoolObject plObject = PoolObject(entry, 0.0f);
                PoolGroup<Quest>& questgroup = mPoolQuestGroups[pool_id];
                questgroup.SetPoolId(pool_id);
                questgroup.AddEntry(plObject, pPoolTemplate->MaxLimit);
                SearchPair p(entry, pool_id);
                mQuestSearchMap.insert(p);

                ++count;
            }
            while (result->NextRow());

            TC_LOG_INFO("server.loading", ">> Loaded %u quests in pools in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
        }
    }

    // The initialize method will spawn all pools not in an event and not in another pool, this is why there is 2 left joins with 2 null checks
    TC_LOG_INFO("server.loading", "Starting objects pooling system...");
    {
        uint32 oldMSTime = getMSTime();

        QueryResult result = WorldDatabase.Query("SELECT DISTINCT pool_template.entry, pool_pool.pool_id, pool_pool.mother_pool FROM pool_template"
            " LEFT JOIN game_event_pool ON pool_template.entry=game_event_pool.pool_entry"
            " LEFT JOIN pool_pool ON pool_template.entry=pool_pool.pool_id WHERE game_event_pool.pool_entry IS NULL");

        if (!result)
        {
            TC_LOG_INFO("server.loading", ">> Pool handling system initialized, 0 pools spawned.");
        }
        else
        {
            uint32 count = 0;
            do
            {
                Field* fields = result->Fetch();
                uint32 pool_entry = fields[0].GetUInt32();
                uint32 pool_pool_id = fields[1].GetUInt32();

                if (!CheckPool(pool_entry))
                {
                    if (pool_pool_id)
                        // The pool is a child pool in pool_pool table. Ideally we should remove it from the pool handler to ensure it never gets spawned,
                        // however that could recursively invalidate entire chain of mother pools. It can be done in the future but for now we'll do nothing.
                        TC_LOG_ERROR("sql.sql", "Pool Id %u has no equal chance pooled entites defined and explicit chance sum is not 100. This broken pool is a child pool of Id %u and cannot be safely removed.", pool_entry, fields[2].GetUInt32());
                    else
                        TC_LOG_ERROR("sql.sql", "Pool Id %u has no equal chance pooled entites defined and explicit chance sum is not 100. The pool will not be spawned.", pool_entry);
                    continue;
                }

                // Don't spawn child pools, they are spawned recursively by their parent pools
                if (!pool_pool_id)
                {
                    SpawnPool(pool_entry);
                    count++;
                }
            }
            while (result->NextRow());

            TC_LOG_DEBUG("pool", "Pool handling system initialized, %u pools spawned in %u ms", count, GetMSTimeDiffToNow(oldMSTime));

        }
    }
}
TEST(PlanningInterfaceTester, loadAllPlanners)
{
  pluginlib::ClassLoader<planning_interface::Planner>* planner_loader;
  try
  {
    planner_loader = new pluginlib::ClassLoader<planning_interface::Planner>("planning_interface", "planning_interface::Planner");
  }
  catch(pluginlib::PluginlibException& ex)
  {
    FAIL() << "Exception while creating class loader " << ex.what();
  }

  std::vector<std::string> classes;
  std::vector<boost::shared_ptr<planning_interface::Planner> > planners;
  planning_scene::PlanningSceneConstPtr scene = g_psm->getPlanningScene();
  planning_models::RobotModelConstPtr model = scene->getRobotModel();

  classes = planner_loader->getDeclaredClasses();
  // Must have some planners
  ASSERT_GT(classes.size(), 0);
  printf("Loading classes:\n");
  for(std::vector<std::string>::const_iterator it = classes.begin();
      it != classes.end();
      ++it)
    printf("  %s\n", it->c_str());
  fflush(stdout);
  return;

  for(std::vector<std::string>::const_iterator it = classes.begin();
      it != classes.end();
      ++it)
  {
    try
    {
      boost::shared_ptr<planning_interface::Planner> p(planner_loader->createUnmanagedInstance(*it));
      p->init(model);
      planners.push_back(p);
    }
    catch(pluginlib::PluginlibException& ex)
    {
      // All planners must load
      ADD_FAILURE() << "Exception while loading planner: " << *it << ": " << ex.what();
    }
  }

  for(std::vector<boost::shared_ptr<planning_interface::Planner> >::const_iterator it = planners.begin();
      it != planners.end();
      ++it)
  {
    // A dumb test: require that the planners return true from
    // canServiceRequest
    moveit_msgs::GetMotionPlan::Request req;
    planning_interface::PlannerCapability capabilities;
    bool can_service = (*it)->canServiceRequest(req, capabilities);
    EXPECT_TRUE(can_service);

    // Another dumb test: require that the planners return false from solve
    moveit_msgs::GetMotionPlan::Response res;
    bool solved = (*it)->solve(scene, req, res);
    EXPECT_FALSE(solved);
  }
}
Пример #25
0
 static void incorporate_after(const node_ptr & bp, const node_ptr & b, const node_ptr & be)
 {
    node_ptr p(NodeTraits::get_next(bp));
    NodeTraits::set_next(bp, b);
    NodeTraits::set_next(be, p);
 }
Пример #26
0
void test_p() {
  int* ip = p((short)1);
  double* dp = p(1.0f);
}
Пример #27
0
bool Robot::locateOwnGate()
{
    IplImage* wMap = worldMap.getMap();
    uchar* wMap_data = (uchar*)wMap->imageData;
    float center_x = 0, center_y = 0;
    float n = 0;
    for(int i = 0; i < MAP_LEN; i++)
    {
        for(int j = 0; j < MAP_LEN; j++)
        {
            int b = wMap_data[i*MAP_LEN*3+j*3+0];
            int g = wMap_data[i*MAP_LEN*3+j*3+1];
            int r = wMap_data[i*MAP_LEN*3+j*3+2];
            if(b == 255 && g==0 && r==0)
            {
                center_x += j;
                center_y += i;
                n++;
            }
        }
    }
    if(n < 10)
    {
        cvReleaseImage(&wMap);
        return false;
    }
    else
    {
        center_x = center_x/n;
        center_y = center_y/n;
        ownGoal_coord.x = center_x - (MAP_LEN>>1);
        ownGoal_coord.y = (MAP_LEN>>1)+1-center_y;
        ownGoalLocated = true;

        cv::Point2f end1,end2,center(center_x,center_y);
        float dist_max = 0;
        for(int i = 0; i < MAP_LEN; i++)
        {
            for(int j = 0; j < MAP_LEN; j++)
            {
                int b = wMap_data[i*MAP_LEN*3+j*3+0];
                int g = wMap_data[i*MAP_LEN*3+j*3+1];
                int r = wMap_data[i*MAP_LEN*3+j*3+2];
                cv::Point2f p(j,i);
                float dist = length(center-p);
                if(b == 255 && g==0 && r==0 && dist>dist_max)
                {
                    dist_max = dist;
                    end1 = p;
                }
            }
        }
        dist_max = 0;
        for(int i = 0; i < MAP_LEN; i++)
        {
            for(int j = 0; j < MAP_LEN; j++)
            {
                int b = wMap_data[i*MAP_LEN*3+j*3+0];
                int g = wMap_data[i*MAP_LEN*3+j*3+1];
                int r = wMap_data[i*MAP_LEN*3+j*3+2];
                cv::Point2f p(j,i);
                float dist = length(center-p);
                if(b == 255 && g==0 && r==0 && dist>dist_max && (p-center).dot(end1-center)<0)
                {
                    dist_max = dist;
                    end2 = p;
                }
            }
        }
        cv::Point2f goalWidthDir = end1-end2;
        ownGoal_width = length(goalWidthDir);
        ownGoal_frontDir = cv::Point2f(-goalWidthDir.y,goalWidthDir.x);
        ownGoal_frontDir = ownGoal_frontDir*(1/length(ownGoal_frontDir));
        ownGoal_frontDir.y = -ownGoal_frontDir.y;

        cv::Point2f robot_coord(x,y);
        if(ownGoal_frontDir.dot(robot_coord - ownGoal_coord)<0)
        {
            ownGoal_frontDir = -ownGoal_frontDir;
        }
        cvReleaseImage(&wMap);
        return true;
    }
}
Пример #28
0
//-----------------------------------------------------------
void FormExportacao::exportarModelo(void)
{
 try
 {
  //Redimensiona a janela para exibição dos widgets de progresso
  this->resize(this->maximumSize());

  //Exibe os widgets de progresso
  prog_pb->setValue(0);
  ln2_frm->setVisible(true);
  rot_prog_lbl->setVisible(true);
  prog_pb->setVisible(true);

  //Inicialmente o ícone de sucesso/erro da exportação fica escondido
  ico_lbl->setVisible(false);

  if(exportacao_png_rb->isChecked())
  {
   QPixmap pix;
   QRectF ret=modelo_wgt->cena->itemsBoundingRect();
   bool exibir_grade, exibir_lim, alin_objs;

   //Faz um backup das opções de grade da cena
   CenaObjetos::obterOpcoesGrade(exibir_grade, alin_objs, exibir_lim);

   //Redefine as opções da grade conforme os checkboxes
   CenaObjetos::definirOpcoesGrade(grade_chk->isChecked(), false, lim_paginas_chk->isChecked());

   //Cria o pixmap
   pix.resize(ret.size().toSize());

   ///Desenha a cena no pixmap e faz a escala correta
   QPainter p(&pix);
   modelo_wgt->cena->update();
   modelo_wgt->cena->render(&p, QRectF(QPointF(0,0), pix.size()), ret);

   //Restaura as definições da grade
   CenaObjetos::definirOpcoesGrade(exibir_grade, alin_objs, exibir_lim);
   modelo_wgt->cena->update();

   //Caso a imagem não possa ser salva, retorna um erro
   if(!pix.save(imagem_edt->text()))
    throw Excecao(Excecao::obterMensagemErro(ERR_PGMODELER_ARQNAOGRAVADO).arg(QString::fromUtf8(imagem_edt->text())),
                  ERR_PGMODELER_ARQNAOGRAVADO,__PRETTY_FUNCTION__,__FILE__,__LINE__);



  }
  else
  {
   int id_tipo;
   QString  versao, buf_sql, cmd_sql;
   ConexaoBD *conexao=NULL, conex_novo_bd;
   unsigned i, qtd;
   bool bd_criado=false;
   int idx_objs[]={-1, -1};
   TipoObjetoBase vet_tipos[]={OBJETO_PAPEL, OBJETO_ESPACO_TABELA};
   ObjetoBase *objeto=NULL;
   vector<Excecao> vet_erros;


   /* Vetor que armazena os códigos de erros referentes a objetos duplicados no PostgreSQL:
    Estes erros podem ser consultados na íntegra em:
      http://www.postgresql.org/docs/current/static/errcodes-appendix.html

    Códigos usados neste método:
     42P04 	duplicate_database
     42723 	duplicate_function
     42P06 	duplicate_schema
     42P07 	duplicate_table
     42710 	duplicate_object
  */
   QString cod_erros[]={"42P04", "42723", "42P06", "42P07", "42710"};
   vector<QString> vet_cod_erros;

   try
   {
    for(i=0; i < 5; i++)
     vet_cod_erros.push_back(cod_erros[i]);

    //Configura o widget de progresso para capturar o progresso da geração do código
    prog_tarefa->setWindowTitle(trUtf8("Generating source code..."));
    prog_tarefa->show();
    connect(this->modelo_wgt->modelo, SIGNAL(s_objetoCarregado(int,QString,unsigned)),
            prog_tarefa, SLOT(executarProgesso(int,QString,unsigned)));

    rot_prog_lbl->setText(trUtf8("Initializing model export..."));
    rot_prog_lbl->repaint();

    //Caso seja exportação em arquivo
    if(exportacao_arq_rb->isChecked())
    {
     //Define a versão do postgresql a ser adotada
     ParserEsquema::definirVersaoPgSQL(pgsqlvers_cmb->currentText());

     rot_prog_lbl->setText(trUtf8("Saving file '%1'").arg(arquivo_edt->text()));

     //Salva o modelo em arquivo
     modelo_wgt->modelo->salvarModelo(arquivo_edt->text(), ParserEsquema::DEFINICAO_SQL);
     prog_pb->setValue(25);
    }
    //Caso seja exportação direto para o SGBD
    else
    {
     //Obtém a conexão selecionada no combo
     conexao=reinterpret_cast<ConexaoBD *>(conexoes_cmb->itemData(conexoes_cmb->currentIndex()).value<void *>());
     //Tenta se conectar
     conexao->conectar();
     //Obtém a versão do servidor PostgreSQL. Essa versão é usada na geração de código a seguir
     versao=(conexao->obterVersaoSGBD()).mid(0,3);

     /* Caso o checkbox de versão esteja marcada então a versão do servidor é ignorada
      usando aquela escolhida no combo */
     if(pgsqlvers_chk->isChecked())
      ParserEsquema::definirVersaoPgSQL(pgsqlvers1_cmb->currentText());
     else
      ParserEsquema::definirVersaoPgSQL(versao);


     //Cria os Papéis e espaços de tabela separadamente dos demais
     for(id_tipo=0; id_tipo < 2; id_tipo++)
     {
      qtd=modelo_wgt->modelo->obterNumObjetos(vet_tipos[id_tipo]);
      for(i=0; i < qtd; i++)
      {
       objeto=modelo_wgt->modelo->obterObjeto(i, vet_tipos[id_tipo]);
       rot_prog_lbl->setText(trUtf8("Creating object '%1' (%2)...").arg(QString::fromUtf8(objeto->obterNome())).arg(objeto->obterNomeTipoObjeto()));
       rot_prog_lbl->repaint();

       try
       {
        conexao->executarComandoDDL(objeto->obterDefinicaoObjeto(ParserEsquema::DEFINICAO_SQL));
       }
       catch(Excecao &e)
       {
        /* Caso o checkbox de ignorar duplicidade não esteja marcado ou se este está marcado porém a
         informação adicinal da exceção não carrega um dos códigos indicando duplicidade de objeto
         redireciona o erro, caso contrário apenas o ignora */
        if(!ignorar_dup_chk->isChecked() ||
           (ignorar_dup_chk->isChecked() &&
            std::find(vet_cod_erros.begin(), vet_cod_erros.end(), e.obterInfoAdicional())==vet_cod_erros.end()))
         throw Excecao(e.obterMensagemErro(),
                       e.obterTipoErro(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e);
        else
         vet_erros.push_back(e);
       }

       prog_pb->setValue((10 * (id_tipo+1)) + ((i/static_cast<float>(qtd)) * 10));
       idx_objs[id_tipo]++;
      }
     }

     //Cria o banco de dados no servidor
     rot_prog_lbl->setText(trUtf8("Creating database '%1'...").arg(QString::fromUtf8(modelo_wgt->modelo->obterNome())));
     rot_prog_lbl->repaint();

     try
     {
      conexao->executarComandoDDL(modelo_wgt->modelo->__obterDefinicaoObjeto(ParserEsquema::DEFINICAO_SQL));
      bd_criado=true;
     }
     catch(Excecao &e)
     {
      /* Caso o checkbox de ignorar duplicidade não esteja marcado ou se este está marcado porém a
       informação adicinal da exceção não carrega um dos códigos indicando duplicidade de objeto
       redireciona o erro, caso contrário apenas o ignora */
      if(!ignorar_dup_chk->isChecked() ||
         (ignorar_dup_chk->isChecked() &&
          std::find(vet_cod_erros.begin(), vet_cod_erros.end(), e.obterInfoAdicional())==vet_cod_erros.end()))
       throw Excecao(e.obterMensagemErro(),
                     e.obterTipoErro(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e);
      else
       vet_erros.push_back(e);
     }

     prog_pb->setValue(30);

     conex_novo_bd=(*conexao);
     conex_novo_bd.definirParamConexao(ConexaoBD::PARAM_NOME_BD, modelo_wgt->modelo->obterNome());
     rot_prog_lbl->setText(trUtf8("Connecting to database '%1'...").arg(QString::fromUtf8(modelo_wgt->modelo->obterNome())));
     rot_prog_lbl->repaint();
     conex_novo_bd.conectar();
     prog_pb->setValue(50);

     //Cria os demais objetos no novo banco
     rot_prog_lbl->setText(trUtf8("Creating objects on database '%1'...").arg(QString::fromUtf8(modelo_wgt->modelo->obterNome())));
     rot_prog_lbl->repaint();

     //Gera o código SQL de todo o banco
     buf_sql=modelo_wgt->modelo->obterDefinicaoObjeto(ParserEsquema::DEFINICAO_SQL, false);

     /* Extrai cada comando SQL do buffeer e o executa separadamente, isso é feito
      para que, em caso de erro, o usuário saiba exatamente a SQL que gerou a
      exceção uma vez que a libpq não proporciona este nível de detalhes */
     i=0;
     qtd=buf_sql.size();

     while(i < qtd)
     {
      try
      {
       cmd_sql.clear();

       //Executa um trimm no comando SQL extraído
       cmd_sql=cmd_sql.trimmed();

       //Extrai os caracteres até encontrar o final do buffer ou um ';'
       while(i < qtd)
       {
        /* Caso o caracter seja um ';' e o próximo seja uma quebra de linha, significa o final do comando SQL
           assim a varredura será interrompida */
        if(buf_sql.at(i)==';' && buf_sql.at(i+1)=='\n')
        {
         cmd_sql+=';';
         break;
        }
        else
         cmd_sql+=buf_sql.at(i);
        i++;
       }

       //Executa um trimm no comando SQL extraído
       //cmd_sql=cmd_sql.trimmed();

       //Caso o comando não esteja vazio
       if(!cmd_sql.isEmpty())
       {
        i++;
        //Executa-o na conexão
        conex_novo_bd.executarComandoDDL(cmd_sql);
       }

       prog_pb->setValue(50 + ((i/static_cast<float>(qtd)) * 10));
      }
      catch(Excecao &e)
      {
       /* Caso o checkbox de ignorar duplicidade não esteja marcado ou se este está marcado porém a
        informação adicinal da exceção não carrega um dos códigos indicando duplicidade de objeto
        redireciona o erro, caso contrário apenas o ignora */
       if(!ignorar_dup_chk->isChecked() ||
          (ignorar_dup_chk->isChecked() &&
           std::find(vet_cod_erros.begin(), vet_cod_erros.end(), e.obterInfoAdicional())==vet_cod_erros.end()))
        throw Excecao(Excecao::obterMensagemErro(ERR_PGMODELERUI_FALHAEXPORTACAO).arg(QString::fromUtf8(cmd_sql)),
                      ERR_PGMODELERUI_FALHAEXPORTACAO,__PRETTY_FUNCTION__,__FILE__,__LINE__,&e);
       else
        vet_erros.push_back(e);
      }
     }
    }

    prog_tarefa->close();
    disconnect(this->modelo_wgt->modelo, NULL, prog_tarefa, NULL);
   }
   catch(Excecao &e)
   {
    QString drop_cmd=QString("DROP %1 %2;");

    prog_tarefa->close();
    disconnect(this->modelo_wgt->modelo, NULL, prog_tarefa, NULL);

    /* Caso os algum objeto tenha sido criado é preciso excluí-los do banco.
     Para isso, os mesmos são removidos na ordem contrária de criação:
     banco de dados, espaço de tabelas e papéis */
    if(bd_criado || idx_objs[0] >= 0 || idx_objs[1] >= 0)
    {
     if(conex_novo_bd.conexaoEstabelecida())
      conex_novo_bd.fechar();

     //Caso o banco de dados foi criado, exclui o mesmo
     if(bd_criado)
      conexao->executarComandoDDL(drop_cmd
                                  .arg(modelo_wgt->modelo->obterNomeSQLObjeto())
                                  .arg(modelo_wgt->modelo->obterNome(true)));

     //Removendo os espaços de tabela e papéis
     for(id_tipo=1; id_tipo >=0; id_tipo--)
     {
      while(idx_objs[id_tipo] >= 0)
      {
       objeto=modelo_wgt->modelo->obterObjeto(idx_objs[id_tipo], vet_tipos[id_tipo]);

       try
       {
        conexao->executarComandoDDL(drop_cmd
                                    .arg(objeto->obterNomeSQLObjeto())
                                    .arg(objeto->obterNome(true)));
       }
       catch(Excecao &e)
       {}

       idx_objs[id_tipo]--;
      }
     }
    }

    if(vet_erros.empty())
     throw Excecao(e.obterMensagemErro(),e.obterTipoErro(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
    else
    {
     vet_erros.push_back(e);
     throw Excecao(e.obterMensagemErro(),__PRETTY_FUNCTION__,__FILE__,__LINE__, vet_erros);
    }
   }
  }

  //Finaliza o progresso da exportação
  prog_pb->setValue(100);
  rot_prog_lbl->setText(trUtf8("Exporting process sucessfuly ended!"));
  rot_prog_lbl->repaint();
  ico_lbl->setPixmap(QPixmap(QString(":/icones/icones/msgbox_info.png")));
  ico_lbl->setVisible(true);

  //Oculta os widgets de progresso após 10 segundos
  QTimer::singleShot(5000, this, SLOT(ocultarProgressoExportacao(void)));
 }
 catch(Excecao &e)
 {
  //Exibe no progresso a mensagem de falha
  rot_prog_lbl->setText(trUtf8("Error on export!"));
  rot_prog_lbl->repaint();
  ico_lbl->setPixmap(QPixmap(QString(":/icones/icones/msgbox_erro.png")));
  ico_lbl->setVisible(true);

  //Oculta os widgets de progresso após 10 segundos
  QTimer::singleShot(5000, this, SLOT(ocultarProgressoExportacao(void)));
  caixa_msg->show(e);
 }
}
int main(int argc, char *argv[])
{

#   include "addTimeOptions.H"
#   include "setRootCase.H"

#   include "createTime.H"

    // Get times list
    instantList Times = runTime.times();

    // set startTime and endTime depending on -time and -latestTime options
#   include "checkTimeOptions.H"

    runTime.setTime(Times[startTime], startTime);

#   include "createMesh.H"

    runTime.setTime(Times[endTime-1], endTime-1);

    volScalarField pMean
    (
        IOobject
        (
            "pMean",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        ),
        mesh
    );

    for (label i=startTime; i<endTime; i++)
    {
        runTime.setTime(Times[i], i);

        Info<< "Time = " << runTime.timeName() << endl;

        IOobject pheader
        (
            "p",
            runTime.timeName(),
            mesh,
            IOobject::MUST_READ
        );

        // Check p exists
        if (pheader.headerOk())
        {
            mesh.readUpdate();

            Info<< "    Reading p" << endl;
            volScalarField p(pheader, mesh);

            Info<< "    Calculating pPrime2" << endl;
            volScalarField pPrime2
            (
                IOobject
                (
                    "pPrime2",
                    runTime.timeName(),
                    mesh,
                    IOobject::NO_READ
                ),
                sqr(p - pMean)
            );
            pPrime2.write();
        }
        else
        {
            Info<< "    No p" << endl;
        }

        Info<< endl;
    }

    return(0);
}
Пример #30
0
Prop *Prop::AllocFontWeight(FontStyle style)
{
    Prop p(PropFontWeight);
    p.fontWeight = style;
    return UniqifyProp(p);
}