Пример #1
0
void ofxWidget::mouseReleased(ofMouseEventArgs & mouse){
	this->mouse=mouse;
	yargs.relative_x=getRelativePosition(mouse.x,mouse.y).x;
	yargs.relative_y=getRelativePosition(mouse.x,mouse.y).y;
	yargs.abs_x = mouse.x;
	yargs.abs_y = mouse.y;
	newEvent(OFX_W_E_POINTER_RELEASED, yargs);
}
Пример #2
0
void ofxWidget::removeTuioCursor(TUIO::TuioCursor &tuioCursor){
	if(cursorsIn.find(tuioCursor.getSessionID())!=cursorsIn.end()){
		cursorsIn.erase(tuioCursor.getSessionID());
		yargs.relative_x=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).x;
		yargs.relative_y=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).y;
		yargs.abs_x=tuioCursor.getX();
		yargs.abs_y=tuioCursor.getY();
		newEvent(OFX_W_E_POINTER_RELEASED, yargs);
	}
}
Пример #3
0
void ofxWidget::mousePressed(ofMouseEventArgs & mouse){
	this->mouse=mouse;
	if(mouseIn()){
		yargs.relative_x=getRelativePosition(mouse.x,mouse.y).x;
		yargs.relative_y=getRelativePosition(mouse.x,mouse.y).y;
		yargs.abs_x = mouse.x;
		yargs.abs_y = mouse.y;
		newEvent(OFX_W_E_POINTER_PRESSED, yargs);
	}
}
Пример #4
0
void ofxWidget::addTuioCursor(TUIO::TuioCursor &tuioCursor){
	if(cursorIn(tuioCursor)){
		yargs.relative_x=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).x;
		yargs.relative_y=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).y;
		yargs.abs_x=tuioCursor.getX();
		yargs.abs_y=tuioCursor.getY();
		newEvent(OFX_W_E_POINTER_OVER, yargs);
		newEvent(OFX_W_E_POINTER_PRESSED, yargs);
		cursorsIn.insert(tuioCursor.getSessionID());
	}
}
Пример #5
0
int valueForPiecesPosition(BitMap * piecesPosition, int pieceType, int pieceColor, int phase){


	if ( piecesPosition == NULL ) {
		logChess(FATAL, "The position is null.");
		return ERROR_NULL_POSITION;
	}


	int retValue=0;
	int piecesPositionFound [8];

	int result=getPiecePosition(piecesPosition, pieceType, piecesPositionFound);
	if(result ==SUCCESS)//if not return SUCCESS the table is empty
	{
		int i;
		for(i=0; i < 8; i++)
		{
			if(piecesPositionFound[i] == -1 || piecesPositionFound[i] == -9)
				break;//exit from the loop if there's not more piece of these type

			int position=getRelativePosition(piecesPositionFound[i],pieceColor);
			retValue+=getValueForPosition(position,pieceType, phase);//here we sum every value of position for every piece
		}
	}

	return retValue;
}
Пример #6
0
void ofxWidget::updateTuioCursor(TUIO::TuioCursor &tuioCursor){
	if(cursorsIn.find(tuioCursor.getSessionID())==cursorsIn.end()) return;
	if(cursorIn(tuioCursor)){
		yargs.relative_x=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).x;
		yargs.relative_y=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).y;
		yargs.abs_x=tuioCursor.getX();
		yargs.abs_y=tuioCursor.getY();
		newEvent(OFX_W_E_POINTER_OVER, yargs);
	}else{
		yargs.relative_x=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).x;
		yargs.relative_y=getRelativePosition(tuioCursor.getX(),tuioCursor.getY()).y;
		yargs.abs_x=tuioCursor.getX();
		yargs.abs_y=tuioCursor.getY();
		newEvent(OFX_W_E_POINTER_OUT, yargs);
	};
}
Пример #7
0
void ofxWidget::mouseDragged(ofMouseEventArgs & mouse){
	this->mouse=mouse;
	if(mouseIn()){
		yargs.relative_x=getRelativePosition(mouse.x,mouse.y).x;
		yargs.relative_y=getRelativePosition(mouse.x,mouse.y).y;
		yargs.abs_x = mouse.x;
		yargs.abs_y = mouse.y;
		newEvent(OFX_W_E_POINTER_OVER, yargs);
	}else{
		yargs.relative_x=getRelativePosition(mouse.x,mouse.y).x;
		yargs.relative_y=getRelativePosition(mouse.x,mouse.y).y;
		yargs.abs_x = mouse.x;
		yargs.abs_y = mouse.y;
		newEvent(OFX_W_E_POINTER_OUT, yargs);
	}

}
        void Collision::onInit()
        {
          InternalMessage("Model","Collision::onInit entering") ;
          m_beam = NULL ;
          m_destroyable = NULL ;
          /*
            if one object is a laser beam
            - destroy it 
            and if the other is destroyable
            - manage damage 
          */
          LaserBeam* beam1 = getTrait()->getObject1()->getTrait<LaserBeam>() ;
          LaserBeam* beam2 = getTrait()->getObject2()->getTrait<LaserBeam>() ;
          
          Destroyable* destroyable1 = getTrait()->getObject1()->getTrait<Destroyable>() ;
          Destroyable* destroyable2 = getTrait()->getObject2()->getTrait<Destroyable>() ;
          
          if (beam1)
          {
            m_beam = beam1 ;
            getTrait()->getObject1()->destroyObject() ;
          }

          if (beam2)
          {
            m_beam = beam2 ;
            getTrait()->getObject2()->destroyObject() ;
          }
          
          if (destroyable1)
          {
            m_destroyable = destroyable1 ;
          }

          if (destroyable2)
          {
            m_destroyable = destroyable2 ;
          }
          
          // handle beam/destroyable collision
          if (m_beam && m_destroyable)
          {
            InternalMessage("Model","Collision::onInit damaging " + Kernel::toString(m_beam->getEnergy().Joule())) ;
            m_destroyable->damage(m_beam->getEnergy()) ;
            Kernel::Object* hit = m_destroyable->getObject()->createObject() ;
            hit->addTrait(new Hit()) ;
            Position position(getRelativePosition(getObject(),m_destroyable->getObject())) ;

            InternalMessage("Model","Collision::onInit creating hit at " + ::Ogre::StringConverter::toString(position.Meter())) ;

            hit->addTrait(new Positioned(position)) ;
            hit->addTrait(new WithLifetime(Duration::Second(0))) ;
            hit->addTrait(new Sized(Distance(Distance::_Meter,60))) ;
            hit->addTrait(new Oriented(Orientation(position))) ;
          }          
          
          InternalMessage("Model","Collision::onInit leaving") ;
        }
Пример #9
0
void eWidget::clear()
{
#if 0
	eWidget *root=this;
	while (root->parent)
		root=root->parent;
	eRect me(getRelativePosition(root), size);
	root->invalidate(me);
#endif
	invalidate(eRect(), 1);
}
Пример #10
0
void BitString::setString( const BitString & i_sStr, uint32_t i_sPos,
                           uint32_t i_sLen, uint32_t i_dPos )
{
    // Ensure the source parameters are valid.
    PRDF_ASSERT( nullptr != i_sStr.getBufAddr() );
    PRDF_ASSERT( 0 < i_sLen ); // at least one bit to copy
    PRDF_ASSERT( i_sPos + i_sLen <= i_sStr.getBitLen() );

    // Ensure the destination has at least one bit available to copy.
    PRDF_ASSERT( nullptr != getBufAddr() );
    PRDF_ASSERT( i_dPos < getBitLen() );

    // If the source length is greater than the destination length than the
    // extra source bits are ignored.
    uint32_t actLen = std::min( i_sLen, getBitLen() - i_dPos );

    // The bit strings may be in overlapping memory spaces. So we need to copy
    // the data in the correct direction to prevent overlapping.
    uint32_t sRelOffset = 0, dRelOffset = 0;
    CPU_WORD * sRelAddr = i_sStr.getRelativePosition( sRelOffset, i_sPos );
    CPU_WORD * dRelAddr =        getRelativePosition( dRelOffset, i_dPos );

    // Copy the data.
    if ( (dRelAddr == sRelAddr) && (dRelOffset == sRelOffset) )
    {
        // Do nothing. The source and destination are the same.
    }
    else if ( (dRelAddr < sRelAddr) ||
              ((dRelAddr == sRelAddr) && (dRelOffset < sRelOffset)) )
    {
        // Copy the data forward.
        for ( uint32_t pos = 0; pos < actLen; pos += CPU_WORD_BIT_LEN )
        {
            uint32_t len = std::min( actLen - pos, CPU_WORD_BIT_LEN );

            CPU_WORD value = i_sStr.getField( i_sPos + pos, len );
            setField( i_dPos + pos, len, value );
        }
    }
    else // Copy the data backwards.
    {
        // Get the first position of the last chunk (CPU_WORD aligned).
        uint32_t lastPos = ((actLen-1) / CPU_WORD_BIT_LEN) * CPU_WORD_BIT_LEN;

        // Start with the last chunk and work backwards.
        for ( int32_t pos = lastPos; 0 <= pos; pos -= CPU_WORD_BIT_LEN )
        {
            uint32_t len = std::min( actLen - pos, CPU_WORD_BIT_LEN );

            CPU_WORD value = i_sStr.getField( i_sPos + pos, len );
            setField( i_dPos + pos, len, value );
        }
    }
}
Пример #11
0
void WindModificator::createBody (const b2Vec2 &pos, float shift)
{
	if (!_bodies.empty())
		return;

	_shift = shift;

	float angle;
	switch (_direction) {
	case DIRECTION_UP:
		angle = 270.0f;
		break;
	case DIRECTION_LEFT:
		angle = 180.0f;
		break;
	case DIRECTION_DOWN:
		angle = 90.0f;
		break;
	default:
		angle = 0.0f;
		break;
	}

	b2BodyDef bodyDef;
	bodyDef.type = b2_staticBody;
	b2Vec2 modPos = pos;
	getRelativePosition(modPos);
	bodyDef.position.Set(modPos.x, modPos.y);
	bodyDef.angle = DegreesToRadians(angle);
	bodyDef.fixedRotation = true;

	// counterclock wise - starting at upper left
	b2Vec2 vertices[4];
	const float x1 = 0.5f;
	const float x2 = x1 / _beginSizeDivisor;
	vertices[0].Set(0.0f, -x2);
	vertices[1].Set(0.0f, x2);
	vertices[2].Set(_modificatorSize, x1);
	vertices[3].Set(_modificatorSize, -x1);

	b2PolygonShape shape;
	shape.Set(vertices, SDL_arraysize(vertices));

	b2FixtureDef fixtureDef;
	fixtureDef.shape = &shape;
	fixtureDef.density = DENSITY_AIR;

	b2Body* body = _map.getWorld()->CreateBody(&bodyDef);
	body->SetUserData((void*) this);
	body->CreateFixture(&fixtureDef);
	addBody(body);
}
Пример #12
0
bool
XFEMGeometricCut3D::cutElementByGeometry(const Elem* elem,
                                         std::vector<CutFace> & cut_faces,
                                         Real /*time*/)
//TODO: Time evolving cuts not yet supported in 3D (hence the lack of use of the time variable)
{
  bool cut_elem = false;

  for (unsigned int i = 0; i < elem->n_sides(); ++i)
  {
    // This returns the lowest-order type of side.
    UniquePtr<Elem> curr_side = elem->side(i);
    if (curr_side->dim() != 2)
      mooseError("In cutElementByGeometry dimension of side must be 2, but it is " << curr_side->dim());
    unsigned int n_edges = curr_side->n_sides();

    std::vector<unsigned int> cut_edges;
    std::vector<Real> cut_pos;

    for (unsigned int j = 0; j < n_edges; j++)
    {
      // This returns the lowest-order type of side.
      UniquePtr<Elem> curr_edge = curr_side->side(j);
      if (curr_edge->type() != EDGE2)
        mooseError("In cutElementByGeometry face edge must be EDGE2, but type is: " << libMesh::Utility::enum_to_string(curr_edge->type())
                   << " base element type is: " << libMesh::Utility::enum_to_string(elem->type()));
      Node * node1 = curr_edge->get_node(0);
      Node * node2 = curr_edge->get_node(1);

      Point intersection;
      if (intersectWithEdge(*node1, *node2, intersection))
      {
        cut_edges.push_back(j);
        cut_pos.push_back(getRelativePosition(*node1, *node2, intersection));
      }
    }

    if (cut_edges.size() == 2)
    {
      cut_elem = true;
      CutFace mycut;
      mycut.face_id = i;
      mycut.face_edge.push_back(cut_edges[0]);
      mycut.face_edge.push_back(cut_edges[1]);
      mycut.position.push_back(cut_pos[0]);
      mycut.position.push_back(cut_pos[1]);
      cut_faces.push_back(mycut);
    }
  }

  return cut_elem;
}
Пример #13
0
	void CSObject::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options)
	{
		out->addInt(		"Id",				getId());
		out->addString(		"Name",				getName().c_str());
		out->addBool(		"Dead",				getDead());
		out->addBool(		"DebugObject",		getDebugObject());
		out->addVector3d(	"Position",			getRelativePosition());
		out->addVector3d(	"PositionOffset",	getPositionOffset());
		out->addVector3d(	"Rotation",			getRelativeRotation());
		out->addVector3d(	"RotationOffset",	getRotationOffset());
		out->addVector3d(	"Scale",			getRelativeScale());
		out->addVector3d(	"ScaleOffset",		getScaleOffset());
		out->addVector3d(	"BBOffset",			getBBOffset());
		out->addBool(		"Shadow",			getShadow());
		out->addString(		"ActorFileName",	getActorFileName().c_str());
		out->addString(		"TextureFileName",	getTextureFileName().c_str());
	}
void IGUIElement::update()
{
	//this->setSize(getSize());

	/*core::vectoru32 tmp = get;

	if(mParent)
		tmp += mParent->getPosition();

	mBound = core::rectu32(tmp, mBound.getSize() + tmp);

	if(mParent) 
	*/
	this->setPosition(getRelativePosition());

	//mController->update(this);
}
Пример #15
0
void drawCandlestick(SubWin sw,int x, float lowprice, float highprice, DayData data){

	//start postion for rectangle. it will be drawn from start to right down corner 
	int startx = x;
	int starty;

	//length of shadow line; hl mean up shadow line, ll mean down shadow line
	int hl, ll;
	float yunit = (highprice - lowprice)/sw->height;
	int length;
	Uint32 color;
	//get the abs value of the candle
	data->start > data->end ? (starty  = data->start, color = GREEN
	):(starty = data->end,color = RED); 
	length = data->start - data->end;
	if(length<0){
		length*=(-1);
	}
	printf("length = %d \n", length);

	//switch to the relative value
	hl = (int)((data->highest - starty)/yunit);
	ll = (int)((starty -length - data->lowest)/yunit);
	length = (int) (length/yunit);

	printf("length = %d pix\n", length);
	if(length <1){
		length = 1;
	}
	getRelativePosition(sw,&startx,&starty, lowprice, highprice);

	//draw
	Draw_Rect(sw->screen,startx,starty,10,length,color);

	Draw_Line(sw->screen,startx+5,starty,startx+5, starty - hl,color);
	Draw_Line(sw->screen,startx+5,starty+length,startx+5, starty+length+ll,color);
}
Пример #16
0
static void layoutNodeImpl(css_node_t *node, float parentMaxWidth, css_direction_t parentDirection) {
  /** START_GENERATED **/
  css_direction_t direction = resolveDirection(node, parentDirection);
  css_flex_direction_t mainAxis = resolveAxis(getFlexDirection(node), direction);
  css_flex_direction_t crossAxis = getCrossFlexDirection(mainAxis, direction);
  css_flex_direction_t resolvedRowAxis = resolveAxis(CSS_FLEX_DIRECTION_ROW, direction);

  // Handle width and height style attributes
  setDimensionFromStyle(node, mainAxis);
  setDimensionFromStyle(node, crossAxis);

  // Set the resolved resolution in the node's layout
  node->layout.direction = direction;

  // The position is set by the parent, but we need to complete it with a
  // delta composed of the margin and left/top/right/bottom
  node->layout.position[leading[mainAxis]] += getLeadingMargin(node, mainAxis) +
    getRelativePosition(node, mainAxis);
  node->layout.position[trailing[mainAxis]] += getTrailingMargin(node, mainAxis) +
    getRelativePosition(node, mainAxis);
  node->layout.position[leading[crossAxis]] += getLeadingMargin(node, crossAxis) +
    getRelativePosition(node, crossAxis);
  node->layout.position[trailing[crossAxis]] += getTrailingMargin(node, crossAxis) +
    getRelativePosition(node, crossAxis);

  // Inline immutable values from the target node to avoid excessive method
  // invocations during the layout calculation.
  int childCount = node->children_count;
  float paddingAndBorderAxisResolvedRow = getPaddingAndBorderAxis(node, resolvedRowAxis);

  if (isMeasureDefined(node)) {
    bool isResolvedRowDimDefined = !isUndefined(node->layout.dimensions[dim[resolvedRowAxis]]);

    float width = CSS_UNDEFINED;
    if (isDimDefined(node, resolvedRowAxis)) {
      width = node->style.dimensions[CSS_WIDTH];
    } else if (isResolvedRowDimDefined) {
      width = node->layout.dimensions[dim[resolvedRowAxis]];
    } else {
      width = parentMaxWidth -
        getMarginAxis(node, resolvedRowAxis);
    }
    width -= paddingAndBorderAxisResolvedRow;

    // We only need to give a dimension for the text if we haven't got any
    // for it computed yet. It can either be from the style attribute or because
    // the element is flexible.
    bool isRowUndefined = !isDimDefined(node, resolvedRowAxis) && !isResolvedRowDimDefined;
    bool isColumnUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_COLUMN) &&
      isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]]);

    // Let's not measure the text if we already know both dimensions
    if (isRowUndefined || isColumnUndefined) {
      css_dim_t measureDim = node->measure(
        node->context,

        width
      );
      if (isRowUndefined) {
        node->layout.dimensions[CSS_WIDTH] = measureDim.dimensions[CSS_WIDTH] +
          paddingAndBorderAxisResolvedRow;
      }
      if (isColumnUndefined) {
        node->layout.dimensions[CSS_HEIGHT] = measureDim.dimensions[CSS_HEIGHT] +
          getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_COLUMN);
      }
    }
    if (childCount == 0) {
      return;
    }
  }

  bool isNodeFlexWrap = isFlexWrap(node);

  css_justify_t justifyContent = node->style.justify_content;

  float leadingPaddingAndBorderMain = getLeadingPaddingAndBorder(node, mainAxis);
  float leadingPaddingAndBorderCross = getLeadingPaddingAndBorder(node, crossAxis);
  float paddingAndBorderAxisMain = getPaddingAndBorderAxis(node, mainAxis);
  float paddingAndBorderAxisCross = getPaddingAndBorderAxis(node, crossAxis);

  bool isMainDimDefined = !isUndefined(node->layout.dimensions[dim[mainAxis]]);
  bool isCrossDimDefined = !isUndefined(node->layout.dimensions[dim[crossAxis]]);
  bool isMainRowDirection = isRowDirection(mainAxis);

  int i;
  int ii;
  css_node_t* child;
  css_flex_direction_t axis;

  css_node_t* firstAbsoluteChild = NULL;
  css_node_t* currentAbsoluteChild = NULL;

  float definedMainDim = CSS_UNDEFINED;
  if (isMainDimDefined) {
    definedMainDim = node->layout.dimensions[dim[mainAxis]] - paddingAndBorderAxisMain;
  }

  // We want to execute the next two loops one per line with flex-wrap
  int startLine = 0;
  int endLine = 0;
  // int nextOffset = 0;
  int alreadyComputedNextLayout = 0;
  // We aggregate the total dimensions of the container in those two variables
  float linesCrossDim = 0;
  float linesMainDim = 0;
  int linesCount = 0;
  while (endLine < childCount) {
    // <Loop A> Layout non flexible children and count children by type

    // mainContentDim is accumulation of the dimensions and margin of all the
    // non flexible children. This will be used in order to either set the
    // dimensions of the node if none already exist, or to compute the
    // remaining space left for the flexible children.
    float mainContentDim = 0;

    // There are three kind of children, non flexible, flexible and absolute.
    // We need to know how many there are in order to distribute the space.
    int flexibleChildrenCount = 0;
    float totalFlexible = 0;
    int nonFlexibleChildrenCount = 0;

    // Use the line loop to position children in the main axis for as long
    // as they are using a simple stacking behaviour. Children that are
    // immediately stacked in the initial loop will not be touched again
    // in <Loop C>.
    bool isSimpleStackMain =
        (isMainDimDefined && justifyContent == CSS_JUSTIFY_FLEX_START) ||
        (!isMainDimDefined && justifyContent != CSS_JUSTIFY_CENTER);
    int firstComplexMain = (isSimpleStackMain ? childCount : startLine);

    // Use the initial line loop to position children in the cross axis for
    // as long as they are relatively positioned with alignment STRETCH or
    // FLEX_START. Children that are immediately stacked in the initial loop
    // will not be touched again in <Loop D>.
    bool isSimpleStackCross = true;
    int firstComplexCross = childCount;

    css_node_t* firstFlexChild = NULL;
    css_node_t* currentFlexChild = NULL;

    float mainDim = leadingPaddingAndBorderMain;
    float crossDim = 0;

    float maxWidth;
    for (i = startLine; i < childCount; ++i) {
      child = node->get_child(node->context, i);
      child->line_index = linesCount;

      child->next_absolute_child = NULL;
      child->next_flex_child = NULL;

      css_align_t alignItem = getAlignItem(node, child);

      // Pre-fill cross axis dimensions when the child is using stretch before
      // we call the recursive layout pass
      if (alignItem == CSS_ALIGN_STRETCH &&
          child->style.position_type == CSS_POSITION_RELATIVE &&
          isCrossDimDefined &&
          !isDimDefined(child, crossAxis)) {
        child->layout.dimensions[dim[crossAxis]] = fmaxf(
          boundAxis(child, crossAxis, node->layout.dimensions[dim[crossAxis]] -
            paddingAndBorderAxisCross - getMarginAxis(child, crossAxis)),
          // You never want to go smaller than padding
          getPaddingAndBorderAxis(child, crossAxis)
        );
      } else if (child->style.position_type == CSS_POSITION_ABSOLUTE) {
        // Store a private linked list of absolutely positioned children
        // so that we can efficiently traverse them later.
        if (firstAbsoluteChild == NULL) {
          firstAbsoluteChild = child;
        }
        if (currentAbsoluteChild != NULL) {
          currentAbsoluteChild->next_absolute_child = child;
        }
        currentAbsoluteChild = child;

        // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
        // left and right or top and bottom).
        for (ii = 0; ii < 2; ii++) {
          axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
          if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
              !isDimDefined(child, axis) &&
              isPosDefined(child, leading[axis]) &&
              isPosDefined(child, trailing[axis])) {
            child->layout.dimensions[dim[axis]] = fmaxf(
              boundAxis(child, axis, node->layout.dimensions[dim[axis]] -
                getPaddingAndBorderAxis(node, axis) -
                getMarginAxis(child, axis) -
                getPosition(child, leading[axis]) -
                getPosition(child, trailing[axis])),
              // You never want to go smaller than padding
              getPaddingAndBorderAxis(child, axis)
            );
          }
        }
      }

      float nextContentDim = 0;

      // It only makes sense to consider a child flexible if we have a computed
      // dimension for the node->
      if (isMainDimDefined && isFlex(child)) {
        flexibleChildrenCount++;
        totalFlexible += child->style.flex;

        // Store a private linked list of flexible children so that we can
        // efficiently traverse them later.
        if (firstFlexChild == NULL) {
          firstFlexChild = child;
        }
        if (currentFlexChild != NULL) {
          currentFlexChild->next_flex_child = child;
        }
        currentFlexChild = child;

        // Even if we don't know its exact size yet, we already know the padding,
        // border and margin. We'll use this partial information, which represents
        // the smallest possible size for the child, to compute the remaining
        // available space.
        nextContentDim = getPaddingAndBorderAxis(child, mainAxis) +
          getMarginAxis(child, mainAxis);

      } else {
        maxWidth = CSS_UNDEFINED;
        if (!isMainRowDirection) {
          if (isDimDefined(node, resolvedRowAxis)) {
            maxWidth = node->layout.dimensions[dim[resolvedRowAxis]] -
              paddingAndBorderAxisResolvedRow;
          } else {
            maxWidth = parentMaxWidth -
              getMarginAxis(node, resolvedRowAxis) -
              paddingAndBorderAxisResolvedRow;
          }
        }

        // This is the main recursive call. We layout non flexible children.
        if (alreadyComputedNextLayout == 0) {
          layoutNode(child, maxWidth, direction);
        }

        // Absolute positioned elements do not take part of the layout, so we
        // don't use them to compute mainContentDim
        if (child->style.position_type == CSS_POSITION_RELATIVE) {
          nonFlexibleChildrenCount++;
          // At this point we know the final size and margin of the element.
          nextContentDim = getDimWithMargin(child, mainAxis);
        }
      }

      // The element we are about to add would make us go to the next line
      if (isNodeFlexWrap &&
          isMainDimDefined &&
          mainContentDim + nextContentDim > definedMainDim &&
          // If there's only one element, then it's bigger than the content
          // and needs its own line
          i != startLine) {
        nonFlexibleChildrenCount--;
        alreadyComputedNextLayout = 1;
        break;
      }

      // Disable simple stacking in the main axis for the current line as
      // we found a non-trivial child-> The remaining children will be laid out
      // in <Loop C>.
      if (isSimpleStackMain &&
          (child->style.position_type != CSS_POSITION_RELATIVE || isFlex(child))) {
        isSimpleStackMain = false;
        firstComplexMain = i;
      }

      // Disable simple stacking in the cross axis for the current line as
      // we found a non-trivial child-> The remaining children will be laid out
      // in <Loop D>.
      if (isSimpleStackCross &&
          (child->style.position_type != CSS_POSITION_RELATIVE ||
              (alignItem != CSS_ALIGN_STRETCH && alignItem != CSS_ALIGN_FLEX_START) ||
              isUndefined(child->layout.dimensions[dim[crossAxis]]))) {
        isSimpleStackCross = false;
        firstComplexCross = i;
      }

      if (isSimpleStackMain) {
        child->layout.position[pos[mainAxis]] += mainDim;
        if (isMainDimDefined) {
          setTrailingPosition(node, child, mainAxis);
        }

        mainDim += getDimWithMargin(child, mainAxis);
        crossDim = fmaxf(crossDim, boundAxis(child, crossAxis, getDimWithMargin(child, crossAxis)));
      }

      if (isSimpleStackCross) {
        child->layout.position[pos[crossAxis]] += linesCrossDim + leadingPaddingAndBorderCross;
        if (isCrossDimDefined) {
          setTrailingPosition(node, child, crossAxis);
        }
      }

      alreadyComputedNextLayout = 0;
      mainContentDim += nextContentDim;
      endLine = i + 1;
    }

    // <Loop B> Layout flexible children and allocate empty space

    // In order to position the elements in the main axis, we have two
    // controls. The space between the beginning and the first element
    // and the space between each two elements.
    float leadingMainDim = 0;
    float betweenMainDim = 0;

    // The remaining available space that needs to be allocated
    float remainingMainDim = 0;
    if (isMainDimDefined) {
      remainingMainDim = definedMainDim - mainContentDim;
    } else {
      remainingMainDim = fmaxf(mainContentDim, 0) - mainContentDim;
    }

    // If there are flexible children in the mix, they are going to fill the
    // remaining space
    if (flexibleChildrenCount != 0) {
      float flexibleMainDim = remainingMainDim / totalFlexible;
      float baseMainDim;
      float boundMainDim;

      // If the flex share of remaining space doesn't meet min/max bounds,
      // remove this child from flex calculations.
      currentFlexChild = firstFlexChild;
      while (currentFlexChild != NULL) {
        baseMainDim = flexibleMainDim * currentFlexChild->style.flex +
            getPaddingAndBorderAxis(currentFlexChild, mainAxis);
        boundMainDim = boundAxis(currentFlexChild, mainAxis, baseMainDim);

        if (baseMainDim != boundMainDim) {
          remainingMainDim -= boundMainDim;
          totalFlexible -= currentFlexChild->style.flex;
        }

        currentFlexChild = currentFlexChild->next_flex_child;
      }
      flexibleMainDim = remainingMainDim / totalFlexible;

      // The non flexible children can overflow the container, in this case
      // we should just assume that there is no space available.
      if (flexibleMainDim < 0) {
        flexibleMainDim = 0;
      }

      currentFlexChild = firstFlexChild;
      while (currentFlexChild != NULL) {
        // At this point we know the final size of the element in the main
        // dimension
        currentFlexChild->layout.dimensions[dim[mainAxis]] = boundAxis(currentFlexChild, mainAxis,
          flexibleMainDim * currentFlexChild->style.flex +
              getPaddingAndBorderAxis(currentFlexChild, mainAxis)
        );

        maxWidth = CSS_UNDEFINED;
        if (isDimDefined(node, resolvedRowAxis)) {
          maxWidth = node->layout.dimensions[dim[resolvedRowAxis]] -
            paddingAndBorderAxisResolvedRow;
        } else if (!isMainRowDirection) {
          maxWidth = parentMaxWidth -
            getMarginAxis(node, resolvedRowAxis) -
            paddingAndBorderAxisResolvedRow;
        }

        // And we recursively call the layout algorithm for this child
        layoutNode(currentFlexChild, maxWidth, direction);

        child = currentFlexChild;
        currentFlexChild = currentFlexChild->next_flex_child;
        child->next_flex_child = NULL;
      }

    // We use justifyContent to figure out how to allocate the remaining
    // space available
    } else if (justifyContent != CSS_JUSTIFY_FLEX_START) {
      if (justifyContent == CSS_JUSTIFY_CENTER) {
        leadingMainDim = remainingMainDim / 2;
      } else if (justifyContent == CSS_JUSTIFY_FLEX_END) {
        leadingMainDim = remainingMainDim;
      } else if (justifyContent == CSS_JUSTIFY_SPACE_BETWEEN) {
        remainingMainDim = fmaxf(remainingMainDim, 0);
        if (flexibleChildrenCount + nonFlexibleChildrenCount - 1 != 0) {
          betweenMainDim = remainingMainDim /
            (flexibleChildrenCount + nonFlexibleChildrenCount - 1);
        } else {
          betweenMainDim = 0;
        }
      } else if (justifyContent == CSS_JUSTIFY_SPACE_AROUND) {
        // Space on the edges is half of the space between elements
        betweenMainDim = remainingMainDim /
          (flexibleChildrenCount + nonFlexibleChildrenCount);
        leadingMainDim = betweenMainDim / 2;
      }
    }

    // <Loop C> Position elements in the main axis and compute dimensions

    // At this point, all the children have their dimensions set. We need to
    // find their position. In order to do that, we accumulate data in
    // variables that are also useful to compute the total dimensions of the
    // container!
    mainDim += leadingMainDim;

    for (i = firstComplexMain; i < endLine; ++i) {
      child = node->get_child(node->context, i);

      if (child->style.position_type == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[mainAxis])) {
        // In case the child is position absolute and has left/top being
        // defined, we override the position to whatever the user said
        // (and margin/border).
        child->layout.position[pos[mainAxis]] = getPosition(child, leading[mainAxis]) +
          getLeadingBorder(node, mainAxis) +
          getLeadingMargin(child, mainAxis);
      } else {
        // If the child is position absolute (without top/left) or relative,
        // we put it at the current accumulated offset.
        child->layout.position[pos[mainAxis]] += mainDim;

        // Define the trailing position accordingly.
        if (isMainDimDefined) {
          setTrailingPosition(node, child, mainAxis);
        }

        // Now that we placed the element, we need to update the variables
        // We only need to do that for relative elements. Absolute elements
        // do not take part in that phase.
        if (child->style.position_type == CSS_POSITION_RELATIVE) {
          // The main dimension is the sum of all the elements dimension plus
          // the spacing.
          mainDim += betweenMainDim + getDimWithMargin(child, mainAxis);
          // The cross dimension is the max of the elements dimension since there
          // can only be one element in that cross dimension.
          crossDim = fmaxf(crossDim, boundAxis(child, crossAxis, getDimWithMargin(child, crossAxis)));
        }
      }
    }

    float containerCrossAxis = node->layout.dimensions[dim[crossAxis]];
    if (!isCrossDimDefined) {
      containerCrossAxis = fmaxf(
        // For the cross dim, we add both sides at the end because the value
        // is aggregate via a max function. Intermediate negative values
        // can mess this computation otherwise
        boundAxis(node, crossAxis, crossDim + paddingAndBorderAxisCross),
        paddingAndBorderAxisCross
      );
    }

    // <Loop D> Position elements in the cross axis
    for (i = firstComplexCross; i < endLine; ++i) {
      child = node->get_child(node->context, i);

      if (child->style.position_type == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[crossAxis])) {
        // In case the child is absolutely positionned and has a
        // top/left/bottom/right being set, we override all the previously
        // computed positions to set it correctly.
        child->layout.position[pos[crossAxis]] = getPosition(child, leading[crossAxis]) +
          getLeadingBorder(node, crossAxis) +
          getLeadingMargin(child, crossAxis);

      } else {
        float leadingCrossDim = leadingPaddingAndBorderCross;

        // For a relative children, we're either using alignItems (parent) or
        // alignSelf (child) in order to determine the position in the cross axis
        if (child->style.position_type == CSS_POSITION_RELATIVE) {
          css_align_t alignItem = getAlignItem(node, child);
          if (alignItem == CSS_ALIGN_STRETCH) {
            // You can only stretch if the dimension has not already been set
            // previously.
            if (!isDimDefined(child, crossAxis)) {
              child->layout.dimensions[dim[crossAxis]] = fmaxf(
                boundAxis(child, crossAxis, containerCrossAxis -
                  paddingAndBorderAxisCross - getMarginAxis(child, crossAxis)),
                // You never want to go smaller than padding
                getPaddingAndBorderAxis(child, crossAxis)
              );
            }
          } else if (alignItem != CSS_ALIGN_FLEX_START) {
            // The remaining space between the parent dimensions+padding and child
            // dimensions+margin.
            float remainingCrossDim = containerCrossAxis -
              paddingAndBorderAxisCross - getDimWithMargin(child, crossAxis);

            if (alignItem == CSS_ALIGN_CENTER) {
              leadingCrossDim += remainingCrossDim / 2;
            } else { // CSS_ALIGN_FLEX_END
              leadingCrossDim += remainingCrossDim;
            }
          }
        }

        // And we apply the position
        child->layout.position[pos[crossAxis]] += linesCrossDim + leadingCrossDim;

        // Define the trailing position accordingly.
        if (isCrossDimDefined) {
          setTrailingPosition(node, child, crossAxis);
        }
      }
    }

    linesCrossDim += crossDim;
    linesMainDim = fmaxf(linesMainDim, mainDim);
    linesCount += 1;
    startLine = endLine;
  }

  // <Loop E>
  //
  // Note(prenaux): More than one line, we need to layout the crossAxis
  // according to alignContent.
  //
  // Note that we could probably remove <Loop D> and handle the one line case
  // here too, but for the moment this is safer since it won't interfere with
  // previously working code.
  //
  // See specs:
  // http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#layout-algorithm
  // section 9.4
  //
  if (linesCount > 1 && isCrossDimDefined) {
    float nodeCrossAxisInnerSize = node->layout.dimensions[dim[crossAxis]] -
        paddingAndBorderAxisCross;
    float remainingAlignContentDim = nodeCrossAxisInnerSize - linesCrossDim;

    float crossDimLead = 0;
    float currentLead = leadingPaddingAndBorderCross;

    css_align_t alignContent = node->style.align_content;
    if (alignContent == CSS_ALIGN_FLEX_END) {
      currentLead += remainingAlignContentDim;
    } else if (alignContent == CSS_ALIGN_CENTER) {
      currentLead += remainingAlignContentDim / 2;
    } else if (alignContent == CSS_ALIGN_STRETCH) {
      if (nodeCrossAxisInnerSize > linesCrossDim) {
        crossDimLead = (remainingAlignContentDim / linesCount);
      }
    }

    int endIndex = 0;
    for (i = 0; i < linesCount; ++i) {
      int startIndex = endIndex;

      // compute the line's height and find the endIndex
      float lineHeight = 0;
      for (ii = startIndex; ii < childCount; ++ii) {
        child = node->get_child(node->context, ii);
        if (child->style.position_type != CSS_POSITION_RELATIVE) {
          continue;
        }
        if (child->line_index != i) {
          break;
        }
        if (!isUndefined(child->layout.dimensions[dim[crossAxis]])) {
          lineHeight = fmaxf(
            lineHeight,
            child->layout.dimensions[dim[crossAxis]] + getMarginAxis(child, crossAxis)
          );
        }
      }
      endIndex = ii;
      lineHeight += crossDimLead;

      for (ii = startIndex; ii < endIndex; ++ii) {
        child = node->get_child(node->context, ii);
        if (child->style.position_type != CSS_POSITION_RELATIVE) {
          continue;
        }

        css_align_t alignContentAlignItem = getAlignItem(node, child);
        if (alignContentAlignItem == CSS_ALIGN_FLEX_START) {
          child->layout.position[pos[crossAxis]] = currentLead + getLeadingMargin(child, crossAxis);
        } else if (alignContentAlignItem == CSS_ALIGN_FLEX_END) {
          child->layout.position[pos[crossAxis]] = currentLead + lineHeight - getTrailingMargin(child, crossAxis) - child->layout.dimensions[dim[crossAxis]];
        } else if (alignContentAlignItem == CSS_ALIGN_CENTER) {
          float childHeight = child->layout.dimensions[dim[crossAxis]];
          child->layout.position[pos[crossAxis]] = currentLead + (lineHeight - childHeight) / 2;
        } else if (alignContentAlignItem == CSS_ALIGN_STRETCH) {
          child->layout.position[pos[crossAxis]] = currentLead + getLeadingMargin(child, crossAxis);
          // TODO(prenaux): Correctly set the height of items with undefined
          //                (auto) crossAxis dimension.
        }
      }

      currentLead += lineHeight;
    }
  }

  bool needsMainTrailingPos = false;
  bool needsCrossTrailingPos = false;

  // If the user didn't specify a width or height, and it has not been set
  // by the container, then we set it via the children.
  if (!isMainDimDefined) {
    node->layout.dimensions[dim[mainAxis]] = fmaxf(
      // We're missing the last padding at this point to get the final
      // dimension
      boundAxis(node, mainAxis, linesMainDim + getTrailingPaddingAndBorder(node, mainAxis)),
      // We can never assign a width smaller than the padding and borders
      paddingAndBorderAxisMain
    );

    if (mainAxis == CSS_FLEX_DIRECTION_ROW_REVERSE ||
        mainAxis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) {
      needsMainTrailingPos = true;
    }
  }

  if (!isCrossDimDefined) {
    node->layout.dimensions[dim[crossAxis]] = fmaxf(
      // For the cross dim, we add both sides at the end because the value
      // is aggregate via a max function. Intermediate negative values
      // can mess this computation otherwise
      boundAxis(node, crossAxis, linesCrossDim + paddingAndBorderAxisCross),
      paddingAndBorderAxisCross
    );

    if (crossAxis == CSS_FLEX_DIRECTION_ROW_REVERSE ||
        crossAxis == CSS_FLEX_DIRECTION_COLUMN_REVERSE) {
      needsCrossTrailingPos = true;
    }
  }

  // <Loop F> Set trailing position if necessary
  if (needsMainTrailingPos || needsCrossTrailingPos) {
    for (i = 0; i < childCount; ++i) {
      child = node->get_child(node->context, i);

      if (needsMainTrailingPos) {
        setTrailingPosition(node, child, mainAxis);
      }

      if (needsCrossTrailingPos) {
        setTrailingPosition(node, child, crossAxis);
      }
    }
  }

  // <Loop G> Calculate dimensions for absolutely positioned elements
  currentAbsoluteChild = firstAbsoluteChild;
  while (currentAbsoluteChild != NULL) {
    // Pre-fill dimensions when using absolute position and both offsets for
    // the axis are defined (either both left and right or top and bottom).
    for (ii = 0; ii < 2; ii++) {
      axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;

      if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
          !isDimDefined(currentAbsoluteChild, axis) &&
          isPosDefined(currentAbsoluteChild, leading[axis]) &&
          isPosDefined(currentAbsoluteChild, trailing[axis])) {
        currentAbsoluteChild->layout.dimensions[dim[axis]] = fmaxf(
          boundAxis(currentAbsoluteChild, axis, node->layout.dimensions[dim[axis]] -
            getBorderAxis(node, axis) -
            getMarginAxis(currentAbsoluteChild, axis) -
            getPosition(currentAbsoluteChild, leading[axis]) -
            getPosition(currentAbsoluteChild, trailing[axis])
          ),
          // You never want to go smaller than padding
          getPaddingAndBorderAxis(currentAbsoluteChild, axis)
        );
      }

      if (isPosDefined(currentAbsoluteChild, trailing[axis]) &&
          !isPosDefined(currentAbsoluteChild, leading[axis])) {
        currentAbsoluteChild->layout.position[leading[axis]] =
          node->layout.dimensions[dim[axis]] -
          currentAbsoluteChild->layout.dimensions[dim[axis]] -
          getPosition(currentAbsoluteChild, trailing[axis]);
      }
    }

    child = currentAbsoluteChild;
    currentAbsoluteChild = currentAbsoluteChild->next_absolute_child;
    child->next_absolute_child = NULL;
  }
  /** END_GENERATED **/
}
      void DetectorObjectView::check()
      {
        InternalMessage("Model","Model::DetectorObjectView::check entering") ;
        
        Detector* detector = getViewPoint()->getObserver() ;
        if (!detector)
          return ;
        bool in_range = detector ? detector->canDetect(getObject()) : false ;
        
        if (!detector->getComputer())
          return ;        
        
        Computer* computer = detector->getComputer()->getTrait<Computer>() ;
        if (! computer)
          return ;
                  
        if (!in_range && m_detection_information)
        {
          // destroy object
          computer->getMemoryModel()->destroyObject(m_detection_information) ;
          m_detection_information = NULL ;
        }
        else if (in_range)
        {
          InternalMessage(
            "Model",
            "Model::DetectorObjectView::check in range updating detection data") ;
          
          bool mobile = false ;
          
          if (! m_detection_information)
          {
            Solid* solid = getObject()->getTrait<Solid>() ;
            
            // create object 
            m_detection_information = computer->getMemoryModel()->createObject() ;
            m_detection_information->addTrait(new DetectionData(detector->getComputer())) ;
            m_detection_information->addTrait(new Positionned()) ;
            m_detection_information->addTrait(new Solid(solid->getMesh())) ;

            m_detection_information->getTrait<DetectionData>()->m_detected = getObject() ;
          }
          // update object position
          Position position = getRelativePosition(getObject(),
                                                  computer->getObject()) ;
          
          m_detection_information->getTrait<Positionned>()->setPosition(position) ;
          
          // update speed if exists
          Mobile* mobileTrait = getObject()->getTrait<Mobile>() ;
          
          if (mobileTrait)
          {
            Mobile* data = m_detection_information->getTrait<Mobile>() ;
            if (! data)
            {
              data = new Mobile() ;
              m_detection_information->addTrait(data) ;
            }
            data->setSpeed(mobileTrait->getSpeed()) ;
            data->setAngularSpeed(mobileTrait->getAngularSpeed()) ;
          }

          // update identification
          Transponder* identified = 
              getObject()->getTrait<Transponder>() ; 
          
          Transponder* identifedData = 
              m_detection_information->getTrait<Transponder>() ; 
          
          if (identified)
          {
            if (! identifedData)
            {
              // gained identification
              m_detection_information->addTrait(new Transponder(*identified)) ;
            }
            else if (identifedData->getCode() != identified->getCode())
            {
              // changed identification
              identifedData->setCode(identified) ;
            }
          }
          else if (identifedData)
          {
            // lost identification
            m_detection_information->destroyTrait(identifedData) ;
          }

          // update Targetting
          std::set<TargetingSystem*> systems = getObject()->getChildren<TargetingSystem>() ;
          TargetingSystem* system_data = 
              m_detection_information->getTrait<TargetingSystem>() ;
          
          if (systems.size() == 1)
          {
            TargetingSystem* system = *(systems.begin()) ;
            
            if (! system_data)
            {
              // gained identification
              m_detection_information->addTrait(new TargetingSystem()) ;
              
              m_detection_information->getTrait<TargetingSystem>()->m_target =
                system->getTarget() ;
              m_detection_information->getTrait<TargetingSystem>()->notify() ;
            }
            else if (system_data->getTarget() != system->getTarget())
            {
              // changed selection
              system_data->m_target = system->getTarget() ;
              system_data->notify() ;
            }
          }
          else if (system_data)
          {
            // lost targeting system
            m_detection_information->destroyTrait(system_data) ;
          }
          
        }
        
        
        InternalMessage("Model","Model::DetectorObjectView::check leaving") ;
      }
Пример #18
0
void CGUIMessageBox::refreshControls()
{
	// Layout can be seen as 4 boxes (a layoutmanager would be nice)
	// One box at top over the whole width for title
	// Two boxes with same height at the middle beside each other for icon and for text
	// One box at the bottom for the buttons

	const IGUISkin* skin = Environment->getSkin();

	const s32 buttonHeight   = skin->getSize(EGDS_BUTTON_HEIGHT);
	const s32 buttonWidth    = skin->getSize(EGDS_BUTTON_WIDTH);
	const s32 titleHeight    = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH)+2;	// titlebar has no own constant
	const s32 buttonDistance = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);
	const s32 borderWidth 	 = skin->getSize(EGDS_MESSAGE_BOX_GAP_SPACE);

	// add the static text for the message
	core::rect<s32> staticRect;
	staticRect.UpperLeftCorner.X = borderWidth;
	staticRect.UpperLeftCorner.Y = titleHeight + borderWidth;
	staticRect.LowerRightCorner.X = staticRect.UpperLeftCorner.X + skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_WIDTH);
	staticRect.LowerRightCorner.Y = staticRect.UpperLeftCorner.Y + skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT);
	if (!StaticText)
	{
		StaticText = Environment->addStaticText(MessageText.c_str(), staticRect, false, false, this);

		StaticText->setWordWrap(true);
		StaticText->setSubElement(true);
		StaticText->grab();
	}
	else
	{
		StaticText->setRelativePosition(staticRect);
		StaticText->setText(MessageText.c_str());
	}

	s32 textHeight  = StaticText->getTextHeight();
	s32 textWidth = StaticText->getTextWidth() + 6;	// +6 because the static itself needs that
	const s32 iconHeight = IconTexture ? IconTexture->getOriginalSize().Height : 0;

	if ( textWidth < skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH) )
		textWidth = skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_WIDTH) + 6;
	// no neeed to check for max because it couldn't get larger due to statictextbox.
	if ( textHeight < skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT) )
		textHeight = skin->getSize(EGDS_MESSAGE_BOX_MIN_TEXT_HEIGHT);
	if ( textHeight > skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT) )
		textHeight = skin->getSize(EGDS_MESSAGE_BOX_MAX_TEXT_HEIGHT);

	// content is text + icons + borders (but not titlebar)
	s32 contentHeight = textHeight > iconHeight ? textHeight : iconHeight;
	contentHeight += borderWidth;
	s32 contentWidth = 0;

	// add icon
	if ( IconTexture )
	{
		core::position2d<s32> iconPos;
		iconPos.Y = titleHeight + borderWidth;
		if ( iconHeight < textHeight )
			iconPos.Y += (textHeight-iconHeight) / 2;
		iconPos.X = borderWidth;

		if (!Icon)
		{
			Icon = Environment->addImage(IconTexture, iconPos, true, this);
			Icon->setSubElement(true);
			Icon->grab();
		}
		else
		{
			core::rect<s32> iconRect( iconPos.X, iconPos.Y, iconPos.X + IconTexture->getOriginalSize().Width, iconPos.Y + IconTexture->getOriginalSize().Height );
			Icon->setRelativePosition(iconRect);
		}

		contentWidth += borderWidth + IconTexture->getOriginalSize().Width;
	}
	else if ( Icon )
	{
		Icon->drop();
		Icon->remove();
		Icon = 0;
	}

	// position text
	core::rect<s32> textRect;
	textRect.UpperLeftCorner.X = contentWidth + borderWidth;
	textRect.UpperLeftCorner.Y = titleHeight + borderWidth;
	if ( textHeight < iconHeight )
		textRect.UpperLeftCorner.Y += (iconHeight-textHeight) / 2;
	textRect.LowerRightCorner.X = textRect.UpperLeftCorner.X + textWidth;
	textRect.LowerRightCorner.Y = textRect.UpperLeftCorner.Y + textHeight;
	contentWidth += 2*borderWidth + textWidth;
	StaticText->setRelativePosition( textRect );

	// find out button size needs
	s32 countButtons = 0;
	if (Flags & EMBF_OK)
		++countButtons;
	if (Flags & EMBF_CANCEL)
		++countButtons;
	if (Flags & EMBF_YES)
		++countButtons;
	if (Flags & EMBF_NO)
		++countButtons;

	s32 buttonBoxWidth = countButtons * buttonWidth + 2 * borderWidth;
	if ( countButtons > 1 )
		buttonBoxWidth += (countButtons-1) * buttonDistance;
	s32 buttonBoxHeight = buttonHeight + 2 * borderWidth;

	// calc new message box sizes
	core::rect<s32> tmp = getRelativePosition();
	s32 msgBoxHeight = titleHeight + contentHeight + buttonBoxHeight;
	s32 msgBoxWidth = contentWidth > buttonBoxWidth ? contentWidth : buttonBoxWidth;

	// adjust message box position
	tmp.UpperLeftCorner.Y = (Parent->getAbsolutePosition().getHeight() - msgBoxHeight) / 2;
	tmp.LowerRightCorner.Y = tmp.UpperLeftCorner.Y + msgBoxHeight;
	tmp.UpperLeftCorner.X = (Parent->getAbsolutePosition().getWidth() - msgBoxWidth) / 2;
	tmp.LowerRightCorner.X = tmp.UpperLeftCorner.X + msgBoxWidth;
	setRelativePosition(tmp);

	// add buttons

	core::rect<s32> btnRect;
	btnRect.UpperLeftCorner.Y = titleHeight + contentHeight + borderWidth;
	btnRect.LowerRightCorner.Y = btnRect.UpperLeftCorner.Y + buttonHeight;
	btnRect.UpperLeftCorner.X = borderWidth;
	if ( contentWidth > buttonBoxWidth )
		btnRect.UpperLeftCorner.X += (contentWidth - buttonBoxWidth) / 2;	// center buttons
	btnRect.LowerRightCorner.X = btnRect.UpperLeftCorner.X + buttonWidth;

	IGUIElement* focusMe = 0;
	setButton(OkButton, (Flags & EMBF_OK) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_OK), focusMe);
	if ( Flags & EMBF_OK )
		btnRect += core::position2d<s32>(buttonWidth + buttonDistance, 0);
	setButton(CancelButton, (Flags & EMBF_CANCEL) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_CANCEL), focusMe);
	if ( Flags & EMBF_CANCEL )
		btnRect += core::position2d<s32>(buttonWidth + buttonDistance, 0);
	setButton(YesButton, (Flags & EMBF_YES) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_YES), focusMe);
	if ( Flags & EMBF_YES )
		btnRect += core::position2d<s32>(buttonWidth + buttonDistance, 0);
	setButton(NoButton, (Flags & EMBF_NO) != 0, btnRect, skin->getDefaultText(EGDT_MSG_BOX_NO), focusMe);

	if (Environment->hasFocus(this) && focusMe)
		Environment->setFocus(focusMe);
}
Пример #19
0
void GUIForumPostItem::setItemData(ForumThread* pThread)
{
	std::wstringstream ss;
	core::rect<s32> itemRect(5, 0, RelativeRect.getWidth()-5, RelativeRect.getHeight()), startRect;
	IGUIFont* pFont = Environment->getSkin()->getFont();

	startRect = itemRect;

	itemRect.LowerRightCorner.Y = itemRect.UpperLeftCorner.Y + FPI_AUTHOR_HEIGHT;
	if ( !m_pTxtAuthor )
	{
    ss << L"Author: " << pThread->getAuthorName().c_str();
		m_pTxtAuthor = Environment->addStaticText(ss.str().c_str(), itemRect, false, false, this);
		m_pTxtAuthor->setOverrideColor(m_colText);
		m_pTxtAuthor->setTextAlignment( EGUIA_UPPERLEFT, EGUIA_CENTER );
    ss.str(L"");
	}

	if ( pThread->getTitle().size() )
	{
 		offsetRect(itemRect, 0, itemRect.getHeight() + 5);
		if ( !m_pTxtSubject )
		{
			ss << L"Subject: " << pThread->getTitle().c_str();
			m_pTxtSubject = Environment->addStaticText(ss.str().c_str(), itemRect, false, false, this);
			m_pTxtSubject->setOverrideColor(m_colText);
			m_pTxtSubject->setTextAlignment( EGUIA_UPPERLEFT, EGUIA_CENTER );
			ss.str(L"");
		}
	}

	offsetRect(itemRect, 0, itemRect.getHeight() + 5);
	if ( !m_pTxtContent )
	{
		ss << pThread->getContent().c_str();
		m_pTxtContent = Environment->addStaticText(ss.str().c_str(), itemRect, true, true, this);
		m_pTxtContent->setBackgroundColor(m_colBkg);
		m_pTxtContent->setOverrideColor(m_colText);
	  itemRect.LowerRightCorner.Y = itemRect.UpperLeftCorner.Y + m_pTxtContent->getTextHeight();
		m_pTxtContent->setRelativePosition( itemRect );
		ss.str(L"");
	}

	// if this is a mission thread, then we need to create the button to accept the mission
	if ( pThread->getMissionID() )
	{
		// check which options should be shown
		MissionMgr& missionMgr = FCModel::instance().GetMissionMgr();
		bool bAccepted = missionMgr.isMissionAccepted(pThread->getMissionID());
		bool bCompleted = missionMgr.isMissionComplete(pThread->getMissionID());

		if ( !bAccepted && !bCompleted )
		{
			offsetRect(itemRect, 0, itemRect.getHeight() + 5);
			itemRect.LowerRightCorner.Y = itemRect.UpperLeftCorner.Y + 20;
			core::rect<s32> btnRect = itemRect;
			ss << "Accept";
			btnRect.LowerRightCorner.X = btnRect.UpperLeftCorner.X + pFont->getDimension(ss.str().c_str()).Width + 20;
			m_pBtnAccept = Environment->addButton(btnRect, this, BTN_ACCEPT, ss.str().c_str());
		}
	}

	core::rect<s32> myRect = getRelativePosition();
	myRect.LowerRightCorner.Y = myRect.UpperLeftCorner.Y + ( itemRect.LowerRightCorner.Y - startRect.UpperLeftCorner.Y ) + 5;
	setRelativePosition(myRect);

	m_pThread = pThread;
}
Пример #20
0
//! constructor
CGUIMessageBox::CGUIMessageBox(IGUIEnvironment* environment, const wchar_t* caption,
                               const wchar_t* text, s32 flags,
                               IGUIElement* parent, s32 id, core::rect<s32> rectangle)
	: CGUIWindow(environment, parent, id, rectangle), StaticText(0),
	OkButton(0), YesButton(0), NoButton(0), CancelButton(0)
{
	#ifdef _DEBUG
	setDebugName("CGUIMessageBox");
	#endif

	// remove focus
	Environment->setFocus(0);

	// remove buttons

	getMaximizeButton()->remove();
	getMinimizeButton()->remove();

	if (caption)
		setText(caption);

	IGUISkin* skin = Environment->getSkin();

	s32 buttonHeight = skin->getSize(EGDS_BUTTON_HEIGHT);
	s32 buttonWidth = skin->getSize(EGDS_BUTTON_WIDTH);
	s32 titleHeight = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH)+2;
	s32 buttonDistance = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);

	// add static multiline text

	core::dimension2d<s32> dim(AbsoluteClippingRect.getWidth() - buttonWidth,
	                           AbsoluteClippingRect.getHeight() - (buttonHeight * 3));
	core::position2d<s32> pos((AbsoluteClippingRect.getWidth() - dim.Width) / 2,
	                          buttonHeight / 2 + titleHeight);

	StaticText = Environment->addStaticText(text,
	                                        core::rect<s32>(pos, dim), false, false, this);
	StaticText->setWordWrap(true);
	StaticText->grab();

	// adjust static text height

	s32 textHeight = StaticText->getTextHeight();
	core::rect<s32> tmp = StaticText->getRelativePosition();
	tmp.LowerRightCorner.Y = tmp.UpperLeftCorner.Y + textHeight;
	StaticText->setRelativePosition(tmp);
	dim.Height = textHeight;

	// adjust message box height

	tmp = getRelativePosition();
	s32 msgBoxHeight = textHeight + (s32)(2.5f * buttonHeight) + titleHeight;

	// adjust message box position

	tmp.UpperLeftCorner.Y = (parent->getAbsolutePosition().getHeight() - msgBoxHeight) / 2;
	tmp.LowerRightCorner.Y = tmp.UpperLeftCorner.Y + msgBoxHeight;
	setRelativePosition(tmp);


	// add buttons

	s32 countButtons = 0;
	if (flags & EMBF_OK) ++countButtons;
	if (flags & EMBF_CANCEL) ++countButtons;
	if (flags & EMBF_YES) ++countButtons;
	if (flags & EMBF_NO) ++countButtons;

	core::rect<s32> btnRect;
	btnRect.UpperLeftCorner.Y = pos.Y + dim.Height + buttonHeight / 2;
	btnRect.LowerRightCorner.Y = btnRect.UpperLeftCorner.Y + buttonHeight;
	btnRect.UpperLeftCorner.X = (AbsoluteClippingRect.getWidth() -
	                             ((buttonWidth + buttonDistance)*countButtons)) / 2;
	btnRect.LowerRightCorner.X = btnRect.UpperLeftCorner.X + buttonWidth;

	// add ok button
	if (flags & EMBF_OK)
	{
		OkButton = Environment->addButton(btnRect, this);
		OkButton->setText(skin->getDefaultText(EGDT_MSG_BOX_OK));
		OkButton->grab();

		btnRect.LowerRightCorner.X += buttonWidth + buttonDistance;
		btnRect.UpperLeftCorner.X += buttonWidth + buttonDistance;

		Environment->setFocus(OkButton);
	}

	// add yes button
	if (flags & EMBF_YES)
	{
		YesButton = Environment->addButton(btnRect, this);
		YesButton->setText(skin->getDefaultText(EGDT_MSG_BOX_YES));
		YesButton->grab();

		btnRect.LowerRightCorner.X += buttonWidth + buttonDistance;
		btnRect.UpperLeftCorner.X += buttonWidth + buttonDistance;
	}

	// add no button
	if (flags & EMBF_NO)
	{
		NoButton = Environment->addButton(btnRect, this);
		NoButton->setText(skin->getDefaultText(EGDT_MSG_BOX_NO));
		NoButton->grab();

		btnRect.LowerRightCorner.X += buttonWidth + buttonDistance;
		btnRect.UpperLeftCorner.X += buttonWidth + buttonDistance;
	}

	// add cancel button
	if (flags & EMBF_CANCEL)
	{
		CancelButton = Environment->addButton(btnRect, this);
		CancelButton->setText(skin->getDefaultText(EGDT_MSG_BOX_CANCEL));
		CancelButton->grab();

		btnRect.LowerRightCorner.X += buttonWidth + buttonDistance;
		btnRect.UpperLeftCorner.X += buttonWidth + buttonDistance;
	}


}
Пример #21
0
static void layoutNodeImpl(css_node_t *node, float parentMaxWidth) {
  /** START_GENERATED **/
  css_flex_direction_t mainAxis = getFlexDirection(node);
  css_flex_direction_t crossAxis = mainAxis == CSS_FLEX_DIRECTION_ROW ?
    CSS_FLEX_DIRECTION_COLUMN :
    CSS_FLEX_DIRECTION_ROW;

  // Handle width and height style attributes
  setDimensionFromStyle(node, mainAxis);
  setDimensionFromStyle(node, crossAxis);

  // The position is set by the parent, but we need to complete it with a
  // delta composed of the margin and left/top/right/bottom
  node->layout.position[leading[mainAxis]] += getMargin(node, leading[mainAxis]) +
    getRelativePosition(node, mainAxis);
  node->layout.position[leading[crossAxis]] += getMargin(node, leading[crossAxis]) +
    getRelativePosition(node, crossAxis);

  if (isMeasureDefined(node)) {
    float width = CSS_UNDEFINED;
    if (isDimDefined(node, CSS_FLEX_DIRECTION_ROW)) {
      width = node->style.dimensions[CSS_WIDTH];
    } else if (!isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]])) {
      width = node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]];
    } else {
      width = parentMaxWidth -
        getMarginAxis(node, CSS_FLEX_DIRECTION_ROW);
    }
    width -= getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);

    // We only need to give a dimension for the text if we haven't got any
    // for it computed yet. It can either be from the style attribute or because
    // the element is flexible.
    bool isRowUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_ROW) &&
      isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]]);
    bool isColumnUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_COLUMN) &&
      isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]]);

    // Let's not measure the text if we already know both dimensions
    if (isRowUndefined || isColumnUndefined) {
      css_dim_t measure_dim = node->measure(
        node->context,
        width
      );
      if (isRowUndefined) {
        node->layout.dimensions[CSS_WIDTH] = measure_dim.dimensions[CSS_WIDTH] +
          getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
      }
      if (isColumnUndefined) {
        node->layout.dimensions[CSS_HEIGHT] = measure_dim.dimensions[CSS_HEIGHT] +
          getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_COLUMN);
      }
    }
    return;
  }

  // Pre-fill some dimensions straight from the parent
  for (int i = 0; i < node->children_count; ++i) {
    css_node_t* child = node->get_child(node->context, i);
    // Pre-fill cross axis dimensions when the child is using stretch before
    // we call the recursive layout pass
    if (getAlignItem(node, child) == CSS_ALIGN_STRETCH &&
        getPositionType(child) == CSS_POSITION_RELATIVE &&
        !isUndefined(node->layout.dimensions[dim[crossAxis]]) &&
        !isDimDefined(child, crossAxis)) {
      child->layout.dimensions[dim[crossAxis]] = fmaxf(
        node->layout.dimensions[dim[crossAxis]] -
          getPaddingAndBorderAxis(node, crossAxis) -
          getMarginAxis(child, crossAxis),
        // You never want to go smaller than padding
        getPaddingAndBorderAxis(child, crossAxis)
      );
    } else if (getPositionType(child) == CSS_POSITION_ABSOLUTE) {
      // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
      // left and right or top and bottom).
      for (int ii = 0; ii < 2; ii++) {
        css_flex_direction_t axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
            !isDimDefined(child, axis) &&
            isPosDefined(child, leading[axis]) &&
            isPosDefined(child, trailing[axis])) {
          child->layout.dimensions[dim[axis]] = fmaxf(
            node->layout.dimensions[dim[axis]] -
            getPaddingAndBorderAxis(node, axis) -
            getMarginAxis(child, axis) -
            getPosition(child, leading[axis]) -
            getPosition(child, trailing[axis]),
            // You never want to go smaller than padding
            getPaddingAndBorderAxis(child, axis)
          );
        }
      }
    }
  }

  float definedMainDim = CSS_UNDEFINED;
  if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
    definedMainDim = node->layout.dimensions[dim[mainAxis]] -
        getPaddingAndBorderAxis(node, mainAxis);
  }

  // We want to execute the next two loops one per line with flex-wrap
  int startLine = 0;
  int endLine = 0;
  int nextLine = 0;
  // We aggregate the total dimensions of the container in those two variables
  float linesCrossDim = 0;
  float linesMainDim = 0;
  while (endLine != node->children_count) {
    // <Loop A> Layout non flexible children and count children by type

    // mainContentDim is accumulation of the dimensions and margin of all the
    // non flexible children. This will be used in order to either set the
    // dimensions of the node if none already exist, or to compute the
    // remaining space left for the flexible children.
    float mainContentDim = 0;

    // There are three kind of children, non flexible, flexible and absolute.
    // We need to know how many there are in order to distribute the space.
    int flexibleChildrenCount = 0;
    float totalFlexible = 0;
    int nonFlexibleChildrenCount = 0;
    for (int i = startLine; i < node->children_count; ++i) {
      css_node_t* child = node->get_child(node->context, i);
      float nextContentDim = 0;

      // It only makes sense to consider a child flexible if we have a computed
      // dimension for the node->
      if (!isUndefined(node->layout.dimensions[dim[mainAxis]]) && isFlex(child)) {
        flexibleChildrenCount++;
        totalFlexible += getFlex(child);

        // Even if we don't know its exact size yet, we already know the padding,
        // border and margin. We'll use this partial information to compute the
        // remaining space.
        nextContentDim = getPaddingAndBorderAxis(child, mainAxis) +
          getMarginAxis(child, mainAxis);

      } else {
        float maxWidth = CSS_UNDEFINED;
        if (mainAxis == CSS_FLEX_DIRECTION_ROW) {
          // do nothing
        } else if (isDimDefined(node, CSS_FLEX_DIRECTION_ROW)) {
          maxWidth = node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] -
            getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
        } else {
          maxWidth = parentMaxWidth -
            getMarginAxis(node, CSS_FLEX_DIRECTION_ROW) -
            getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
        }

        // This is the main recursive call. We layout non flexible children.
        if (nextLine == 0) {
          layoutNode(child, maxWidth);
        }

        // Absolute positioned elements do not take part of the layout, so we
        // don't use them to compute mainContentDim
        if (getPositionType(child) == CSS_POSITION_RELATIVE) {
          nonFlexibleChildrenCount++;
          // At this point we know the final size and margin of the element.
          nextContentDim = getDimWithMargin(child, mainAxis);
        }
      }

      // The element we are about to add would make us go to the next line
      if (isFlexWrap(node) &&
          !isUndefined(node->layout.dimensions[dim[mainAxis]]) &&
          mainContentDim + nextContentDim > definedMainDim) {
        nextLine = i + 1;
        break;
      }
      nextLine = 0;
      mainContentDim += nextContentDim;
      endLine = i + 1;
    }

    // <Loop B> Layout flexible children and allocate empty space

    // In order to position the elements in the main axis, we have two
    // controls. The space between the beginning and the first element
    // and the space between each two elements.
    float leadingMainDim = 0;
    float betweenMainDim = 0;

    // The remaining available space that needs to be allocated
    float remainingMainDim = 0;
    if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
      remainingMainDim = definedMainDim - mainContentDim;
    } else {
      remainingMainDim = fmaxf(mainContentDim, 0) - mainContentDim;
    }

    // If there are flexible children in the mix, they are going to fill the
    // remaining space
    if (flexibleChildrenCount != 0) {
      float flexibleMainDim = remainingMainDim / totalFlexible;

      // The non flexible children can overflow the container, in this case
      // we should just assume that there is no space available.
      if (flexibleMainDim < 0) {
        flexibleMainDim = 0;
      }
      // We iterate over the full array and only apply the action on flexible
      // children. This is faster than actually allocating a new array that
      // contains only flexible children.
      for (int i = startLine; i < endLine; ++i) {
        css_node_t* child = node->get_child(node->context, i);
        if (isFlex(child)) {
          // At this point we know the final size of the element in the main
          // dimension
          child->layout.dimensions[dim[mainAxis]] = flexibleMainDim * getFlex(child) +
            getPaddingAndBorderAxis(child, mainAxis);

          float maxWidth = CSS_UNDEFINED;
          if (mainAxis == CSS_FLEX_DIRECTION_ROW) {
            // do nothing
          } else if (isDimDefined(node, CSS_FLEX_DIRECTION_ROW)) {
            maxWidth = node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] -
              getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
          } else {
            maxWidth = parentMaxWidth -
              getMarginAxis(node, CSS_FLEX_DIRECTION_ROW) -
              getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
          }

          // And we recursively call the layout algorithm for this child
          layoutNode(child, maxWidth);
        }
      }

    // We use justifyContent to figure out how to allocate the remaining
    // space available
    } else {
      css_justify_t justifyContent = getJustifyContent(node);
      if (justifyContent == CSS_JUSTIFY_FLEX_START) {
        // Do nothing
      } else if (justifyContent == CSS_JUSTIFY_CENTER) {
        leadingMainDim = remainingMainDim / 2;
      } else if (justifyContent == CSS_JUSTIFY_FLEX_END) {
        leadingMainDim = remainingMainDim;
      } else if (justifyContent == CSS_JUSTIFY_SPACE_BETWEEN) {
        remainingMainDim = fmaxf(remainingMainDim, 0);
        if (flexibleChildrenCount + nonFlexibleChildrenCount - 1 != 0) {
          betweenMainDim = remainingMainDim /
            (flexibleChildrenCount + nonFlexibleChildrenCount - 1);
        } else {
          betweenMainDim = 0;
        }
      } else if (justifyContent == CSS_JUSTIFY_SPACE_AROUND) {
        // Space on the edges is half of the space between elements
        betweenMainDim = remainingMainDim /
          (flexibleChildrenCount + nonFlexibleChildrenCount);
        leadingMainDim = betweenMainDim / 2;
      }
    }

    // <Loop C> Position elements in the main axis and compute dimensions

    // At this point, all the children have their dimensions set. We need to
    // find their position. In order to do that, we accumulate data in
    // variables that are also useful to compute the total dimensions of the
    // container!
    float crossDim = 0;
    float mainDim = leadingMainDim +
      getPaddingAndBorder(node, leading[mainAxis]);

    for (int i = startLine; i < endLine; ++i) {
      css_node_t* child = node->get_child(node->context, i);

      if (getPositionType(child) == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[mainAxis])) {
        // In case the child is position absolute and has left/top being
        // defined, we override the position to whatever the user said
        // (and margin/border).
        child->layout.position[pos[mainAxis]] = getPosition(child, leading[mainAxis]) +
          getBorder(node, leading[mainAxis]) +
          getMargin(child, leading[mainAxis]);
      } else {
        // If the child is position absolute (without top/left) or relative,
        // we put it at the current accumulated offset.
        child->layout.position[pos[mainAxis]] += mainDim;
      }

      // Now that we placed the element, we need to update the variables
      // We only need to do that for relative elements. Absolute elements
      // do not take part in that phase.
      if (getPositionType(child) == CSS_POSITION_RELATIVE) {
        // The main dimension is the sum of all the elements dimension plus
        // the spacing.
        mainDim += betweenMainDim + getDimWithMargin(child, mainAxis);
        // The cross dimension is the max of the elements dimension since there
        // can only be one element in that cross dimension.
        crossDim = fmaxf(crossDim, getDimWithMargin(child, crossAxis));
      }
    }

    float containerMainAxis = node->layout.dimensions[dim[mainAxis]];
    // If the user didn't specify a width or height, and it has not been set
    // by the container, then we set it via the children.
    if (isUndefined(node->layout.dimensions[dim[mainAxis]])) {
      containerMainAxis = fmaxf(
        // We're missing the last padding at this point to get the final
        // dimension
        mainDim + getPaddingAndBorder(node, trailing[mainAxis]),
        // We can never assign a width smaller than the padding and borders
        getPaddingAndBorderAxis(node, mainAxis)
      );
    }

    float containerCrossAxis = node->layout.dimensions[dim[crossAxis]];
    if (isUndefined(node->layout.dimensions[dim[crossAxis]])) {
      containerCrossAxis = fmaxf(
        // For the cross dim, we add both sides at the end because the value
        // is aggregate via a max function. Intermediate negative values
        // can mess this computation otherwise
        crossDim + getPaddingAndBorderAxis(node, crossAxis),
        getPaddingAndBorderAxis(node, crossAxis)
      );
    }

    // <Loop D> Position elements in the cross axis

    for (int i = startLine; i < endLine; ++i) {
      css_node_t* child = node->get_child(node->context, i);

      if (getPositionType(child) == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[crossAxis])) {
        // In case the child is absolutely positionned and has a
        // top/left/bottom/right being set, we override all the previously
        // computed positions to set it correctly.
        child->layout.position[pos[crossAxis]] = getPosition(child, leading[crossAxis]) +
          getBorder(node, leading[crossAxis]) +
          getMargin(child, leading[crossAxis]);

      } else {
        float leadingCrossDim = getPaddingAndBorder(node, leading[crossAxis]);

        // For a relative children, we're either using alignItems (parent) or
        // alignSelf (child) in order to determine the position in the cross axis
        if (getPositionType(child) == CSS_POSITION_RELATIVE) {
          css_align_t alignItem = getAlignItem(node, child);
          if (alignItem == CSS_ALIGN_FLEX_START) {
            // Do nothing
          } else if (alignItem == CSS_ALIGN_STRETCH) {
            // You can only stretch if the dimension has not already been set
            // previously.
            if (!isDimDefined(child, crossAxis)) {
              child->layout.dimensions[dim[crossAxis]] = fmaxf(
                containerCrossAxis -
                  getPaddingAndBorderAxis(node, crossAxis) -
                  getMarginAxis(child, crossAxis),
                // You never want to go smaller than padding
                getPaddingAndBorderAxis(child, crossAxis)
              );
            }
          } else {
            // The remaining space between the parent dimensions+padding and child
            // dimensions+margin.
            float remainingCrossDim = containerCrossAxis -
              getPaddingAndBorderAxis(node, crossAxis) -
              getDimWithMargin(child, crossAxis);

            if (alignItem == CSS_ALIGN_CENTER) {
              leadingCrossDim += remainingCrossDim / 2;
            } else { // CSS_ALIGN_FLEX_END
              leadingCrossDim += remainingCrossDim;
            }
          }
        }

        // And we apply the position
        child->layout.position[pos[crossAxis]] += linesCrossDim + leadingCrossDim;
      }
    }

    linesCrossDim += crossDim;
    linesMainDim = fmaxf(linesMainDim, mainDim);
    startLine = endLine;
  }

  // If the user didn't specify a width or height, and it has not been set
  // by the container, then we set it via the children.
  if (isUndefined(node->layout.dimensions[dim[mainAxis]])) {
    node->layout.dimensions[dim[mainAxis]] = fmaxf(
      // We're missing the last padding at this point to get the final
      // dimension
      linesMainDim + getPaddingAndBorder(node, trailing[mainAxis]),
      // We can never assign a width smaller than the padding and borders
      getPaddingAndBorderAxis(node, mainAxis)
    );
  }

  if (isUndefined(node->layout.dimensions[dim[crossAxis]])) {
    node->layout.dimensions[dim[crossAxis]] = fmaxf(
      // For the cross dim, we add both sides at the end because the value
      // is aggregate via a max function. Intermediate negative values
      // can mess this computation otherwise
      linesCrossDim + getPaddingAndBorderAxis(node, crossAxis),
      getPaddingAndBorderAxis(node, crossAxis)
    );
  }

  // <Loop E> Calculate dimensions for absolutely positioned elements

  for (int i = 0; i < node->children_count; ++i) {
    css_node_t* child = node->get_child(node->context, i);
    if (getPositionType(child) == CSS_POSITION_ABSOLUTE) {
      // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
      // left and right or top and bottom).
      for (int ii = 0; ii < 2; ii++) {
        css_flex_direction_t axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
            !isDimDefined(child, axis) &&
            isPosDefined(child, leading[axis]) &&
            isPosDefined(child, trailing[axis])) {
          child->layout.dimensions[dim[axis]] = fmaxf(
            node->layout.dimensions[dim[axis]] -
            getPaddingAndBorderAxis(node, axis) -
            getMarginAxis(child, axis) -
            getPosition(child, leading[axis]) -
            getPosition(child, trailing[axis]),
            // You never want to go smaller than padding
            getPaddingAndBorderAxis(child, axis)
          );
        }
      }
      for (int ii = 0; ii < 2; ii++) {
        css_flex_direction_t axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (isPosDefined(child, trailing[axis]) &&
            !isPosDefined(child, leading[axis])) {
          child->layout.position[leading[axis]] =
            node->layout.dimensions[dim[axis]] -
            child->layout.dimensions[dim[axis]] -
            getPosition(child, trailing[axis]);
        }
      }
    }
  }
  /** END_GENERATED **/
}
Пример #22
0
void CGUIImage::setRelativeScale(vector2df scale)
{
    Scale = scale;
    this->setRelativePosition(getRelativePosition()); //Tells it to resize the image
}
Пример #23
0
void WindModificator::setRelativePositionTo (const b2Vec2& pos)
{
	b2Vec2 modPos = pos;
	getRelativePosition(modPos);
	setPos(modPos);
}