コード例 #1
0
ファイル: CCSprite3D.cpp プロジェクト: dabingnn/cocosVR
bool Sprite3D::initWithFile(const std::string& path)
{
    _meshes.clear();
    _meshVertexDatas.clear();
    CC_SAFE_RELEASE_NULL(_skeleton);
    removeAllAttachNode();
    
    if (loadFromCache(path))
        return true;
    
    MeshDatas* meshdatas = new (std::nothrow) MeshDatas();
    MaterialDatas* materialdatas = new (std::nothrow) MaterialDatas();
    NodeDatas* nodeDatas = new (std::nothrow) NodeDatas();
    if (loadFromFile(path, nodeDatas, meshdatas, materialdatas))
    {
        if (initFrom(*nodeDatas, *meshdatas, *materialdatas))
        {
            //add to cache
            auto data = new (std::nothrow) Sprite3DCache::Sprite3DData();
            data->materialdatas = materialdatas;
            data->nodedatas = nodeDatas;
            data->meshVertexDatas = _meshVertexDatas;
            for (const auto mesh : _meshes) {
                data->glProgramStates.pushBack(mesh->getGLProgramState());
            }
            
            Sprite3DCache::getInstance()->addSprite3DData(path, data);
            CC_SAFE_DELETE(meshdatas);
            _contentSize = getBoundingBox().size;
            return true;
        }
    }
    CC_SAFE_DELETE(meshdatas);
    CC_SAFE_DELETE(materialdatas);
    CC_SAFE_DELETE(nodeDatas);
    
    return false;
}
コード例 #2
0
ファイル: SVGStylable.cpp プロジェクト: CaptEmulation/svgl
  void
  SVGStylable::glTraverseBoundingBox(svgl::Context * svglContext, svgl::GLInfo* glinfo)
  {
    float x,y,width,height;
    getBoundingBox(svglContext, glinfo, &x, &y, &width, &height);
    const css::CSSStyleDeclaration& style = getStyle().getValue();
    svg::SVGLength strokeWidth = style.getStrokeWidth();
    float sw = svglContext->computeWidthLength(strokeWidth);
    float swon2 = sw/2.0;
    glBegin(GL_LINE_LOOP);

    glVertex2f(x-swon2,y-swon2);
    glVertex2f(x+sw+width,y-swon2);
    glVertex2f(x+sw+width,y+sw+height);
    glVertex2f(x-swon2,y+sw+height);

    glVertex2f(x-swon2,y-swon2);
    glVertex2f(x+sw+width,y+sw+height);
    glVertex2f(x+sw+width,y-swon2);
    glVertex2f(x-swon2,y+sw+height);

    glEnd();  
  }
コード例 #3
0
ファイル: GoostBase.cpp プロジェクト: yfxx/SimpleGame
bool GoostBase::isDesiredPositionValid() {
	Rect box;
	box.origin = this->getBoundingBox().origin + (_desiredPosition - this->getPosition());
	box.size = Size(GOOST_CENTER_TO_SIDE * 2, GOOST_CENTER_TO_SIDE * 2);

	// detect boundary collision
	auto vsize = Director::getInstance()->getVisibleSize();
	if (_desiredPosition.x > vsize.width - GOOST_CENTER_TO_SIDE || _desiredPosition.x < GOOST_CENTER_TO_SIDE
		|| _desiredPosition.y > vsize.height-80 - GOOST_CENTER_TO_SIDE || _desiredPosition.y < GOOST_CENTER_TO_SIDE) {
		return false;
	}

	// detect brick collision
	auto bricks = GameScene::getInstance()->_mapLayer->getAllBricks();
	for (int i = 0; i < bricks.size(); i++) {
		auto brick = bricks.at(i);
		if (brick->getBoundingBox().intersectsRect(box)) {
			return false;
		}
	}

	return true;
}
コード例 #4
0
ファイル: GRCluster.cpp プロジェクト: anttirt/guidolib
void GRCluster::updateBoundingBox()
{
    float curLSpace = mGrStaff->getStaffLSPACE();
    float dx        = getBoundingBox().left + fdx + fhdx;
    float dy        = - fdy - fhdy;

    float xOrientation = 0;

    if (fClusterOrientation == ARTHead::LEFT && fStemDir == dirDOWN)
        xOrientation = - 55;
    else if (fClusterOrientation == ARTHead::RIGHT && fStemDir == dirUP)
        xOrientation =   55;

    NVPoint pFirstNote  = (firstNote->getPosition().y < secondNote->getPosition().y ? firstNote->getPosition() : secondNote->getPosition());
    NVPoint pSecondNote = (firstNote->getPosition().y > secondNote->getPosition().y ? firstNote->getPosition() : secondNote->getPosition());

    mMapping.top    = dy + pFirstNote.y + curLSpace / 2;
    mMapping.bottom = dy + pSecondNote.y + 3 * curLSpace / 2;
    mMapping.left   = dx + (xOrientation - 31) * mTagSize * fsize;
    mMapping.right  = dx + (xOrientation + 29) * mTagSize * fsize;

    mMapping += mPosition;
}
コード例 #5
0
bool introduction::init()
{
	if (!Layer::init())
	{
		return false;
	}

	visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();
	dispatcher = Director::getInstance()->getEventDispatcher();

	auto background = Sprite::create("parent_read/about_us.png");
	auto x = visibleSize.width / background->getContentSize().width;
	auto y = visibleSize.height / background->getContentSize().height;
	background->setScale(x, y);
	background->setAnchorPoint(Vec2::ZERO);
	background->setPosition(Vec2::ZERO);
	this->addChild(background, 1);

	auto taglabel = Sprite::create("parentmode/44.png");
	float xx = visibleSize.width / taglabel->getContentSize().width;
	float yy = visibleSize.height / taglabel->getContentSize().height;
	taglabel->setScale(xx / 2, yy);
	taglabel->setAnchorPoint(Vec2::ZERO);
	taglabel->setPosition(Vec2::ZERO);
	this->addChild(taglabel, 5);

	auto back = MenuItemImage::create("timeset/back.png", "timeset/back.png", CC_CALLBACK_1(introduction::returnto, this));
	back->setScale(0.2*visibleSize.height / back->getContentSize().height);
	auto back_menu = Menu::create(back, NULL);
	back_menu->setPosition(Vec2(back->getBoundingBox().size.width / 2, visibleSize.height - back->getBoundingBox().size.height / 2));
	this->addChild(back_menu, 3);

	testTouchEvent();

	return true;
}
コード例 #6
0
void GhostFormSpell::loadParticleSystem(float startVelocity) {
	m_ps = std::unique_ptr<particles::TextureParticleSystem>(new particles::TextureParticleSystem(100, g_resourceManager->getTexture(ResourceID::Texture_Particle_longblob)));
	m_ps->additiveBlendMode = true;
	m_ps->emitRate = 50.0f;

	// Generators
	auto posGen = m_ps->addGenerator<particles::BoxPositionGenerator>();
	posGen->center = sf::Vector2f(getPosition().x + getBoundingBox()->width / 2.f, getPosition().y + getBoundingBox()->height / 2.f);
	posGen->size = sf::Vector2f(1.f, m_mob->getBoundingBox()->height / 2.f);
	m_posGenerator = posGen;

	auto sizeGen = m_ps->addGenerator<particles::SizeGenerator>();
	sizeGen->minStartSize = 2.f;
	sizeGen->maxStartSize = 5.f;
	sizeGen->minEndSize = 0.5f;
	sizeGen->maxEndSize = 2.f;

	auto colGen = m_ps->addGenerator<particles::ColorGenerator>();
	colGen->minStartCol = sf::Color(89, 222, 100, 200);
	colGen->maxStartCol = sf::Color(157, 254, 167, 250);
	colGen->minEndCol = sf::Color(200, 255, 200, 0);
	colGen->maxEndCol = sf::Color(255, 255, 255, 0);

	auto velGen = m_ps->addGenerator<particles::AngledVelocityGenerator>();
	velGen->minStartVel = startVelocity / 2.f - 10.f;
	velGen->maxStartVel = startVelocity / 2.f + 10.f;
	m_velGenerator = velGen;

	auto timeGen = m_ps->addGenerator<particles::TimeGenerator>();
	timeGen->minTime = 0.5f;
	timeGen->maxTime = 1.f;

	// Updaters
	m_ps->addUpdater<particles::TimeUpdater>();
	m_ps->addUpdater<particles::ColorUpdater>();
	m_ps->addUpdater<particles::SizeUpdater>();
}
コード例 #7
0
ファイル: RTPolySet.cpp プロジェクト: havardh/ECE594Q
// Duplicate of Scene::intersection should be refactored
IntersectionPtr RTPolySet::intersect(const Ray ray) {

  IntersectionPtr intersection(NULL);

  float min, max;

  if (!getBoundingBox().intersects(ray, min, max)) {    
    return intersection;
  }

  std::vector<RTTriangle>::iterator it;
  for (it = triangles.begin();
       it != triangles.end();
       ++it) {

    IntersectionPtr newIntersection = it->intersect(ray);
    if (newIntersection != nullptr) {
      if (intersection == nullptr || *newIntersection < *intersection) {
        intersection = newIntersection;
      }
    }
  }
  return intersection;
}
コード例 #8
0
ファイル: MeshObject.cpp プロジェクト: mantidproject/mantid
/**
 * Given a track, fill the track with valid section
 * @param UT :: Initial track
 * @return Number of segments added
 */
int MeshObject::interceptSurface(Geometry::Track &UT) const {

  int originalCount = UT.count(); // Number of intersections original track
  BoundingBox bb = getBoundingBox();
  if (!bb.doesLineIntersect(UT)) {
    return 0;
  }

  std::vector<Kernel::V3D> intersectionPoints;
  std::vector<TrackDirection> entryExit;

  getIntersections(UT.startPoint(), UT.direction(), intersectionPoints,
                   entryExit);
  if (intersectionPoints.empty())
    return 0; // Quit if no intersections found

  // For a 3D mesh, a ray may intersect several segments
  for (size_t i = 0; i < intersectionPoints.size(); ++i) {
    UT.addPoint(entryExit[i], intersectionPoints[i], *this);
  }
  UT.buildLink();

  return UT.count() - originalCount;
}
コード例 #9
0
ファイル: MeshObject.cpp プロジェクト: mantidproject/mantid
/**
 * Calculate volume.
 * @return The volume.
 */
double MeshObject::volume() const {
  // Select centre of bounding box as centre point.
  // For each triangle calculate the signed volume of
  // the tetrahedron formed by the triangle and the
  // centre point. Then add to total.

  BoundingBox bb = getBoundingBox();
  double cX = 0.5 * (bb.xMax() + bb.xMin());
  double cY = 0.5 * (bb.yMax() + bb.yMin());
  double cZ = 0.5 * (bb.zMax() + bb.zMin());
  Kernel::V3D centre(cX, cY, cZ);

  double volumeTimesSix(0.0);

  Kernel::V3D vertex1, vertex2, vertex3;
  for (size_t i = 0; getTriangle(i, vertex1, vertex2, vertex3); ++i) {
    Kernel::V3D a = vertex1 - centre;
    Kernel::V3D b = vertex2 - centre;
    Kernel::V3D c = vertex3 - centre;
    volumeTimesSix += a.scalar_prod(b.cross_prod(c));
  }

  return volumeTimesSix / 6.0;
}
コード例 #10
0
ファイル: KeyboardPaddle.cpp プロジェクト: Zaka/yap
bool KeyboardPaddle::collideWithBall(Ball* ball) {
        auto paddleBBox = getBoundingBox();
        auto ballBBox = ball->getBoundingBox();

        float bLeft = ballBBox.getMinX();
        float bHigh = ballBBox.getMaxY();
        float bLow = ballBBox.getMinY();

        float pRight = paddleBBox.getMaxX();
        float pHigh = paddleBBox.getMaxY();
        float pLow = paddleBBox.getMinY();

        if (bLeft <= pRight) {
                if (bHigh <= pHigh
                    && bHigh >= pLow) {
                        return true;
                } else if (bLow <= pHigh
                           && bLow >= pLow) {
                        return true;
                }
        }

        return false;
}
コード例 #11
0
	// 更新触发器数据,调用这个会导致一次遍历查询,并回调
	void OctreeTriggerPlayer::updateTrigger()
	{
		if(m_aabb.isNull())
			return;
		// 更新有向包围盒信息
		m_obb.setCenter(getPosition());
		m_obb.setExtents(getBoundingBox().getHalfSize() * getScale());
		m_obb.setOrientation(getOrientation());

		m_query->setBox(getWorldBoundingBox(true));
		SceneQueryResult& result = m_query->execute();

		// 现在发生了碰撞的列表
		MapCollideTriggerEntity mapCollideTriggerEntity;

		// 遍历结果
		for(SceneQueryResultMovableList::iterator iter = result.movables.begin() ; iter != result.movables.end() ; iter ++)
		{
			// 先转换成ITriggerEntity
			ITriggerEntity *entity = trigger_cast((*iter)->getUserAny());
			if(entity)
			{
				// 做碰撞计算,如果发生碰撞了
				if(entity->collide(this))
				{				
					// 添加进去
					mapCollideTriggerEntity[entity->getName()] = entity;
				}
			}
		}

		// 遍历发生碰撞的结果
		for(MapCollideTriggerEntity::iterator iter = mapCollideTriggerEntity.begin() ; iter != mapCollideTriggerEntity.end() ; iter ++)
		{
			// 如果不在里面,就说明进去了
			if(m_mapCollideTriggerEntity.find(iter->second->getName()) == m_mapCollideTriggerEntity.end())
			{
				// 回调到玩家
				const ITriggerPlayer::ListListener &listPlayer = getListenerList();
				for(size_t i = 0 ; i < listPlayer.size() ; i ++)
				{
					listPlayer[i]->onEnter(iter->second , this);
				}
				// 回调到触发器
				const ITriggerEntity::ListListener &listEntity = iter->second->getListenerList();
				for(size_t i = 0 ; i < listEntity.size() ; i ++)
				{
					listEntity[i]->onEnter(iter->second , this);
				}
				// 回调到世界
				const ITriggerWorld::ListListener &listWorld = m_world->getListenerList();
				for(size_t i = 0 ; i < listWorld.size() ; i ++)
				{
					listWorld[i]->onEnter(iter->second , this);
				}
			}
		}

		// 遍历未发生碰撞的结果
		for(MapCollideTriggerEntity::iterator iter = m_mapCollideTriggerEntity.begin() ; iter != m_mapCollideTriggerEntity.end() ; iter ++)
		{
			// 如果不在里面,就说明出去了
			if(mapCollideTriggerEntity.find(iter->second->getName()) == mapCollideTriggerEntity.end())
			{
				// 回调到玩家
				const ITriggerPlayer::ListListener &listPlayer = getListenerList();
				for(size_t i = 0 ; i < listPlayer.size() ; i ++)
				{
					listPlayer[i]->onLeave(iter->second , this);
				}
				// 回调到触发器
				const ITriggerEntity::ListListener &listEntity = iter->second->getListenerList();
				for(size_t i = 0 ; i < listEntity.size() ; i ++)
				{
					listEntity[i]->onLeave(iter->second , this);
				}
				// 回调到世界
				const ITriggerWorld::ListListener &listWorld = m_world->getListenerList();
				for(size_t i = 0 ; i < listWorld.size() ; i ++)
				{
					listWorld[i]->onLeave(iter->second , this);
				}
			}
		}

		// 保存新的结果
		m_mapCollideTriggerEntity = mapCollideTriggerEntity;
	}
コード例 #12
0
ファイル: SVGStylable.cpp プロジェクト: CaptEmulation/svgl
  void
  SVGStylable::glTraverseOpacity(svgl::Context * svglContext,
				 svgl::GLInfo* glinfo,
				 const css::Color * fill,
				 const css::Color * stroke,
				 float fillOpacity,
				 float strokeOpacity,
				 float opacity,
				 float strokeWidth,
				 bool stencilStrokeHint
				 )
  {
    float sw = strokeWidth;
    float swon2 = sw/2.;
    float bbx,bby,bbwidth,bbheight;
    getBoundingBox(svglContext, glinfo, &bbx, &bby, &bbwidth, &bbheight);


    if(strokeOpacity==1) { // stroke is opaque
      // we can draw the stroke with stencil on,
      // then draw the fill where the stencil is off

      // stroke
      glinfo->stencilEnableTopAndPush();
      float alpha_save = glinfo->alpha;
      glinfo->alpha *= strokeOpacity * opacity;
      stroke->glPreTraverse(svglContext, glinfo, this, sw);
      glTraverseStroke(svglContext, glinfo, sw);
      stroke->glPostTraverse(svglContext, glinfo, this, sw);

      // fill only parts that do not belong to the stroke
      glinfo->alpha = alpha_save * fillOpacity * opacity;
      fill->glPreTraverse(svglContext, glinfo, this);
      glTraverseFill(svglContext, glinfo);
      fill->glPostTraverse(svglContext, glinfo, this);
      glinfo->alpha = alpha_save;

      // remove stencil
      glinfo->stencilPop();
      glBegin(GL_QUAD_STRIP);
      glVertex2f(bbx-swon2,bby-swon2);
      glVertex2f(bbx-swon2, bby+bbheight+sw);
      glVertex2f(bbx+bbwidth+sw, bby-swon2);
      glVertex2f(bbx+bbwidth+sw, bby+bbheight+sw);
      glEnd();
      glinfo->stencilEnableTop();
    }

    else { // stroke is not opaque
      svgl::BoundingBoxManager bboxManager;
      glPushMatrix();

      bboxManager.glPreTraverse(glinfo);

      glBegin(GL_LINE_LOOP);
      glVertex2f(bbx-swon2,bby-swon2);
      glVertex2f(bbx+sw+bbwidth,bby-swon2);
      glVertex2f(bbx+sw+bbwidth,bby+sw+bbheight);
      glVertex2f(bbx-swon2,bby+sw+bbheight);

      glVertex2f(bbx-swon2,bby-swon2);
      glVertex2f(bbx+sw+bbwidth,bby+sw+bbheight);
      glVertex2f(bbx+sw+bbwidth,bby-swon2);
      glVertex2f(bbx-swon2,bby+sw+bbheight);
      glEnd();  

      float xminf,yminf,xmaxf,ymaxf;
      bool snap_done = bboxManager.glPostTraverse(glinfo, &xminf, &yminf, &xmaxf, &ymaxf);
      glPopMatrix();

      if(snap_done) {
	svgl::MultiPassManager multiPassManager;
	multiPassManager.push(glinfo, xminf, yminf, xmaxf, ymaxf);
	float alpha_save  = glinfo->alpha;

	// fill
	glinfo->alpha = alpha_save * fillOpacity;
	fill->glPreTraverse(svglContext, glinfo, this);
	glTraverseFill(svglContext, glinfo);
	fill->glPostTraverse(svglContext, glinfo, this);
	  
	// stroke	
	//stencilStrokeHint=0;
	if(stencilStrokeHint) {
	  // since stroke pathes recover themself, we must use stencil
#if 1
	  glinfo->stencilEnableTopAndPush();
#else
	  glinfo->stencilEnableTest();
	  int& stencil = glinfo->stencil;
	  glStencilFunc(GL_EQUAL, stencil, static_cast<GLuint>(-1));
	  glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
	  ++stencil;
#endif
	}

	glinfo->alpha = alpha_save * strokeOpacity;
	stroke->glPreTraverse(svglContext, glinfo, this, sw);
	glTraverseStroke(svglContext, glinfo, sw);
#if 0
	if(stencilStrokeHint) {
	  glinfo->stencilEnableTop();
	}
#endif
	stroke->glPostTraverse(svglContext, glinfo, this, sw);

	// remove stencil
	if(stencilStrokeHint) {
	  // FIXME, not necessary if stroke is a gradient...
	  // not sure though...
	  glinfo->stencilPop();
	  glBegin(GL_QUAD_STRIP);
	  glVertex2f(bbx-swon2,bby-swon2);
	  glVertex2f(bbx-swon2, bby+bbheight+sw);
	  glVertex2f(bbx+bbwidth+sw, bby-swon2);
	  glVertex2f(bbx+bbwidth+sw, bby+bbheight+sw);
	  glEnd();
	  glinfo->stencilEnableTop();
	}
	glinfo->alpha = opacity;
	multiPassManager.pop(glinfo);
	glinfo->alpha = alpha_save;

      }
    }

  }
コード例 #13
0
ファイル: SVGStylable.cpp プロジェクト: CaptEmulation/svgl
  void
  SVGStylable::glTraverse(svgl::Context * svglContext,
			  svgl::GLInfo* glinfo,
			  bool stencilStrokeHint,
			  bool traverseEvenIfNonVisible)
  {

    const css::CSSStyleDeclaration& style = GET_SIMPLE_VAL(Style);

    const css::Color * fill = style.getFill();
    const css::Color * stroke = style.getStroke();
    float fillOpacity = style.getFillOpacity();
    float strokeOpacity = style.getStrokeOpacity();
    float opacity = style.getOpacity();
    svg::SVGLength strokeWidth = style.getStrokeWidth();
    float sw = svglContext->computeWidthLength(strokeWidth);
    css::CSSStyle::DisplayType display = style.getDisplay();
		
		//FIXME
    if(fill==css::Color::getNoneColor())
      fill = 0; // as if it wasn't there...
    if(stroke==css::Color::getNoneColor())
      stroke = 0; // as if it wasn't there...

    if(!display) {
      return;
    }

		computeGeometryForDrawing(svglContext,glinfo);
		
    SVGElement * meAsElement = dynamic_cast<SVGElement*>(this);
    dom::Document * currentDoc = meAsElement->getOwnerDocument();

    svg::SVGClipPathElement *clippath_element=0;
    clippath_element = getSVGClipPathElement(svglContext->externalEntityManager, currentDoc);
    if(clippath_element) {
      clippath_element->glPreTraverse(svglContext, glinfo);
    }

    SVGFilterElement* filter_element = 0;
#if 1
    filter_element = getSVGFilterElement(svglContext->externalEntityManager, currentDoc);
    if(filter_element)
      filter_element->glPreTraverse(svglContext, glinfo, dynamic_cast<SVGElement*>(this));
#endif

    if(fill && stroke && opacity<1) {
      glTraverseOpacity(svglContext,
			glinfo,
			fill,
			stroke,
			fillOpacity,
			strokeOpacity,
			opacity,
			sw,
			stencilStrokeHint
			//,
			//bbx,bby,bbwidth,bbheight
			);
    }
    else {
      float alpha_save = glinfo->alpha;
      glinfo->alpha *= opacity;

#define AA 1

#if AA
//#define AA_PRIMITIVE GL_POLYGON_SMOOTH
//#define AA_PRIMITIVE GL_MULTISAMPLE_ARB
#define AA_PRIMITIVE glinfo->aa_primitive
#define AA_PRIMITIVE_HINT GL_POLYGON_SMOOTH_HINT
#endif

      if(fill) {
	float alpha_save = glinfo->alpha;
	glinfo->alpha *= fillOpacity;

	fill->glPreTraverse(svglContext, glinfo, this);
	if(!stroke && glinfo->doAntiAliasing()) {
	  bool opaque = false;
	  if(glinfo->alpha==1) opaque = true;
	  glinfo->enableAntiAliasing(opaque);
	}

	glTraverseFill(svglContext, glinfo);
	fill->glPostTraverse(svglContext, glinfo, this);

	if(!stroke && glinfo->doAntiAliasing()) {
	  glinfo->disableAntiAliasing();
	}
	glinfo->alpha = alpha_save;
      }

      if(stroke && sw > 0) {
	float alpha_save = glinfo->alpha;
	float swon2 = sw/2.;
	float bbx,bby,bbwidth,bbheight;

	stencilStrokeHint=1;
	if(stencilStrokeHint && strokeOpacity<1) {
	  // since stroke pathes may recover themselves (think "8") , we must use stencil
#if 1
	  glinfo->stencilEnableTopAndPush();
#else
	  glinfo->stencilEnableTest();
	  int& stencil = glinfo->stencil;
	  glStencilFunc(GL_EQUAL, stencil, static_cast<GLuint>(-1));
	  glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
	  ++stencil;
#endif
	}

	glinfo->alpha *= strokeOpacity;
	stroke->glPreTraverse(svglContext, glinfo, this, sw);

	if(glinfo->doAntiAliasing()) {
	  bool opaque = false;
	  if(glinfo->alpha==1) opaque = true;
	  glinfo->enableAntiAliasing(opaque);
	}

	glTraverseStroke(svglContext, glinfo, sw);

	if(glinfo->doAntiAliasing()) {
	  glinfo->disableAntiAliasing();
	}

	// remove stencil
	if(stencilStrokeHint && strokeOpacity<1) {
	  // FIXME, not necessary if stroke is a gradient...
	  // not sure though...
	  getBoundingBox(svglContext, glinfo, &bbx, &bby, &bbwidth, &bbheight);
	  glinfo->stencilPop();
	  glBegin(GL_QUAD_STRIP);
	  glVertex2f(bbx-swon2,bby-swon2);
	  glVertex2f(bbx-swon2, bby+bbheight+sw);
	  glVertex2f(bbx+bbwidth+sw, bby-swon2);
	  glVertex2f(bbx+bbwidth+sw, bby+bbheight+sw);
	  glEnd();
	  glinfo->stencilEnableTop();
	}

	stroke->glPostTraverse(svglContext, glinfo, this, sw);
	glinfo->alpha = alpha_save;
	
	

#if AA
#undef AA_PRIMITIVE
#undef AA_PRIMITIVE_HINT
#undef AA
#endif
      }

      glinfo->alpha = alpha_save;
    }

    SVGStylable::glTraverseMarker(svglContext, glinfo, sw);

    if(filter_element) {
      filter_element->glPostTraverse(svglContext, glinfo, dynamic_cast<SVGElement*>(this));
    }

    if(clippath_element) {
      clippath_element->glPostTraverse(svglContext, glinfo);
    }

#if 0
		// draw bbox
		//if(glinfo->_has_GL_ARB_imaging) {
		if(1) {
			float swon2 = sw/2.;
			float bbx,bby,bbwidth,bbheight;
			getBoundingBox(svglContext, glinfo, &bbx, &bby, &bbwidth, &bbheight);

			glinfo->stencilDisableTest();
			glColor4d(0,0,0,1);
			glBegin(GL_LINE_LOOP);
			glVertex2f(bbx-swon2,bby-swon2);
			glVertex2f(bbx-swon2, bby+bbheight+swon2);
			glVertex2f(bbx+bbwidth+swon2, bby+bbheight+swon2);
			glVertex2f(bbx+bbwidth+swon2, bby-swon2);
			glEnd();
			glinfo->stencilEnableTest();
		}
		// --
#endif
		

  }
コード例 #14
0
ファイル: SvgPolygon.cpp プロジェクト: GiulioGx/Marinajo
SvgPoint& SvgPolygon::getBarycenter() {
	getBoundingBox();
	return this->boundingBoxPtr->getCenter();
}
コード例 #15
0
/**
 * A map detector ID and Q ranges
 * This method looks unnecessary as it could be calculated on the fly but
 * the parallelization means that lazy instantation slows it down due to the
 * necessary CRITICAL sections required to update the cache. The Q range
 * values are required very frequently so the total time is more than
 * offset by this precaching step
 */
DetectorAngularCache initAngularCaches(const MatrixWorkspace *const workspace) {
  const size_t nhist = workspace->getNumberHistograms();
  std::vector<double> thetas(nhist);
  std::vector<double> thetaWidths(nhist);
  std::vector<double> detectorHeights(nhist);

  auto inst = workspace->getInstrument();
  const auto samplePos = inst->getSample()->getPos();
  const V3D upDirVec = inst->getReferenceFrame()->vecPointingUp();

  for (size_t i = 0; i < nhist; ++i) // signed for OpenMP
  {
    IDetector_const_sptr det;
    try {
      det = workspace->getDetector(i);
    } catch (Exception::NotFoundError &) {
      // Catch if no detector. Next line tests whether this happened - test
      // placed
      // outside here because Mac Intel compiler doesn't like 'continue' in a
      // catch
      // in an openmp block.
    }
    // If no detector found, skip onto the next spectrum
    if (!det || det->isMonitor()) {
      thetas[i] = -1.0; // Indicates a detector to skip
      thetaWidths[i] = -1.0;
      continue;
    }
    // We have to convert theta from radians to degrees
    const double theta = workspace->detectorSignedTwoTheta(*det) * rad2deg;
    thetas[i] = theta;
    /**
     * Determine width from shape geometry. A group is assumed to contain
     * detectors with the same shape & r, theta value, i.e. a ring mapped-group
     * The shape is retrieved and rotated to match the rotation of the detector.
     * The angular width is computed using the l2 distance from the sample
     */
    if (auto group = boost::dynamic_pointer_cast<const DetectorGroup>(det)) {
      // assume they all have same shape and same r,theta
      auto dets = group->getDetectors();
      det = dets[0];
    }
    const auto pos = det->getPos() - samplePos;
    double l2(0.0), t(0.0), p(0.0);
    pos.getSpherical(l2, t, p);
    // Get the shape
    auto shape =
        det->shape(); // Defined in its own reference frame with centre at 0,0,0
    BoundingBox bbox = shape->getBoundingBox();
    auto maxPoint(bbox.maxPoint());
    auto minPoint(bbox.minPoint());
    auto span = maxPoint - minPoint;
    detectorHeights[i] = span.scalar_prod(upDirVec);
    thetaWidths[i] = 2.0 * std::fabs(std::atan((detectorHeights[i] / 2) / l2)) *
                     180.0 / M_PI;
  }
  DetectorAngularCache cache;
  cache.thetas = thetas;
  cache.thetaWidths = thetaWidths;
  cache.detectorHeights = detectorHeights;
  return cache;
}
コード例 #16
0
void MainAxisPCA::computeMainAxis(const std::vector<ml::vec3>& pointCloud)
{
    ML_TRACE_IN("void MainAxisPCA::computeMainAxis()");

    float** covaMatrix = matrix(1,3,1,3);
    float** jacobiMat  = matrix(1,3,1,3);
    float** invMatrix  = matrix(1,3,1,3);
    float*  eigenValues = vL_vector(1,3);
    
    const int size = static_cast<int>( pointCloud.size() );
    
    // copy positions to vertices
    float* vertices = NULL;
    ML_CHECK_NEW(vertices, float[size * 3]);

    unsigned int i=0;
    unsigned int entry = 0;

    for (i = 0; i < size; i++){

        const ml::vec3& currPos = pointCloud[i];

        vertices[entry++] = static_cast<float>(currPos[0]);
        vertices[entry++] = static_cast<float>(currPos[1]);
        vertices[entry++] = static_cast<float>(currPos[2]);
    }
    
    // Calculate center of mass
    ML_DELETE_ARR(_baryCenter);
    _baryCenter = calcBaryCenter(vertices, size);
    
    // Compute covariant matrix, so the Jacobian matrix can be computed
    getCovarianceMatrix(vertices, static_cast<long int>(size), covaMatrix, _baryCenter);
    
    // Compute the Jacobian matrix
    int nrot=0; // dummy variable
    jacobi(covaMatrix, 3, eigenValues, jacobiMat, &nrot);
    
    // Calculate main axes
    unsigned int counter=0;
    for (counter = 0; counter < 3; counter++) {
        _xAxis[counter] = jacobiMat[counter + 1][1];
        _yAxis[counter] = jacobiMat[counter + 1][2];
        _zAxis[counter] = jacobiMat[counter + 1][3];
    }
    
    // Multiply each point by the eigenvectors of the Jacobian matrix
    const float* points = vertices;
    float* newVertices  =  NULL;
    ML_CHECK_NEW(newVertices, float[size * 3]);

    unsigned int counter2 = 0;
    for (counter = 0; counter < size; counter++) {
        
        newVertices[counter2++] = dotProduct(points, _xAxis); //tempPoint.dot(_xAxis);
        newVertices[counter2++] = dotProduct(points, _yAxis); //tempPoint.dot(_yAxis);
        newVertices[counter2++] = dotProduct(points, _zAxis); //tempPoint.dot(_zAxis);
        points += 3;
    }
    
    // Get extends of the bounding box
    float minX=0, maxX=0, minY=0, maxY=0, minZ=0, maxZ=0;
    getBoundingBox(newVertices, static_cast<long int>(size), minX, maxX, minY, maxY, minZ, maxZ);
    
    // Extends of the object aligned bounding box
    _xDiameter = maxX - minX;
    _yDiameter = maxY - minY;
    _zDiameter = maxZ - minZ;
    
    // Half the extend...
    float half_x = _xDiameter / 2.0f;
    float half_y = _yDiameter / 2.0f;
    float half_z = _zDiameter / 2.0f;
    
    // Rotate all points back by multiplying them with the inverse Jacobian matrix.
    getInverseMatrix(jacobiMat, invMatrix);
    
    float* tmp = stretchVector(_xAxis, half_x);  
    for (counter = 0; counter < 3; counter++) {  
        _midPoint[counter] =  
            minX           * invMatrix[1][counter + 1] + 
           (minY + half_y) * invMatrix[2][counter + 1] + 
           (minZ + half_z) * invMatrix[3][counter + 1] + tmp[counter];
    }
    
    ML_DELETE_ARR(tmp);
    ML_DELETE_ARR(newVertices);
    ML_DELETE_ARR(vertices);
    
    free_matrix(covaMatrix, 1, 3, 1, 3);
    free_matrix(jacobiMat,  1, 3, 1, 3);
    free_matrix(invMatrix,  1, 3, 1, 3);
    free(eigenValues);
}
コード例 #17
0
void LeapOfFaithSpell::updateParticleSystemPosition() {
	if (m_pointGenerator == nullptr) return;
	m_pointGenerator->center.x = getPosition().x + getBoundingBox()->width / 2;
	m_pointGenerator->center.y = getPosition().y + getBoundingBox()->height / 2;
}
コード例 #18
0
ファイル: button.cpp プロジェクト: zephyrz4/pongGame
std::vector<SDL_Rect> button::getBox() {

	return getBoundingBox();
}
コード例 #19
0
ファイル: textlocation.cpp プロジェクト: browny/invoiceq-core
bool TextLocation::locateRecogBox() {

    // Verify edgeAndBlack image
    int clusterNum = 0;
    CvRect box;
    bool havebox = getBoundingBox(m_edgeAndBlackImg, clusterNum, box);
    if (havebox)
        checkBox(m_edgeAndBlackImg, box);

    // Draw boxes
    /*for (unsigned int i = 0; i < boxes.size(); ++i) {
      cvRectangle(
      outImg,
      cvPoint(boxes[i].x, boxes[i].y),
      cvPoint(boxes[i].x + boxes[i].width,
      boxes[i].y + boxes[i].height), CV_RGB(255, 0, 255), 3);
      }*/

    CvRect verifiedBox = cvRect(0, 0, 0, 0);

    bool edgeAndBlackGood = verifyBox(m_edgeAndBlackImg, clusterNum, box, verifiedBox);

    /*if (edgeAndBlackGood) {
      cvRectangle(
      outImg,
      cvPoint(verifiedBox.x, verifiedBox.y),
      cvPoint(verifiedBox.x + verifiedBox.width,
      verifiedBox.y + verifiedBox.height), CV_RGB(255, 0, 255), 3);
      }*/


    // Verify edge image
    int clusterNum2 = 0;
    CvRect box2;

    bool edgeGood = false;
    CvRect verifiedBox2 = cvRect(0, 0, 0, 0);

    if (thrImgMode == ADVANCED_EDGE) {

        bool havebox = getBoundingBox(m_advancedEdgeImg, clusterNum2, box2);

        if (havebox)
            checkBox(m_advancedEdgeImg, box2);

        edgeGood = verifyBox(m_advancedEdgeImg, clusterNum2, box2, verifiedBox2);

    }
    else if (thrImgMode == SIMPLE_EDGE) {

        bool havebox = getBoundingBox(m_simpleEdgeImg, clusterNum2, box2);

        if (havebox)
            checkBox(m_simpleEdgeImg, box2);

        edgeGood = verifyBox(m_simpleEdgeImg, clusterNum2, box2, verifiedBox2);
    }

    // Draw boxes2
    /*for (unsigned int i = 0; i < boxes2.size(); ++i) {
      cvRectangle(
      outImg,
      cvPoint(boxes2[i].x, boxes2[i].y),
      cvPoint(boxes2[i].x + boxes2[i].width,
      boxes2[i].y + boxes2[i].height), CV_RGB(0, 255, 255), 1);
      }*/

    /*if (edgeGood) {
      cvRectangle(
      outImg,
      cvPoint(verifiedBox2.x, verifiedBox2.y),
      cvPoint(verifiedBox2.x + verifiedBox2.width,
      verifiedBox2.y + verifiedBox2.height),
      CV_RGB(0, 255, 255), 3);
      }*/

    if (edgeAndBlackGood) {

        vector<int> segLines(0);
        getSegLines(m_edgeAndBlackImg, verifiedBox, segLines);
        getSegRects(m_edgeAndBlackImg, segLines, verifiedBox, this->segRects);

        return true;

    }
    else if (edgeGood) {

        if (thrImgMode == ADVANCED_EDGE) {

            vector<int> segLines(0);
            getSegLines(m_advancedEdgeImg, verifiedBox2, segLines);
            getSegRects(m_advancedEdgeImg, segLines, verifiedBox2,
                    this->segRects);

        } else if (thrImgMode == SIMPLE_EDGE) {

            vector<int> segLines(0);
            getSegLines(m_simpleEdgeImg, verifiedBox2, segLines);
            getSegRects(m_simpleEdgeImg, segLines, verifiedBox2, this->segRects);

        }

        return true;

    }
    else
        return false;

}
コード例 #20
0
ファイル: Quad.cpp プロジェクト: NUbots/NUbots
 arma::vec2 Quad::getSize() const {
     Quad boundingBox = getBoundingBox(getVertices());
     return {boundingBox.getAverageWidth(), boundingBox.getAverageHeight()};
 }
コード例 #21
0
ファイル: Cylinder.cpp プロジェクト: chazmatazz/nestk
XnBool Cylinder::isInside(XnPoint3D p) {
    return inBoundingBox(p, getBoundingBox());
}
コード例 #22
0
//----------------------------------------
void ofxBox2dPolygon::updateShape() {
	
	calculateArea();
	calculateCentroid();
	bounds = getBoundingBox();
}
コード例 #23
0
ファイル: Toggle.cpp プロジェクト: gdevillele/pxlframework
		// @todo industrialize with Button::onTouch()
		bool Toggle::onTouch( TouchEvent event )
		{
			// if the Toggle is disabled
			// we ignore this touch event
			if( _state == State::DISABLED )
			{
				return false;
			}
			
			// if the touch event is a CANCEL event
			// we just release the Toggle and return
			// without consuming the touch event
			if (event.getType() == TouchEvent::Type::CANCEL)
			{
				release();
				return false;
			}
			
			bool result = false;
			
			// get event data
			const TouchEvent::Type eventType = event.getType();
			const float eventX = event.getX();
			const float eventY = event.getY();
			
			// get this Toggle's bounding box
			px::tools::Rect bb = getBoundingBox();
			
			// add the GUI touch margin to the bounding box
            
			bb.setX(bb.getX() - guiButtonTouchMargin);
			bb.setY(bb.getY() - guiButtonTouchMargin);
			bb.setWidth(bb.getWidth() + 2*guiButtonTouchMargin);
			bb.setHeight(bb.getHeight() + 2*guiButtonTouchMargin);
			
			// test if touch event is on the Toggle
			if(eventX > bb.getX() && eventX < bb.getX()+bb.getWidth() &&
			   eventY > bb.getY() && eventY < bb.getY()+bb.getHeight())
			{
				// event is on the Toggle
				// in this case we test only touch DOWN and UP
				if( eventType == TouchEvent::Type::DOWN )
				{
					// we push the Toggle
					press();
					// we consume the touch event
					result = true;
				}
				else if( eventType == TouchEvent::Type::UP )
				{
					// Toggle receives a touch up event on it
					// but it may be not pushed at this time
					// if it was pushed, it's a click action
					// if it wasn't it does nothing
					if( _state == State::PRESSED )
					{
						if(_on)
							setOff();
						else
							setOn();
						// this is a click action
						clickCallback();
						// we consume the touch event
						result = true;
					}
					// in both cases, Toggle isn't pushed anymore
					release();
				}
			}
			else
			{
				// event is not on this Toggle object
				if( eventType == TouchEvent::Type::UP )
				{
					// Toggle is no more down, it's a click cancel action
					// PXLLOG("Toggle touch UP cancel");
					release();
					// we do not consume this event because it wasn't on the Toggle
				}
			}
			return result;
		}
コード例 #24
0
ファイル: Player.cpp プロジェクト: P1CACHU/Platform
Rect Player::collisionBoundingBox()
{
	return getBoundingBox();
}
コード例 #25
0
/**
 * \return A polygon that contains this entity.
 * Default implementation returns a polygon around the bounding box.
 */
RPolyline REntityData::getHull(double offset) const {
    RBox bb = getBoundingBox();
    bb.grow(offset);
    return bb.getPolyline2d();
}
コード例 #26
0
ファイル: TileMapScene.cpp プロジェクト: wayonglee/tilemap
void TileMapScene::onTouchesMoved(const std::vector<Touch*>& touches,Event* pEvent)
{
	auto visibleSize = Director::getInstance()->getVisibleSize();
	if(touches.size()==1)
	{
		auto point = touches[0]->getLocation();
		auto prePoint = touches[0]->getPreviousLocation();
		auto offSetX = point.x-prePoint.x;
		auto offSetY = point.y-prePoint.y;
		auto map = (TMXTiledMap*)this->getChildByTag(1);
		auto player = (Sprite*)this->getChildByTag(2);
		map->setPosition(Vec2(map->getPosition().x+offSetX,map->getPosition().y+offSetY));
		player->setPosition(Vec2(player->getPosition().x+offSetX,player->getPosition().y+offSetY));
		bgOrigin = Vec2(bgOrigin.x+offSetX,bgOrigin.y+offSetY);

		if(bgOrigin.x>0)//·ÀÖ¹³öÏÖºÚ±ß
		{
			map->setPosition(Vec2(map->getPosition().x-bgOrigin.x,map->getPosition().y));
			player->setPosition(Vec2(player->getPosition().x-bgOrigin.x,player->getPosition().y));
			bgOrigin.x = 0;
		}
		if(bgOrigin.y>0)
		{
			map->setPosition(Vec2(map->getPosition().x,map->getPosition().y-bgOrigin.y));
			player->setPosition(Vec2(player->getPosition().x,player->getPosition().y-bgOrigin.y));
			bgOrigin.y = 0;
		}
		if(bgOrigin.x < visibleSize.width - map->getBoundingBox().size.width)
		{
			map->setPosition(Vec2(map->getPosition().x+visibleSize.width - map->getBoundingBox().size.width - bgOrigin.x,map->getPosition().y));
			player->setPosition(Vec2(player->getPosition().x+visibleSize.width - map->getBoundingBox().size.width - bgOrigin.x,player->getPosition().y));
			bgOrigin.x = visibleSize.width - map->getBoundingBox().size.width;
		}
		if(bgOrigin.y < visibleSize.height - map->getBoundingBox().size.height)
		{
			map->setPosition(Vec2(map->getPosition().x,map->getPosition().y+visibleSize.height - map->getBoundingBox().size.height - bgOrigin.y));
			player->setPosition(Vec2(player->getPosition().x,player->getPosition().y+visibleSize.height - map->getBoundingBox().size.height - bgOrigin.y));
			bgOrigin.y = visibleSize.height - map->getBoundingBox().size.height;
		}
	}
	if(touches.size()>1&&1==0)//Ëõ·Å
	{
		auto visibleSize = Director::getInstance()->getVisibleSize();
		auto map = (TMXTiledMap*)this->getChildByTag(1);
		auto p1 = touches[0]->getLocation();
		auto p2 = touches[1]->getLocation();
		auto pp1 = touches[0]->getPreviousLocation();
		auto pp2 = touches[1]->getPreviousLocation();
		auto curDistance = p1.distance(p2);
		auto preDistance = pp1.distance(pp2);

		auto midX = (p1.x+p2.x)/2;
		auto midY = (p1.y+p2.y)/2;
		auto realMidX = midX - bgOrigin.x;
		auto realMidY = midY - bgOrigin.y;
		map->setAnchorPoint(Vec2(realMidX/map->getBoundingBox().size.width,realMidY/map->getBoundingBox().size.height));
		map->setPosition(midX,midY);
		auto scale = map->getScale()*curDistance/preDistance;
		map->setScale(scale);
		bgOrigin = Vec2(midX-map->getBoundingBox().size.width*map->getAnchorPoint().x,midY-map->getBoundingBox().size.height*map->getAnchorPoint().y);
	}
}
コード例 #27
0
    void WeHaveAWinnerWidget::updateBoundingBox()
    {
        m_particleSource->setBoundingBox(m_boundingBox);
        m_victoryImage->setPosition(getBoundingBox().x + getBoundingBox().w / 2 - m_victoryImage->getBoundingBox().w / 2,
                                    10);

        m_playerNameLabel->setPosition(getBoundingBox().x + getBoundingBox().w / 2 - m_playerNameLabel->getBoundingBox().w / 2,
                                              getBoundingBox().y + getBoundingBox().h / 2 - getBoundingBox().y / 4 - m_playerNameLabel->getBoundingBox().h / 2);
        m_playerNameDisplayLabel->setPosition(getBoundingBox().x + getBoundingBox().w / 2 - m_playerNameDisplayLabel->getBoundingBox().w / 2,
                                       getBoundingBox().h / 4 * 3 - m_playerNameDisplayLabel->getBoundingBox().h / 2);

        m_particleSource->setXStartRange(getBoundingBox().w / 6 * 2, getBoundingBox().w / 6 * 4);
        m_particleSource->setYStartRange(getBoundingBox().y + getBoundingBox().h, getBoundingBox().y + getBoundingBox().h + 100);

        //Set the target count relative to the screen size. (Equals to 80 particles at 800x600)
        m_particleSource->setTargetCount(getBoundingBox().w * getBoundingBox().h / 6000);
    }
コード例 #28
0
ファイル: grid_projection.hpp プロジェクト: 9gel/hellopcl
template <typename PointNT> bool
pcl::GridProjection<PointNT>::reconstructPolygons (std::vector<pcl::Vertices> &polygons)
{
  data_.reset (new pcl::PointCloud<PointNT> (*input_));
  getBoundingBox ();

  // Store the point cloud data into the voxel grid, and at the same time
  // create a hash map to store the information for each cell
  cell_hash_map_.max_load_factor (2.0);
  cell_hash_map_.rehash (data_->points.size () / static_cast<long unsigned int> (cell_hash_map_.max_load_factor ()));

  // Go over all points and insert them into the right leaf
  for (int cp = 0; cp < static_cast<int> (data_->points.size ()); ++cp)
  {
    // Check if the point is invalid
    if (!pcl_isfinite (data_->points[cp].x) ||
        !pcl_isfinite (data_->points[cp].y) ||
        !pcl_isfinite (data_->points[cp].z))
      continue;

    Eigen::Vector3i index_3d;
    getCellIndex (data_->points[cp].getVector4fMap (), index_3d);
    int index_1d = getIndexIn1D (index_3d);
    if (cell_hash_map_.find (index_1d) == cell_hash_map_.end ())
    {
      Leaf cell_data;
      cell_data.data_indices.push_back (cp);
      getCellCenterFromIndex (index_3d, cell_data.pt_on_surface);
      cell_hash_map_[index_1d] = cell_data;
      occupied_cell_list_[index_1d] = 1;
    }
    else
    {
      Leaf cell_data = cell_hash_map_.at (index_1d);
      cell_data.data_indices.push_back (cp);
      cell_hash_map_[index_1d] = cell_data;
    }
  }

  Eigen::Vector3i index;
  int numOfFilledPad = 0;

  for (int i = 0; i < data_size_; ++i)
  {
    for (int j = 0; j < data_size_; ++j)
    {
      for (int k = 0; k < data_size_; ++k)
      {
        index[0] = i;
        index[1] = j;
        index[2] = k;
        if (occupied_cell_list_[getIndexIn1D (index)])
        {
          fillPad (index);
          numOfFilledPad++;
        }
      }
    }
  }

  // Update the hashtable and store the vector and point
  BOOST_FOREACH (typename HashMap::value_type entry, cell_hash_map_)
  {
    getIndexIn3D (entry.first, index);
    std::vector <int> pt_union_indices;
    getDataPtsUnion (index, pt_union_indices);

    // Needs at least 10 points (?)
    // NOTE: set as parameter later
    if (pt_union_indices.size () > 10)
    {
      storeVectAndSurfacePoint (entry.first, index, pt_union_indices, entry.second);
      //storeVectAndSurfacePointKNN(entry.first, index, entry.second);
      occupied_cell_list_[entry.first] = 1;
    }
  }
コード例 #29
0
bool parentMode::init()
{
	if (!Layer::init())
	{
		return false;
	}

	visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();
	dispatcher = Director::getInstance()->getEventDispatcher();

	
	//log("%s", FileUtils::getInstance()->getWritablePath().c_str());
	//auto path = FileUtils::getInstance()->getWritablePath() + "/UserDefault.xml";

	auto background = Sprite::create("parent_read/login.png");
	float x = visibleSize.width / background->getContentSize().width;
	float y = visibleSize.height / background->getContentSize().height;
	background->setScale(x, y);
	background->setAnchorPoint(Vec2::ZERO);
	background->setPosition(Vec2::ZERO);
	this->addChild(background);

	taglabel = Sprite::create("parentmode/11.png");
	float xx = visibleSize.width / taglabel->getContentSize().width;
	float yy = visibleSize.height / taglabel->getContentSize().height;
	taglabel->setScale(xx/2,yy);
	taglabel->setAnchorPoint(Vec2::ZERO);
	taglabel->setPosition(Vec2::ZERO);
	this->addChild(taglabel);



	auto panel = Sprite::create("parentmode/11.png");
	panel->setPosition(visibleSize.width / 5 * 3, visibleSize.height / 2);

	auto label2 = Label::createWithTTF("选择家长", "fonts/my_font3.ttf", 24);
	label2->setPosition(Vec2(panel->getPosition().x-panel->getContentSize().width/1.7+label2->getContentSize().width, panel->getPosition().y+panel->getContentSize().height/3));
	this->addChild(label2, 1);
	label2->setVisible(false);

	//auto label3 = Label::createWithTTF("联系方式", "fonts/my_font3.ttf", 24);
	//label3->setPosition(Vec2(panel->getPosition().x - panel->getContentSize().width / 1.7 + label2->getContentSize().width, panel->getPosition().y + panel->getContentSize().height / 12));
	//this->addChild(label3, 3);

	//auto label4 = Label::createWithTTF("家庭住址", "fonts/my_font3.ttf", 24);
	//label4->setPosition(Vec2(panel->getPosition().x - panel->getContentSize().width / 1.7 + label2->getContentSize().width, panel->getPosition().y-panel->getContentSize().height / 6));
	//this->addChild(label4, 3);

	auto level_1 = MenuItemImage::create(
		"my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::Level_1, this));
	auto menuWidth = visibleSize.width / 38 * 4.6;
	auto menuHeight = visibleSize.height / 19 * 2;
	level_1->setScale(menuWidth / level_1->getContentSize().width, menuHeight / level_1->getContentSize().height);
	//creat Level_2
	auto level_2 = MenuItemImage::create(
		"my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::Level_1, this));
	level_2->setEnabled(false);

	auto menu = Menu::create(level_1, NULL);
	menu->alignItemsHorizontallyWithPadding(level_1->getContentSize().width);
	menu->setPosition(Vec2(visibleSize.width/38*20.72,visibleSize.height/19*2.95));
	this->addChild(menu, 3);

	auto close_item = MenuItemImage::create("CloseNormal.png",
		"CloseSelected.png",
		CC_CALLBACK_1(parentMode::menuCloseCallback,
		this));
	close_item->setPosition(
		Vec2(origin.x + visibleSize.width - close_item->getContentSize().width / 2,
		origin.y + close_item->getContentSize().height / 2));
	// create menu, it's an autorelease object
	auto mymenu = Menu::create(close_item, NULL);
	mymenu->setPosition(Vec2::ZERO);
	this->addChild(mymenu, 1);
	/////////////////////////////
	// 3. add your codes below...

	// add a label shows "Hello World"
	// create and initialize a label

	//创建一个label作为下拉菜单的默认选项
	auto label = Label::createWithTTF("妈妈",
		"fonts/my_font3.ttf",
		36);
	label->setColor(Color3B::BLACK);
	label->setTextColor(Color4B::BLACK);
	//设置大小
	auto box_size = Size(visibleSize.width/38*5.15,
		visibleSize.height/19*1.05);

	//
	list_box = CustomDropDownListBox::DropDownList::Create(label,
		box_size,
		Size(visibleSize.width / 38 * 5.15,
		visibleSize.height / 19 * 1.05));


	//添加一堆label进去
	CCDictionary *strings = CCDictionary::createWithContentsOfFile("fonts/chinese.xml");
	const char *charchinese = ((CCString*)strings->objectForKey("parent1"))->getCString();
	auto labell0 = Label::create(charchinese, "Arial", 18);
	labell0->setColor(Color3B::BLACK);
	//auto labell0 = Label::createWithTTF();
	list_box->AddLabel(labell0);//不知道怎么把默认显示的label添加到选项里,只好再添加一个

	CCDictionary *strings1 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml");
	const char *charchinese1 = ((CCString*)strings1->objectForKey("parent2"))->getCString();
	auto labell1 = Label::create(charchinese1, "Arial", 18);
	labell1->setColor(Color3B::BLACK);
	list_box->AddLabel(labell1);

	CCDictionary *strings2 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml");
	const char *charchinese2 = ((CCString*)strings2->objectForKey("parent3"))->getCString();
	auto labell2 = Label::create(charchinese2, "Arial", 18);
	labell2->setColor(Color3B::BLACK);
	list_box->AddLabel(labell2);
	
	CCDictionary *strings3 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml");
	const char *charchinese3 = ((CCString*)strings3->objectForKey("parent4"))->getCString();
	auto labell3 = Label::create(charchinese3, "Arial", 18);
	labell3->setColor(Color3B::BLACK);
	list_box->AddLabel(labell3);

	CCDictionary *strings4 = CCDictionary::createWithContentsOfFile("fonts/chinese.xml");
	const char *charchinese4 = ((CCString*)strings4->objectForKey("parent5"))->getCString();
	auto labell4 = Label::create(charchinese4, "Arial", 18);
	labell4->setColor(Color3B::BLACK);
	list_box->AddLabel(labell4);

	// 设置位置
	list_box->setPosition(
		Vec2(visibleSize.width/38*14.45, 
		visibleSize.height/19*13.85));
	this->addChild(list_box,
		4);
	//启动监听
	list_box->OpenListener();

	testTouchEvent();



	/*auto timesetLabel = MenuItemImage::create(
		"my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::timeset, this));
	auto timesetmenu = Menu::create(timesetLabel, NULL);
	timesetmenu->alignItemsHorizontallyWithPadding(timesetLabel->getContentSize().width / 3 * 2);
	timesetmenu->setPosition(Vec2(100, visibleSize.height / 4 * 3));
	this->addChild(timesetmenu, 3);

	auto messagelabel = MenuItemImage::create(
		"my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::message, this));
	auto messagemenu = Menu::create(messagelabel, NULL);
	messagemenu->alignItemsHorizontallyWithPadding(messagelabel->getContentSize().width / 3 * 2);
	messagemenu->setPosition(Vec2(100, visibleSize.height / 4 * 2));
	this->addChild(messagemenu, 3);

	auto parentstudylabel = MenuItemImage::create(
		"my_button.png", "my_button3.png", "my_button2.png", CC_CALLBACK_1(parentMode::parentstudy, this));
	auto parentstudymenu = Menu::create(parentstudylabel, NULL);
	parentstudymenu->alignItemsHorizontallyWithPadding(parentstudylabel->getContentSize().width / 3 * 2);
	parentstudymenu->setPosition(Vec2(100, visibleSize.height / 4));
	this->addChild(parentstudymenu, 3);*/



	auto back = MenuItemImage::create("timeset/back.png", "timeset/back.png", CC_CALLBACK_1(parentMode::returnto, this));
	back->setScale(0.2*visibleSize.height/back->getContentSize().height);
	auto back_menu = Menu::create(back, NULL);
	back_menu->setPosition(Vec2(back->getBoundingBox().size.width/2, visibleSize.height - back->getBoundingBox().size.height/2));
	this->addChild(back_menu, 3);

	//CCDictionary *xmlstrings = CCDictionary::createWithContentsOfFile(path.c_str());
	if (!database->getBoolForKey("isExist")){
		database->setBoolForKey("isExist", true);
		database->setStringForKey("babyName", "Child's name");
		database->setStringForKey("telNumber", "Tel number");
		database->setStringForKey("address", "Address");
		database->setStringForKey("password", "Password");
		database->setIntegerForKey("indexs", 0);
	}

	list_box->SetSelectedIndex(database->getIntegerForKey("indexs"));

	auto childname = database->getStringForKey("babyName");
	textEdit = TextFieldTTF::textFieldWithPlaceHolder(childname, "fonts/arial.ttf", 36);
	textEdit->setPosition(Vec2(visibleSize.width/38*27.95,visibleSize.height/19*14.35));
	this->addChild(textEdit, 10);
	setTouchMode(kCCTouchesOneByOne);
	setTouchEnabled(true);

	auto telNumber = database->getStringForKey("telNumber");
	textEdit2 = TextFieldTTF::textFieldWithPlaceHolder(telNumber, "fonts/arial.ttf", 36);
	textEdit2->setPosition(Vec2(visibleSize.width / 38 * 17.78, visibleSize.height / 19 * 10.79));
	this->addChild(textEdit2, 10);
	setTouchMode(kCCTouchesOneByOne);
	setTouchEnabled(true);

	auto address = database->getStringForKey("address");
	textEdit3 = TextFieldTTF::textFieldWithPlaceHolder(address, "fonts/arial.ttf", 36);
	textEdit3->setPosition(Vec2(visibleSize.width/38*20.58,visibleSize.height/19*6.85));
	this->addChild(textEdit3, 10);
	setTouchMode(kCCTouchesOneByOne);
	setTouchEnabled(true);

	auto password = database->getStringForKey("password");
	if (password != "Password") {
		for (int i = 0; i < password.length(); i++) {
			password.at(i) = '*';
		}
	}
	textEdit4 = TextFieldTTF::textFieldWithPlaceHolder(password, "fonts/arial.ttf", 36);
	textEdit4->setPosition(Vec2(visibleSize.width / 38 * 29.1, visibleSize.height / 19 * 10.79));
	this->addChild(textEdit4, 10);
	setTouchMode(kCCTouchesOneByOne);
	setTouchEnabled(true);

	return true;
}
コード例 #30
0
ファイル: Dragon.cpp プロジェクト: tieunun/Grow
bool Dragon::init(Item& item)
{
    bool result;
    if (ItemModel::init(item)) {
        
        setAnchorPoint(Vec2(145.0/382,196.0/413));
        if(_type == Dragon_Clockwise)
        {
            setAnchorPoint(Vec2(237.0/382,196.0/413));
        }
        std::string bodyFilename;
        std::string backFilename;
        int rotateDirection;
        float w = kDefaultDragonW;
        float backTransparency = kDefaultDragonBackTransparency;
        
        switch (_type) {
            case Dragon_Anti:
            {
                bodyFilename = "DragonTrunk_Anti.png";
                backFilename = "DragonBack_Anti.png";
                rotateDirection = -1;
            }
                break;
            case Dragon_Clockwise:
            {
                bodyFilename = "DragonTrunk_Clockwise.png";
                backFilename = "DragonBack_Clockwise.png";
                rotateDirection = 1;
            }
                break;
            default:
                return false;
        }
        
        if(item.features){
            Features_Dragon* features = (Features_Dragon*)item.features;
            w = features->w;
            backTransparency = features->backTransparency;
        }
        
        setTexture(bodyFilename);
        Sprite* dragonBack = Sprite::create(backFilename);
        dragonBack->setPosition(getBoundingBox().size.width/2,getBoundingBox().size.height/2);
        addChild(dragonBack);
        
        setRotation(CC_RADIANS_TO_DEGREES(item.angle));
        setScale(item.scale);
        
        ActionInterval* flickering = FadeTo::create(1,255*backTransparency);
        ActionInterval* flickering_reverse = FadeTo::create(1, 255);
        ActionInterval* sequence = Sequence::createWithTwoActions(flickering, flickering_reverse);
        dragonBack->runAction(RepeatForever::create(sequence));
        
        result = true;
    }else{
        result = false;
    }
    
    _collisionCallBack = std::bind(&Dragon::collisionWithPlant, this,std::placeholders::_1);
    return result;
}