/**
*	short simulation with out frition to remove some potential energy and magic bullet energy
*/
bool Physics::relaxCreature(){
	enableEffectors=false;
	btCollisionObject* ground = m_dynamicsWorld->getCollisionObjectArray().at(0);
	btScalar friction = ground->getFriction();
	ground->setFriction(0);
	//float last = 0.f;
	float margin = 0.0000001f;
	int size = m_dynamicsWorld->getCollisionObjectArray().size();
	std::vector<float> last = std::vector<float>();
	std::vector<float> Ys = std::vector<float>();
	for(int i = 1; i < m_dynamicsWorld->getCollisionObjectArray().size(); i++){
		last.push_back(m_dynamicsWorld->getCollisionObjectArray().at(i)->getWorldTransform().getOrigin().y());
	}
	int count = 0;int totalCount=0;
	while(count<20){
		simulationLoopStep(1/1000.f);
		//float center = calcPosition().y();
		//if(center<(last+0.0000001f)&&center>(last-0.0000001f)){count++;}
		bool succeeded = true;
		for(int j = 1; j<m_dynamicsWorld->getCollisionObjectArray().size(); j++){
			float y = m_dynamicsWorld->getCollisionObjectArray().at(j)->getWorldTransform().getOrigin().y();
			if(!(y<(last.at(j-1)+margin) && y>(last.at(j-1)-margin))){
				succeeded = false;
			}
			Ys.push_back(y);
		}
		if(succeeded){count++;}
		else{count=0;}
		last.swap(Ys);
		Ys.clear();
		if(totalCount>20000){
			ground->setFriction(friction);
			startPoint=calcPosition();
			pastPoint=startPoint;
			enableEffectors=true;
			fitness=0;
			for(int dead=0;dead<tests.size();dead++){
				tests.at(dead).value=0;
			}
#ifdef _DEBUG
			printf("relax failed");
#endif
			return false;
		}
		totalCount++;
	}
	ground->setFriction(friction);
	startPoint=calcPosition();
	pastPoint=startPoint;
	enableEffectors=true;

	fitness=0;
	for(int dead=0;dead<tests.size();dead++){
		tests.at(dead).value=0;
	}
	return true;
}
Example #2
0
void updateCam( Camera *cam ) {

    State *state = cam->state;

    /* update target orientation */
    applyTorque( state );
    quatSlerp( state->orientation, state->targetOrien, state->orientation, cam->smoothing );
    quatNorm( state->orientation );

    /* rotation matrix */
    GLfloat rotaMatrix[16];
    quatToMat(rotaMatrix, state->orientation);

    /* update orientation vectors */
    mat4multVec3(rotaMatrix, baseUpVec, state->up );
    mat4multVec3(rotaMatrix, baseRightVec, state->right );
    mat4multVec3(rotaMatrix, baseForwardVec, state->forward );

    // calc & update velocity
    float newVel[] = {
        state->velocity[0] + lerpStep(state->velocity[0], state->targetVelocity[0], cam->smoothing ),
        state->velocity[1] + lerpStep(state->velocity[1], state->targetVelocity[1], cam->smoothing ),
        state->velocity[2] + lerpStep(state->velocity[2], state->targetVelocity[2], cam->smoothing )
    };
    cpyBuf( state->velocity, newVel, 3 );
    calcPosition( state->position, state, 1.0f);
    watch( "Camera Position ( %.1f, %.1f, %.1f )\n", state->position[0], state->position[1], state->position[2] );

    // calc & store perspective
    cam->fov[0] += lerpStep( cam->fov[0], cam->fov[1], cam->smoothing );
    mat4perspinf( cam->perspective, cam->nearClip, cam->fov[0], cam->aspectRatio );
}
Example #3
0
/**
 * Tooltip position depends on the screen quadrant of the source
 */
void MenuTooltip::render(TooltipData tip, Point pos, int style) {
	SDL_Rect background;
	
	string fulltext;
	
	fulltext = tip.lines[0];
	for (int i=1; i<tip.num_lines; i++) {
		fulltext = fulltext + "\n" + tip.lines[i];
	}
	
	Point size = font->calc_size(fulltext, width);
	background.w = size.x + margin + margin;
	background.h = size.y + margin + margin;
	
	int cursor_x;
	int cursor_y;
	
	calcPosition(style, pos, size, background.x, background.y, cursor_x, cursor_y);
	
	SDL_FillRect(screen, &background, 0);
	for (int i=0; i<tip.num_lines; i++) {
		font->render(tip.lines[i], cursor_x, cursor_y, JUSTIFY_LEFT, screen, size.x, tip.colors[i]);
		cursor_y = font->cursor_y;
	}
			
}
Example #4
0
void animate(void)
{
  if (deltaMove) {
    calcPosition(deltaMove);
  }

  glutPostRedisplay();
}
  void 
  GVolumetricPotential::runEvent(Particle& part, const double dt)  {
    //Despite the system not being streamed this must be done.  This is
    //because the scheduler and all interactions, locals and systems
    //expect the particle to be up to date.
    Sim->dynamics->updateParticle(part);

    const size_t oldCellIndex = _cellData.getCellID(part.getID());
    const int cellDirectionInt(Sim->dynamics->getSquareCellCollision3(part, calcPosition(oldCellIndex, part), _cellDimension));
    const size_t cellDirection = abs(cellDirectionInt) - 1;

    GlobalEvent iEvent(getEvent(part));

#ifdef DYNAMO_DEBUG 
    if (std::isnan(iEvent.getdt()))
      M_throw() << "A NAN Interaction collision time has been found when recalculating this global"
		<< iEvent.stringData(Sim);
#endif

    Sim->systemTime += iEvent.getdt();
    Sim->ptrScheduler->stream(iEvent.getdt());  
    Sim->stream(iEvent.getdt());

    //Calculate which cell the particle might end up in
    const auto oldCellCoord = _ordering.toCoord(oldCellIndex);
    auto newCellCoord = oldCellCoord;
    newCellCoord[cellDirection] += _ordering.getDimensions()[cellDirection] + ((cellDirectionInt > 0) ? 1 : -1);
    newCellCoord[cellDirection] %= _ordering.getDimensions()[cellDirection];
    const size_t newCellIndex = _ordering.toIndex(newCellCoord);


    Vector vNorm{0,0,0};
    vNorm[cellDirection] = (cellDirectionInt > 0) ? -1 : 1;

    NEventData EDat;

    //Run the collision and catch the data
    Sim->dynamics->updateParticle(part);    
    Vector pos(part.getPosition()), vel(part.getVelocity());
    Sim->BCs->applyBC(pos, vel);
    double potEnergyChange = 0.5 * (double(_volumeData[newCellIndex]) - double(_volumeData[oldCellIndex]));
    double arg =  vel[cellDirection] * vel[cellDirection] - 2 * potEnergyChange / Sim->species(part)->getMass(part);
    if (arg > 0)
      {
	EDat = ParticleEventData(part, *Sim->species(part), WALL);
	part.getVelocity()[cellDirection] *= std::sqrt(arg) / std::abs(part.getVelocity()[cellDirection]);
	_cellData.moveTo(oldCellIndex, newCellIndex, part.getID());
      }
    else
      EDat = Sim->dynamics->runPlaneEvent(part, vNorm, 1.0, 0.0);
    
    //Now we're past the event update the scheduler and plugins
    Sim->_sigParticleUpdate(EDat);
    Sim->ptrScheduler->fullUpdate(part);  
    for (shared_ptr<OutputPlugin> & Ptr : Sim->outputPlugins)
      Ptr->eventUpdate(iEvent, EDat);
  }
Example #6
0
QGraphicsPolygonItem * KiviatView::addMarker(float position)
{
   QPolygonF polygon;

   for(int i=0; i<axisCount; i++)
      polygon << calcPosition(i,position);

   QGraphicsPolygonItem * polyItem = scene.addPolygon(polygon);
   polyItem->setZValue(0);

   return polyItem;
}
/**
*	calculates fitness based on last move and time since start
*/
float Physics::fitMove2(){
	btVector3 tmpPos = calcPosition();
	btVector3 pastVector = pastPoint-startPoint;
	btVector3 vector = tmpPos-startPoint;
	pastPoint = tmpPos;

	float pastLength = sqrt(pastVector.getX()*pastVector.getX()+pastVector.getZ()*pastVector.getZ());
	float length = sqrt(vector.getX()*vector.getX()+vector.getZ()*vector.getZ());

	float weight = totaltime/10000.f;
	return (length-pastLength)*weight;
}
Example #8
0
  Vector 
  GCells::calcPosition(const magnet::math::MortonNumber<3>& coords, const Particle& part) const
  {
    //We always return the cell that is periodically nearest to the particle
    Vector primaryCell = calcPosition(coords);
    Vector imageCell;
  
    for (size_t i = 0; i < NDIM; ++i)
      imageCell[i] = primaryCell[i]
	- Sim->primaryCellSize[i] * lrint((primaryCell[i] - part.getPosition()[i]) 
					  / Sim->primaryCellSize[i]);

    return imageCell;
  }
Example #9
0
void cam_rh2v2_cordlg::reconfigure(int widthNew,int heightNew){
    if(plotters!=NULL){
        for(int x=0;x<width;x++){
            for(int y=0;y<height;y++){
                int i=y*width+x;
                if(plotters[i]!=NULL){
                    ui->glPlotter->removeWidget(plotters[i]);
                    int xp=calcPosition(32,width,x);
                    int yp=calcPosition(32,height,y);
                    plotters[i]->deletePlot(plots[32*yp+xp]);
                    plots[32*yp+xp]->setParent(NULL);
                    delete plotters[i];
                }
            }
        }
        qfFree(plotters);
    }
    width=widthNew;
    height=heightNew;
    plotters=static_cast<JKQTFastPlotter**>(qfMalloc(width*height*sizeof(JKQTFastPlotter*)));
    for(int x=0;x<width;x++){
        for(int y=0;y<height;y++){
            int i=y*width+x;
            plotters[i]=(JKQTFastPlotter*) new JKQTFastPlotter(this);
            ui->glPlotter->addWidget(plotters[i],y,x);
            int xp=calcPosition(32,width,x);
            int yp=calcPosition(32,height,y);
            plotters[i]->addPlot(plots[32*yp+xp]);
            plotters[i]->set_yMin(ui->dsbMin->value());
            plotters[i]->set_yMax(ui->dsbMax->value());
            plots[32*yp+xp]->setParent(plotters[y*width+x]);
            QObject::connect(ui->dsbMin, SIGNAL(valueChanged(double)), plotters[i], SLOT(set_yMin(double)));
            QObject::connect(ui->dsbMax, SIGNAL(valueChanged(double)), plotters[i], SLOT(set_yMax(double)));
        }
    }
    emit reconfigure(this->camera);
}
Example #10
0
void KiviatView::redrawAll()
{
   //Delete markers and axes,keep the captions
   qDeleteAll(markers);
   qDeleteAll(axes);
   markers.clear();
   axes.clear();

   setupAxesCaptions();

   //Paint Axes and adjust label position
   for(int i=0; i<axisCount; i++)
   {
      //Draw the axis-line
      QGraphicsLineItem * line= scene.addLine(QLineF(QPointF(0,0),calcPosition(i,1)));
      line->setZValue(1);
      axes.push_back(line);

      // Why Position 1.08?  Pos 1.0 means end of axis
      // label is positioned a litte bit further away from center
      // also needed in setAxisLabel
      QPointF lPos = calcPosition(i, 1.08);
      axisLabels[i]->setPos(QPoint(0,0));
      axisLabels[i]->moveBy(lPos.x(),lPos.y());

      // If the axis is on the left side, the text has to be moved to the left
      if( axisLabels[i]->pos().x()<0 )
         axisLabels[i]->moveBy(- axisLabels[i]->boundingRect().width(),0);
   }

   //Call setMarkerCount with current count, to paint them
   setMarkerCount(prop_markerCount);

   redrawData();

}
Example #11
0
/**
 * Tooltip position depends on the screen quadrant of the source.
 * Draw the buffered tooltip if it exists, else render the tooltip and buffer it
 */
void WidgetTooltip::render(TooltipData &tip, Point pos, int style) {

	if (tip.tip_buffer == NULL) {
		createBuffer(tip);
	}

	Point size;
	size.x = tip.tip_buffer->w;
	size.y = tip.tip_buffer->h;
		
	Point tip_pos = calcPosition(style, pos, size);

	SDL_Rect dest;
	dest.x = tip_pos.x;
	dest.y = tip_pos.y;
	
	SDL_BlitSurface(tip.tip_buffer, NULL, screen, &dest);
}
Example #12
0
  GlobalEvent 
  GCellsShearing::getEvent(const Particle& part) const
  {
#ifdef ISSS_DEBUG
    if (!Sim->dynamics->isUpToDate(part))
      M_throw() << "Particle is not up to date";
#endif

    //We do not inherit GCells get Event as the calcPosition thing done
    //for infinite systems is breaking it for shearing for some reason.
    return GlobalEvent(part,
		       Sim->dynamics->
		       getSquareCellCollision2
		       (part, calcPosition(partCellData[part.getID()]), 
			cellDimension)
		       - Sim->dynamics->getParticleDelay(part),
		       CELL, *this);
  }
void Genetic_AlgorithmApp::mouseDrag(MouseEvent event)
{
#if 0
    if (m_isBuilder)
    {
        float u = static_cast<float>(event.getX()) / static_cast<float>(getWindowWidth());
        float v = static_cast<float>(event.getY()) / static_cast<float>(getWindowHeight());

        auto ray = m_camera.getCamera().generateRay(u, v, static_cast<float>(m_algoGenResult.getWidth()) / static_cast<float>(m_algoGenResult.getHeight()));

        float result;

        if (ray.calcPlaneIntersection(ci::Vec3f::zero(), ci::Vec3f::zAxis(), &result))
        {
            auto intersect = ray.calcPosition(result);

            int demiW = m_algoGenResult.getWidth() / 2;
            int demiH = m_algoGenResult.getHeight() / 2;

            if (intersect.x <= demiW && intersect.x >= -demiW &&
                intersect.y <= demiH && intersect.y >= -demiH)
            {
                auto heightPos = ci::Vec2i(static_cast<int>(intersect.x + demiW), static_cast<int>(-intersect.y + demiH));
                auto pixel = m_heightMap.getPixel(heightPos);

                /*pixel.r = tools::clamp(0.0f, 255.0f, pixel.r + 2.0f);
                pixel.g = tools::clamp(0.0f, 255.0f, pixel.g + 1.0f);
                pixel.b = tools::clamp(0.0f, 255.0f, pixel.b + 3.0f);*/

                pixel.r = tools::clamp(0.0f, std::numeric_limits<float>::max(), pixel.r + 2.0f);
                pixel.g = tools::clamp(0.0f, std::numeric_limits<float>::max(), pixel.g + 1.0f);
                pixel.b = tools::clamp(0.0f, std::numeric_limits<float>::max(), pixel.b + 3.0f);

                m_heightMap.setPixel(heightPos, pixel);
            }
        }
    }
#endif
}
void EnMapView::setupMapView()
{
    // get the screen size
    unsigned int windowwidth  = 600;
    unsigned int windowheight = 800;
    yaf3d::Application::get()->getScreenSize( windowwidth, windowheight );
    _screenSize = osg::Vec2f( static_cast< float >( windowwidth ), static_cast< float >( windowheight ) );

    // calculate internal variables
    _factor   = osg::Vec2f( ( 1.0f / _levelDimensions.x() ) * _stretch.x(), ( 1.0f / _levelDimensions.y() ) * _stretch.y() );
    _halfSize = osg::Vec2f( _size * 0.5f );

    try
    {
        // calculate position of view map
        osg::Vec2 position = calcPosition( _align, _size, _screenSize );
        _snapPoints = calcSnapPoints( _size, _screenSize );

        _p_wnd = CEGUI::WindowManager::getSingleton().createWindow( "DefaultWindow", MAPVIEW_WND "mainWnd" );
        _p_wnd->setMetricsMode( CEGUI::Absolute );
        _p_wnd->setSize( CEGUI::Size( _size.x(), _size.y() ) );
        _p_wnd->setPosition( CEGUI::Point( position.x(), position.y() ) );
        _p_wnd->setAlpha( _alpha );
        _p_wnd->setAlwaysOnTop( true );
        _p_wnd->subscribeEvent( CEGUI::Window::EventMouseButtonDown, CEGUI::Event::Subscriber( &vrc::EnMapView::onMouseDown, this ) );
        _p_wnd->subscribeEvent( CEGUI::Window::EventMouseButtonUp,   CEGUI::Event::Subscriber( &vrc::EnMapView::onMouseUp,   this ) );
        _p_wnd->subscribeEvent( CEGUI::Window::EventMouseMove,       CEGUI::Event::Subscriber( &vrc::EnMapView::onMouseMove, this ) );

        // put the map picture into a static image element
        CEGUI::StaticImage* p_staticimg = static_cast< CEGUI::StaticImage* >( CEGUI::WindowManager::getSingleton().createWindow( "TaharezLook/StaticImage", MAPVIEW_WND "image" ) );
        p_staticimg->setSize( CEGUI::Size( 1.0f, 1.0f ) );
        p_staticimg->setPosition( CEGUI::Point( 0.0f, 0.0f ) );
        p_staticimg->setBackgroundEnabled( false );
        p_staticimg->setFrameEnabled( false );
        p_staticimg->setAlpha( _alpha );
        // create a new imageset for map picture
        {
            CEGUI::Texture*  p_texture = yaf3d::GuiManager::get()->getGuiRenderer()->createTexture( _minMapFile, std::string( MAPVIEW_WND ) + _minMapFile );
            CEGUI::Imageset* p_imageSet = CEGUI::ImagesetManager::getSingleton().createImageset( std::string( MAPVIEW_WND ) + _minMapFile, p_texture );
            if ( !p_imageSet->isImageDefined( _minMapFile ) )
                p_imageSet->defineImage( std::string( MAPVIEW_WND ) + _minMapFile, CEGUI::Point( 0.0f, 0.0f ), CEGUI::Size( p_texture->getWidth(), p_texture->getHeight() ), CEGUI::Point( 0.0f,0.0f ) );

            CEGUI::Image* p_image = &const_cast< CEGUI::Image& >( p_imageSet->getImage( std::string( MAPVIEW_WND ) + _minMapFile ) );
            p_staticimg->setImage( p_image );
            _p_wnd->addChildWindow( p_staticimg );
        }

        // create a static text for displaying player name when mouse is over its point on map
        {
            _nameDisplay = static_cast< CEGUI::StaticText* >( CEGUI::WindowManager::getSingleton().createWindow( "TaharezLook/StaticText", MAPVIEW_WND "playername" ) );
            _nameDisplay->setMetricsMode( CEGUI::Absolute );
            _nameDisplay->setFrameEnabled( false );
            _nameDisplay->setBackgroundEnabled( false );
            _nameDisplay->setFont( YAF3D_GUI_FONT8 );
            _nameDisplay->setTextColours( CEGUI::colour( _nameDisplayColor.x(), _nameDisplayColor.y(), _nameDisplayColor.z() ) );
            _nameDisplay->setPosition( CEGUI::Point( _nameDisplayPos.x(), _nameDisplayPos.y() ) );
            _nameDisplay->setSize( CEGUI::Size( _nameDisplaySize.x(), _nameDisplaySize.y() ) );
            _nameDisplay->setAlwaysOnTop( true );

            _p_wnd->addChildWindow( _nameDisplay );
        }

        // image for marking a player on map
        _p_imgPlayerMarker = vrc::gameutils::GuiUtils::get()->getCustomImage( IMAGE_NAME_CROSSHAIR );

        vrc::gameutils::GuiUtils::get()->getMainGuiWindow()->addChildWindow( _p_wnd );

        // update the map
        updatePlayerList();
        updateMap();
    }
    catch ( const CEGUI::Exception& e )
    {
        log_error << "EnMapView: problem creating gui" << std::endl;
        log_out << "      reason: " << e.getMessage().c_str() << std::endl;
    }
}
Example #15
0
char *
inputLineHistSearch(char *prompt, char *def_str, int flag, Hist *hist,
		    int (*incrfunc) (int ch, Str str, Lineprop *prop))
{
    int opos, x, y, lpos, rpos, epos;
    unsigned char c;
    char *p;
#ifdef USE_M17N
    Str tmp;
#endif

    is_passwd = FALSE;
    move_word = TRUE;

    CurrentHist = hist;
    if (hist != NULL) {
	use_hist = TRUE;
	strCurrentBuf = NULL;
    }
    else {
	use_hist = FALSE;
    }
    if (flag & IN_URL) {
	cm_mode = CPL_ALWAYS | CPL_URL;
    }
    else if (flag & IN_FILENAME) {
	cm_mode = CPL_ALWAYS;
    }
    else if (flag & IN_PASSWORD) {
	cm_mode = CPL_NEVER;
	is_passwd = TRUE;
	move_word = FALSE;
    }
    else if (flag & IN_COMMAND)
	cm_mode = CPL_ON;
    else
	cm_mode = CPL_OFF;
    opos = get_strwidth(prompt);
    epos = CLEN - opos;
    if (epos < 0)
	epos = 0;
    lpos = epos / 3;
    rpos = epos * 2 / 3;
    offset = 0;

    if (def_str) {
	strBuf = Strnew_charp(def_str);
	CLen = CPos = setStrType(strBuf, strProp);
    }
    else {
	strBuf = Strnew();
	CLen = CPos = 0;
    }

#ifdef SUPPORT_WIN9X_CONSOLE_MBCS
    enable_win9x_console_input();
#endif
    i_cont = TRUE;
    i_broken = FALSE;
    i_quote = FALSE;
    cm_next = FALSE;
    cm_disp_next = -1;
    need_redraw = FALSE;

#ifdef USE_M17N
    wc_char_conv_init(wc_guess_8bit_charset(DisplayCharset), InnerCharset);
#endif
    do {
	x = calcPosition(strBuf->ptr, strProp, CLen, CPos, 0, CP_FORCE);
	if (x - rpos > offset) {
	    y = calcPosition(strBuf->ptr, strProp, CLen, CLen, 0, CP_AUTO);
	    if (y - epos > x - rpos)
		offset = x - rpos;
	    else if (y - epos > 0)
		offset = y - epos;
	}
	else if (x - lpos < offset) {
	    if (x - lpos > 0)
		offset = x - lpos;
	    else
		offset = 0;
	}
	move(LASTLINE, 0);
	addstr(prompt);
	if (is_passwd)
	    addPasswd(strBuf->ptr, strProp, CLen, offset, COLS - opos);
	else
	    addStr(strBuf->ptr, strProp, CLen, offset, COLS - opos);
	clrtoeolx();
	move(LASTLINE, opos + x - offset);
	refresh();

      next_char:
	c = getch();
#ifdef __EMX__
	if (c == 0) {
	    if (!(c = getcntrl()))
		goto next_char;
	}
#endif
	cm_clear = TRUE;
	cm_disp_clear = TRUE;
	if (!i_quote &&
	    (((cm_mode & CPL_ALWAYS) && (c == CTRL_I || c == ' ')) ||
	     ((cm_mode & CPL_ON) && (c == CTRL_I)))) {
	    if (emacs_like_lineedit && cm_next) {
		_dcompl();
		need_redraw = TRUE;
	    }
	    else {
		_compl();
		cm_disp_next = -1;
	    }
	}
	else if (!i_quote && CLen == CPos &&
		 (cm_mode & CPL_ALWAYS || cm_mode & CPL_ON) && c == CTRL_D) {
	    if (!emacs_like_lineedit) {
		_dcompl();
		need_redraw = TRUE;
	    }
	}
	else if (!i_quote && c == DEL_CODE) {
	    _bs();
	    cm_next = FALSE;
	    cm_disp_next = -1;
	}
	else if (!i_quote && c < 0x20) {	/* Control code */
	    if (incrfunc == NULL
		|| (c = incrfunc((int)c, strBuf, strProp)) < 0x20)
		(*InputKeymap[(int)c]) (c);
	    if (incrfunc && c != (unsigned char)-1 && c != CTRL_J)
		incrfunc(-1, strBuf, strProp);
	    if (cm_clear)
		cm_next = FALSE;
	    if (cm_disp_clear)
		cm_disp_next = -1;
	}
#ifdef USE_M17N
	else {
	    tmp = wc_char_conv(c);
	    if (tmp == NULL) {
		i_quote = TRUE;
		goto next_char;
	    }
	    i_quote = FALSE;
	    cm_next = FALSE;
	    cm_disp_next = -1;
	    if (CLen + tmp->length > STR_LEN || !tmp->length)
		goto next_char;
	    ins_char(tmp);
	    if (incrfunc)
		incrfunc(-1, strBuf, strProp);
	}
#else
	else {
	    i_quote = FALSE;
	    cm_next = FALSE;
	    cm_disp_next = -1;
	    if (CLen >= STR_LEN)
		goto next_char;
	    insC();
	    strBuf->ptr[CPos] = c;
	    if (!is_passwd && get_mctype(&c) == PC_CTRL)
		strProp[CPos] = PC_CTRL;
	    else
		strProp[CPos] = PC_ASCII;
	    CPos++;
	    if (incrfunc)
		incrfunc(-1, strBuf, strProp);
	}
#endif
	if (CLen && (flag & IN_CHAR))
	    break;
    } while (i_cont);
/** Points the camera towards the center of the simulated creature
*
**/
void Physics::pointCamera(){
	btVector3 aPoint = calcPosition();
	//setCameraPosition(btVector3(aPoint.x(),aPoint.y()-100,aPoint.z()-100));
	setCameraTargetPosition(aPoint);
	//setCameraDistance(30);
}
Example #17
0
void KasPopup::positionSelf()
{
    move(calcPosition(item_, width(), height()));
}
Example #18
0
  void
  GCells::addCells(double maxdiam)
  {
    list.clear();
    partCellData.clear();
    NCells = 1;

    for (size_t iDim = 0; iDim < NDIM; iDim++)
      {
	cellCount[iDim] = int(Sim->primaryCellSize[iDim] 
			      / (maxdiam * (1.0 + 10 * std::numeric_limits<double>::epsilon())));
      
	if (cellCount[iDim] < 2 * overlink + 1)
	  cellCount[iDim] = 2 * overlink + 1;
	
	NCells *= cellCount[iDim];
      
	dilatedCellMax[iDim] = cellCount[iDim] - 1;
	cellLatticeWidth[iDim] = Sim->primaryCellSize[iDim] / cellCount[iDim];
	cellDimension[iDim] = cellLatticeWidth[iDim] + (cellLatticeWidth[iDim] - maxdiam) 
	  * lambda;
	cellOffset[iDim] = -(cellLatticeWidth[iDim] - maxdiam) * lambda * 0.5;
      }

    if (getMaxSupportedInteractionLength() < maxdiam)
      M_throw() << "The system size is too small to support the range of interactions specified (i.e. the system is smaller than the interaction diameter of one particle).";

    //Find the required size of the morton array
    magnet::math::MortonNumber<3> coords(cellCount[0], cellCount[1], cellCount[2]);
    size_t sizeReq = coords.getMortonNum();

    list.resize(sizeReq); //Empty Cells created!

    dout << "Cells <x,y,z> " << cellCount[0] << ","
	 << cellCount[1] << "," << cellCount[2]
	 << "\nCell Offset "
	 << cellOffset[0] / Sim->units.unitLength() << ","
	 << cellOffset[1] / Sim->units.unitLength() << ","
	 << cellOffset[2] / Sim->units.unitLength()
	 << "\nCells Dimension " 
	 << cellDimension[0] / Sim->units.unitLength()
	 << ","
	 << cellDimension[1] / Sim->units.unitLength()
	 << "," 
	 << cellDimension[2] / Sim->units.unitLength()
	 << "\nLattice spacing " 
	 << cellLatticeWidth[0] / Sim->units.unitLength()
	 << ","
	 << cellLatticeWidth[1] / Sim->units.unitLength()
	 << "," 
	 << cellLatticeWidth[2] / Sim->units.unitLength()
	 << "\nRequested supported length " << maxdiam / Sim->units.unitLength()
	 << "\nSupported length           " << getMaxSupportedInteractionLength() / Sim->units.unitLength()
	 << "\nVector Size <N>  " << sizeReq << std::endl;
  
    //Add the particles section
    //Required so particles find the right owning cell
    Sim->dynamics->updateAllParticles();
  
    ////Add all the particles 
    BOOST_FOREACH(const size_t& id, *range)
      {
	Particle& p = Sim->particles[id];
	Sim->dynamics->updateParticle(p); 
	addToCell(id);
	if (verbose)
	  {
	    boost::unordered_map<size_t, size_t>::iterator it = partCellData.find(id);
	    magnet::math::MortonNumber<3> currentCell(it->second);
	    
	    magnet::math::MortonNumber<3> estCell(getCellID(Sim->particles[ID].getPosition()));
	  
	    Vector wrapped_pos = p.getPosition();
	    for (size_t n = 0; n < NDIM; ++n)
	      {
		wrapped_pos[n] -= Sim->primaryCellSize[n] *
		  lrint(wrapped_pos[n] / Sim->primaryCellSize[n]);
	      }
	    Vector origin_pos = wrapped_pos + 0.5 * Sim->primaryCellSize - cellOffset;

	    derr << "Added particle ID=" << p.getID() << " to cell <"
		 << currentCell[0].getRealValue() 
		 << "," << currentCell[1].getRealValue()
		 << "," << currentCell[2].getRealValue()
		 << ">"
		 << "\nParticle is at this distance " << Vector(p.getPosition() - calcPosition(it->second, p)).toString() << " from the cell origin"
		 << "\nParticle position  " << p.getPosition().toString()	
		 << "\nParticle wrapped distance  " << wrapped_pos.toString()	
		 << "\nParticle relative position  " << origin_pos.toString()
		 << "\nParticle cell number  " << Vector(origin_pos[0] / cellLatticeWidth[0],
							 origin_pos[1] / cellLatticeWidth[1],
							 origin_pos[2] / cellLatticeWidth[2]
							 ).toString()
		 << std::endl;
	  }
      }

    dout << "Cell loading " << float(partCellData.size()) / NCells 
	 << std::endl;
  }
/**
*	calculates Center of mass distance from its starting point
*/
float Physics::fitMove(){
	btVector3 tmpPos= calcPosition()-startPoint;

	return sqrt(tmpPos.getX()*tmpPos.getX()+tmpPos.getZ()*tmpPos.getZ());
}
Example #20
0
void MorphEffect::Render(Effect *effect, const SettingsMap &SettingsMap, RenderBuffer &buffer) {

    int start_x1 = SettingsMap.GetInt("SLIDER_Morph_Start_X1", 0);
    int start_y1 = SettingsMap.GetInt("SLIDER_Morph_Start_Y1", 0);
    int start_x2 = SettingsMap.GetInt("SLIDER_Morph_Start_X2", 0);
    int start_y2 = SettingsMap.GetInt("SLIDER_Morph_Start_Y2", 0);
    int end_x1 = SettingsMap.GetInt("SLIDER_Morph_End_X1", 0);
    int end_y1 = SettingsMap.GetInt("SLIDER_Morph_End_Y1", 0);
    int end_x2 = SettingsMap.GetInt("SLIDER_Morph_End_X2", 0);
    int end_y2 = SettingsMap.GetInt("SLIDER_Morph_End_Y2", 0);
    int start_length = SettingsMap.GetInt("SLIDER_MorphStartLength", 0);
    int end_length = SettingsMap.GetInt("SLIDER_MorphEndLength", 0);
    bool start_linked = SettingsMap.GetBool("CHECKBOX_Morph_Start_Link");
    bool end_linked = SettingsMap.GetBool("CHECKBOX_Morph_End_Link");
    int duration = SettingsMap.GetInt("SLIDER_MorphDuration", 0);
    int acceleration = SettingsMap.GetInt("SLIDER_MorphAccel", 0);
    bool showEntireHeadAtStart = SettingsMap.GetBool("CHECKBOX_ShowHeadAtStart");
    int repeat_count = SettingsMap.GetInt("SLIDER_Morph_Repeat_Count", 0);
    int repeat_skip = SettingsMap.GetInt("SLIDER_Morph_Repeat_Skip", 0);
    int stagger = SettingsMap.GetInt("SLIDER_Morph_Stagger", 0);

    double eff_pos = buffer.GetEffectTimeIntervalPosition();
    double step_size = 0.1;

    int hcols = 0, hcole = 1;
    int tcols = 2, tcole = 3;
    int num_tail_colors = 2;
    switch (buffer.palette.Size()) {
        case 1:  //one color selected, use it for all
            hcols = hcole = tcols = tcole = 0;
            break;
        case 2: //two colors, head/tail
            hcols = hcole = 0;
            tcols = tcole = 1;
            break;
        case 3: //three colors, head /tail start/end
            hcols = hcole = 0;
            tcols = 1;
            tcole = 2;
            break;
        case 4:
            break;
        case 5:
            num_tail_colors = 3;
            break;
        case 6:
            num_tail_colors = 4;
            break;
    }

    int x1a = calcPosition(start_x1, buffer.BufferWi);
    int y1a = calcPosition(start_y1, buffer.BufferHt);
    int x2a = calcPosition(end_x1, buffer.BufferWi);
    int y2a = calcPosition(end_y1, buffer.BufferHt);

    int x1b, x2b, y1b, y2b;

    if( start_linked )
    {
        x1b = x1a;
        y1b = y1a;
    }
    else
    {
        x1b = calcPosition(start_x2, buffer.BufferWi);
        y1b = calcPosition(start_y2, buffer.BufferHt);
    }

    if( end_linked )
    {
        x2b = x2a;
        y2b = y2a;
    }
    else
    {
        x2b = calcPosition(end_x2, buffer.BufferWi);
        y2b = calcPosition(end_y2, buffer.BufferHt);
    }

    xlColor head_color, tail_color, test_color;

    // compute direction
    int delta_xa = x2a - x1a;
    int delta_xb = x2b - x1b;
    int delta_ya = y2a - y1a;
    int delta_yb = y2b - y1b;
    int direction = delta_xa + delta_xb + delta_ya + delta_yb;
    int repeat_x = 0;
    int repeat_y = 0;
    double effect_pct = 1.0;
    double stagger_pct = 0.0;
    if( repeat_count > 0 )
    {
        if( (std::abs((float)delta_xa) + std::abs((float)delta_xb)) < (std::abs((float)delta_ya) + std::abs((float)delta_yb)) )
        {
            repeat_x = repeat_skip;
        }
        else
        {
            repeat_y = repeat_skip;
        }
        double stagger_val = (double)(std::abs((double)stagger))/200.0;
        effect_pct = 1.0 / (1 + stagger_val * repeat_count);
        stagger_pct = effect_pct * stagger_val;
    }

    std::vector<int> v_ax;
    std::vector<int> v_ay;
    std::vector<int> v_bx;
    std::vector<int> v_by;

    StoreLine(x1a, y1a, x2a, y2a, &v_ax, &v_ay);  // store side a
    StoreLine(x1b, y1b, x2b, y2b, &v_bx, &v_by);  // store side b

    int size_a = v_ax.size();
    int size_b = v_bx.size();

    std::vector<int> *v_lngx;  // pointer to longest vector x
    std::vector<int> *v_lngy;  // pointer to longest vector y
    std::vector<int> *v_shtx;  // pointer to shorter vector x
    std::vector<int> *v_shty;  // pointer to shorter vector y

    if( size_a > size_b )
    {
        v_lngx = &v_ax;
        v_lngy = &v_ay;
        v_shtx = &v_bx;
        v_shty = &v_by;
    }
    else
    {
        v_lngx = &v_bx;
        v_lngy = &v_by;
        v_shtx = &v_ax;
        v_shty = &v_ay;
    }

    double pos_a, pos_b;
    double total_tail_length, alpha_pct;
    double total_length = v_lngx->size();     // total length of longest vector
    double head_duration = duration/100.0;    // time the head is in the frame
    double head_end_of_head_pos = total_length + 1;
    double tail_end_of_head_pos = total_length + 1;
    double head_end_of_tail_pos = -1;
    double tail_end_of_tail_pos = -1;

    for( int repeat = 0; repeat <= repeat_count; repeat++ )
    {
        double eff_pos_adj = buffer.calcAccel(eff_pos, acceleration);
        double eff_start_pct = (stagger >= 0) ? stagger_pct*repeat : stagger_pct*(repeat_count-repeat);
        double eff_end_pct = eff_start_pct + effect_pct;
        eff_pos_adj = (eff_pos_adj - eff_start_pct) / (eff_end_pct - eff_start_pct);
        if( eff_pos_adj < 0.0 )
        {
            head_end_of_head_pos = -1;
            tail_end_of_head_pos = -1;
            head_end_of_tail_pos = -1;
            tail_end_of_tail_pos = -1;
            total_tail_length = 1.0;
            if( showEntireHeadAtStart )
            {
                head_end_of_head_pos = start_length;
            }
        }
        else
        {
            if( head_duration > 0.0 )
            {
                double head_loc_pct = eff_pos_adj / head_duration;
                head_end_of_head_pos = total_length * head_loc_pct;
                double current_total_head_length = end_length * head_loc_pct + start_length * (1.0 - head_loc_pct);  // adjusted head length excluding clipping
                head_end_of_head_pos += current_total_head_length * head_loc_pct * head_duration;
                total_tail_length = total_length * ( 1 / head_duration - 1.0);
                if( showEntireHeadAtStart )
                {
                    head_end_of_head_pos += current_total_head_length * (1.0 - eff_pos_adj);
                }
                tail_end_of_head_pos = head_end_of_head_pos - current_total_head_length;
                head_end_of_tail_pos = tail_end_of_head_pos - step_size;
                tail_end_of_tail_pos = head_end_of_tail_pos - total_tail_length;
                buffer.Get2ColorBlend(hcols, hcole, std::min( head_loc_pct, 1.0), head_color);
            }
            else
            {
                total_tail_length = total_length;
                head_end_of_tail_pos = total_length * 2 * eff_pos_adj;
                tail_end_of_tail_pos = head_end_of_tail_pos - total_tail_length;
            }
        }

        // draw the tail
        for( double i = std::min(head_end_of_tail_pos, total_length-1); i >= tail_end_of_tail_pos && i >= 0.0; i -= step_size )
        {
            double pct = ((total_length == 0) ? 0.0 : i / total_length);
            pos_a = i;
            pos_b = v_shtx->size() * pct;
            double tail_color_pct = (i-tail_end_of_tail_pos) / total_tail_length;
            if( num_tail_colors > 2 )
            {
                double color_index = ((double)num_tail_colors - 1.0) * (1.0 - tail_color_pct);
                tail_color_pct = color_index - (double)((int)color_index);
                tcols = (int)color_index + 2;
                tcole = tcols + 1;
                if( tcole == num_tail_colors+1 )
                {
                    alpha_pct = (1.0 - tail_color_pct);
                }
                else
                {
                    alpha_pct = 1.0;
                }
                buffer.Get2ColorBlend(tcols, tcole, tail_color_pct, tail_color);
            }
            else
            {
                if( tail_color_pct > 0.5 )
                {
                    alpha_pct = 1.0;
                }
                else
                {
                    alpha_pct = tail_color_pct / 0.5;
                }
                buffer.Get2ColorBlend(tcole, tcols, tail_color_pct, tail_color);
            }
            if( buffer.allowAlpha ) {
                tail_color.alpha = 255 * alpha_pct;
            }
            buffer.DrawThickLine( (*v_lngx)[pos_a]+(repeat_x*repeat), (*v_lngy)[pos_a]+(repeat_y*repeat), (*v_shtx)[pos_b]+(repeat_x*repeat), (*v_shty)[pos_b]+(repeat_y*repeat), tail_color, direction >= 0);
        }

        // draw the head
        for( double i = std::max(tail_end_of_head_pos, 0.0); i <= head_end_of_head_pos && i < total_length; i += step_size )
        {
            double pct = ((total_length == 0) ? 0.0 : i / total_length);
            pos_a = i;
            pos_b = v_shtx->size() * pct;
            buffer.DrawThickLine( (*v_lngx)[pos_a]+(repeat_x*repeat), (*v_lngy)[pos_a]+(repeat_y*repeat), (*v_shtx)[pos_b]+(repeat_x*repeat), (*v_shty)[pos_b]+(repeat_y*repeat), head_color, direction >= 0);
        }
    }
}
Example #21
0
  void 
  GCellsShearing::runEvent(Particle& part, const double) const
  {
    Sim->dynamics->updateParticle(part);

    size_t oldCell(partCellData[part.getID()]);
    magnet::math::MortonNumber<3> oldCellCoords(oldCell);
    Vector oldCellPosition(calcPosition(oldCellCoords));

    //Determine the cell transition direction, its saved
    int cellDirectionInt(Sim->dynamics->
			 getSquareCellCollision3(part, oldCellPosition, cellDimension));
  
    size_t cellDirection = abs(cellDirectionInt) - 1;

    magnet::math::MortonNumber<3> endCell = oldCellCoords; //The ID of the cell the particle enters

    if ((cellDirection == 1) &&
	(oldCellCoords[1] == ((cellDirectionInt < 0) ? 0 : (cellCount[1] - 1))))
      {
	//We're wrapping in the y direction, we have to compute
	//which cell its entering
	endCell[1] = (endCell[1].getRealValue() + cellCount[1] 
		      + ((cellDirectionInt < 0) ?  -1 : 1)) % cellCount[1];

	//Remove the old x contribution
	//Calculate the final x value
	//Time till transition, assumes the particle is up to date
	double dt = Sim->dynamics->getSquareCellCollision2(part, oldCellPosition, cellDimension);
     
	//Predict the position of the particle in the x dimension
	Sim->dynamics->advanceUpdateParticle(part, dt);
	Vector tmpPos = part.getPosition();
	//This rewinds the particle again
	Sim->dynamics->updateParticle(part);

	//Adding this extra half cell ensures we get into the next
	//simulation image, to calculate the position of the new cell
	tmpPos[1] += ((cellDirectionInt < 0) ? -0.5 : 0.5) * cellDimension[1];

	//Determine the x position (in cell coords) of the particle and
	//add it to the endCellID
	Sim->BCs->applyBC(tmpPos, dt);
      
	endCell[0] = getCellID(tmpPos)[0];

	removeFromCell(part.getID());
	addToCell(part.getID(), endCell.getMortonNum());
      
	//Get rid of the virtual event that is next, update is delayed till
	//after all events are added
	Sim->ptrScheduler->popNextEvent();

	//Check the entire neighbourhood, could check just the new
	//neighbours and the extra LE neighbourhood strip but its a lot
	//of code
	if (isUsedInScheduler)
	  {
	    BOOST_FOREACH(const size_t& id2, getParticleNeighbours(part))
	      {
		Sim->ptrScheduler->addInteractionEvent(part, id2);

		BOOST_FOREACH(const nbHoodSlot& nbs, sigNewNeighbourNotify)
		  nbs.second(part, id2);
	      }
	  }