Exemplo n.º 1
0
void TiledLayerChromium::prepareToUpdate(const IntRect& layerRect)
{
    m_skipsDraw = false;
    m_skipsIdlePaint = false;
    m_requestedUpdateTilesRect = IntRect();
    m_paintRect = IntRect();

    updateBounds();

    if (layerRect.isEmpty() || !m_tiler->numTiles())
        return;

    int left, top, right, bottom;
    m_tiler->layerRectToTileIndices(layerRect, left, top, right, bottom);

    prepareToUpdateTiles(false, left, top, right, bottom);
}
Exemplo n.º 2
0
void AcidDrop::update(float deltaTime)
{
	m_fStateTime += deltaTime;

	m_position->add(m_velocity->getX() * deltaTime, m_velocity->getY() * deltaTime);
	updateBounds();
	m_remove = ScreenUtils::isVectorOffScreen(*m_position);

	if (OverlapTester::isPointInRectangle(*m_position, *m_destinationBounds))
	{
		World::getInstance()->getToxicClouds().push_back(std::unique_ptr<ToxicCloud>(new ToxicCloud(m_destinationBounds->getLowerLeft().getX() + m_destinationBounds->getWidth() / 2, m_destinationBounds->getLowerLeft().getY() + m_destinationBounds->getHeight() / 2, m_fWidth / 2, m_fWidth * 3, m_fPoisonTime, m_fPoisonToCreepHealthRatio)));
        
        GameListener::getInstance()->playSound(SOUND_TOXIC_CLOUD);
        
		m_remove = true;
	}
}
Exemplo n.º 3
0
void RendererImplementationBase3D::applyCurrentCoordinateSystem(const CoordinateSystemSpecification & spec)
{
    const auto contents = renderView().visualizations();
    for (auto visualization : contents)
    {
        auto rendered = static_cast<RenderedData *>(visualization);
        rendered->setDefaultCoordinateSystem(spec);
    }

    updateAxisLabelFormat(spec);

    updateBounds();

    for (unsigned int i = 0; i < renderView().numberOfSubViews(); ++i)
    {
        resetCamera(true, i);
    }
}
Exemplo n.º 4
0
void EditorBuffer::draw(float x, float y, float w, float h) {
  ofPushMatrix();
  ofPushStyle();
  ofTranslate(x, y);
  
  // Need to calculate size of editor before drawing
  updateBounds();
  
  // Scale down if needed
  float scale = 1;
  if (bounds.width > 0 && bounds.height > 0) {
    scale = min(w / bounds.width, h / bounds.height);
    scale = min(scale, maxScale);
    scale = max(scale, minScale);
    ofScale(scale, scale);
  }
  
  // Move editor content if cursor is off screen
  float offsetY = (h / scale) - cursorPoint.y;
  if (offsetY < 0) {
    ofTranslate(0, offsetY);
  }
  float offsetX = (w / scale) - cursorPoint.x;
  if (offsetX < 0) {
    ofTranslate(offsetX, 0);
  }
  
  // Draw selected text highlight
  for (vector<ofTTFCharacter>::iterator i = shapes.begin(); i < shapes.end(); ++i) {
    (*i).draw();
  }

  // Draw text buffer content
  ofSetColor(textColor);
  drawStrings();
  

  // Draw cursor
  ofSetColor(cursorColor);
  ofRect(cursorPoint, 10, -lineHeight);

  ofPopStyle();
  ofPopMatrix();
}
Exemplo n.º 5
0
void Overlay::rebuildGeometry()
{
    Vector<Vector3> pos;
    Vector< Color > colors;

    pos.Push( Vector3(borderWidth, borderWidth, -0.1f) );
    pos.Push( Vector3(borderWidth, size.y-borderWidth, -0.1f) );
    pos.Push( Vector3(size.x-borderWidth, size.y-borderWidth, -0.1f) );
    pos.Push( Vector3(size.x-borderWidth, borderWidth, -0.1f) );

    Color color = backgroundColor;
    color.a = opacity;
    
    colors.Push(color);
    colors.Push(color);
    colors.Push(color);
    colors.Push(color);

    if( borderWidth > 0 )
    {
        pos.Push( Vector3(0, 0, -0.2f) );
        pos.Push( Vector3(0, size.y, -0.2f) );
        pos.Push( Vector3(size.x, size.y, -0.2f) );
        pos.Push( Vector3(size.x, 0, -0.2f) );
    
        color = borderColor;

        colors.Push(color);
        colors.Push(color);
        colors.Push(color);
        colors.Push(color);
    }

    GeometryBuffer* gb = renderable->getGeometryBuffer().get();
    
    gb->clear();
    gb->declarations.reset();

    gb->set( VertexAttribute::Position, pos );
    gb->set( VertexAttribute::Color, colors );

    updateBounds();
}
Exemplo n.º 6
0
	bool GUIWidget::isDirty(bool cleanIfDirty)
	{
		if (!mIsActive)
			return false;

		bool dirty = mWidgetIsDirty || mDirtyContents.size() > 0;

		if(cleanIfDirty && dirty)
		{
			mWidgetIsDirty = false;

			for (auto& dirtyElement : mDirtyContents)
				dirtyElement->_updateRenderElements();

			mDirtyContents.clear();
			updateBounds();
		}
		
		return dirty;
	}
Exemplo n.º 7
0
	void LinksPlayer::setPropertyValue(
			string name, string value, double duration, double by) {

		//TODO: set scrollbar, support...
		if (name == "transparency") {
			double val;

			val = stof(value);
			if (val >= 0.0 && val <= 1.0) {
				browserSetAlpha((int)(val * 0xFF), mBrowser);
			}

		} else if (name == "bounds") {
			int x, y, w, h;
			vector<string>* params;

			params = split(value, ",");
			if (params->size() != 4) {
				delete params;
				return;
			}

			x = (int)stof((*params)[0]);
			y = (int)stof((*params)[1]);
			w = (int)stof((*params)[2]);
			h = (int)stof((*params)[3]);

			delete params;

			if (!hasBrowser) {
				setBounds(x, y, w, h);

			} else {
				updateBounds(x, y, w, h);
			}

			return;
		}

		Player::setPropertyValue(name, value, duration, by);
	}
Exemplo n.º 8
0
void Form::update(float elapsedTime)
{
    if (isDirty())
    {
        updateBounds();

        // Cache themed attributes for performance.
        _skin = getSkin(_state);
        _opacity = getOpacity(_state);

        GP_ASSERT(_layout);
        if (_scroll != SCROLL_NONE)
        {
            updateScroll();
        }
        else
        {
            _layout->update(this, Vector2::zero());
        }
    }
}
Exemplo n.º 9
0
    bool CircleMesh::load(const float radius, int pointCount)
    {
        pointCount = std::max(3, pointCount);

        const float radians = glm::two_pi<float>() / pointCount;
        float theta = glm::half_pi<float>();

        std::vector<Vertex> vertexarray;
        vertexarray.reserve(pointCount + 1);

        vertexarray.emplace_back(glm::vec3(0.f, 0.f, 0.f), glm::vec2(0.5f, 0.5f), glm::vec3(0.f, 0.f, 1.f));

        for (int i = 0; i < pointCount; ++i)
        {
            vertexarray.emplace_back(glm::vec3(std::cos(theta) * radius, std::sin(theta) * radius, 0.f), glm::vec2(0.f), glm::vec3(0.f, 0.f, 1.f));

            vertexarray.back().texCoords.x = (vertexarray.back().position.x / radius + 1.f) * 0.5f;
            vertexarray.back().texCoords.y = 1.f - ((vertexarray.back().position.y / radius + 1.f) * 0.5f);

            theta += radians;
        }

        std::vector<unsigned int> indices;

        for (unsigned int i = 2; i < vertexarray.size(); ++i)
        {
            indices.push_back(0);
            indices.push_back(i - 1);
            indices.push_back(i);
        }
        indices.push_back(0);
        indices.push_back(vertexarray.size() - 1);
        indices.push_back(1);

        m_radius = radius;

        updateBounds(glm::vec3(-radius, -radius, 0.f), glm::vec3(radius, radius, 0.f));

        return Mesh::load(vertexarray, indices);
    }
Exemplo n.º 10
0
void MediaPlayer::update(){
    updateBounds();
    if (que.size() > 0){
        loadFromQue(queIndex);
    }else{
        if (groups.size() > 0){
            calculateDimensions();
            if (groups[groupIndex]->media.size() >= mediaIndex+1){
                manageLooping();
                timedelta = ofGetLastFrameTime();
                if (loopingIndex == 1){
                    if (groups[groupIndex]->media[mediaIndex]->getPosition() > .96){
                        cout << "media done";
                        switchMedia(1);
                    }
                }
                groups[groupIndex]->media[mediaIndex]->update();
            }
        }
    }

}
Exemplo n.º 11
0
void Model::build()
{
	if( modelBuilt ) return;

	MeshRenderablesMap::iterator it = meshRenderables.find(mesh);
	
	if( it == meshRenderables.end() )
	{
		RenderablesVector& rends = meshRenderables[mesh];
	
		if( !MeshBuild(mesh, rends) )
		{
			LogError("Error building mesh '%s'", mesh->getPath().c_str());
			return;
		}
	}

	RenderablesVector& rends = meshRenderables[mesh];

	for( size_t i = 0; i < rends.size(); ++i )
	{
		Renderable* rend = rends[i].get();
		rend->onPreRender.Bind(this, &Model::onRender);
		
		addRenderable( rend );
	}

	// Updates the model bounding box.
	updateBounds();
	
	// Re-compute the bounding box.
	Transform* transform = getEntity()->getTransform().get();
	transform->markBoundingVolumeDirty();

	prepareSkinning();

	modelBuilt = true;
}
Exemplo n.º 12
0
void StaticSprite::loadSprite(uint32 fileHash, uint flags, int surfacePriority, int16 x, int16 y) {
	_spriteResource.load(fileHash, true);
	if (!_surface)
		createSurface(surfacePriority, _spriteResource.getDimensions().width, _spriteResource.getDimensions().height);
	if (flags & kSLFDefDrawOffset)
		_drawOffset.set(0, 0, _spriteResource.getDimensions().width, _spriteResource.getDimensions().height);
	else if (flags & kSLFCenteredDrawOffset)
		_drawOffset.set(-(_spriteResource.getDimensions().width / 2), -(_spriteResource.getDimensions().height / 2),
			_spriteResource.getDimensions().width, _spriteResource.getDimensions().height);
	if (flags & kSLFDefPosition) {
		_x = _spriteResource.getPosition().x;
		_y = _spriteResource.getPosition().y;
	} else if (flags & kSLFSetPosition) {
		_x = x;
		_y = y;
	}
	if (flags & kSLFDefCollisionBoundsOffset) {
		_collisionBoundsOffset = _drawOffset;
		updateBounds();
	}
	_needRefresh = true;
	updatePosition();
}
Exemplo n.º 13
0
    void PSliderT<T>::setup(const std::string label, T *value, const T min, const T max, ci::Vec2<T> sliderLeft, ci::Vec2<T> sliderRight ){
        mLabelText = label;
        mValue = value;
        mMin = min;
        mMax = max;
        mSliderLeft = sliderLeft;
        mSliderRight = sliderRight;
        mPosOffset = 0;
        
        // texture skin rect
		mSkinTexRect.set(0, 0, 13, 12);
		mSkinDestRect = mSkinTexRect;
		mSkinDestRect.offset(Vec2i(-7, -7));
        
        bIsDragging = false;
        mHandlePos.set(15, 22);
        mHandleHitbox.set(-5, -7, 5, 5);
        mSliderPct = 0.0f;
        
        mGlobal = PretzelGlobal::getInstance();
        
        updateBounds( mSliderLeft, mSliderRight );
    }
void ColouredElement::setCurrentBounds (const Rectangle<int>& newBounds,
                                        const Rectangle<int>& parentArea,
                                        const bool undoable)
{
    Rectangle<int> r (newBounds);

    if (isStrokePresent)
    {
        r = r.expanded (-((int) strokeType.stroke.getStrokeThickness() / 2 + 1));

        r.setSize (jmax (1, r.getWidth()), jmax (1, r.getHeight()));
    }

    RelativePositionedRectangle pr (position);
    pr.updateFrom (r.getX() - parentArea.getX(),
                   r.getY() - parentArea.getY(),
                   r.getWidth(), r.getHeight(),
                   Rectangle<int> (0, 0, parentArea.getWidth(), parentArea.getHeight()),
                   getDocument()->getComponentLayout());
    setPosition (pr, undoable);

    updateBounds (parentArea);
}
Exemplo n.º 15
0
// ----------------------------------------------------------------------
bool ObjMesh::loadFromObjFile(char *filename)
{
	FILE *f = fopen(filename, "r");
	if (!f) return false;
	clear();
	ObjMeshString s, subs[maxVerticesPerFace];
	ObjMeshString mtllib, matName;

	mHasTextureCoords = false;
	mHasNormals = false;

	strcpy(mtllib, "");
	int materialNr = -1;
	int i,j;
	NxVec3 v;
	ObjMeshTriangle t;
	TexCoord tc;

	std::vector<NxVec3> centermVertices;
	std::vector<TexCoord> centermTexCoords;
	std::vector<NxVec3> centerNormals;

	extractPath(filename);

	while (!feof(f)) {
		if (fgets(s, OBJ_MESH_STRING_LEN, f) == NULL) break;

		if (strncmp(s, "mtllib", 6) == 0) {  // material library
			sscanf(&s[7], "%s", mtllib);
			importMtlFile(mtllib);
		}
		else if (strncmp(s, "usemtl", 6) == 0) {  // use material
			sscanf(&s[7], "%s", matName);
			materialNr = 0;
			int numMaterials = (int)mMaterials.size();
			while (materialNr < numMaterials &&
				   strcasecmp(mMaterials[materialNr].name, matName) != 0)
				materialNr++;
			if (materialNr >= numMaterials) 
				materialNr = -1;
		}
		else if (strncmp(s, "v ", 2) == 0) {	// vertex
			sscanf(s, "v %f %f %f", &v.x, &v.y, &v.z);
			mVertices.push_back(v);
		}
		else if (strncmp(s, "vn ", 3) == 0) {	// normal
			sscanf(s, "vn %f %f %f", &v.x, &v.y, &v.z);
			mNormals.push_back(v);
		}
		else if (strncmp(s, "vt ", 3) == 0) {	// texture coords
			sscanf(s, "vt %f %f", &tc.u, &tc.v);
			mTexCoords.push_back(tc);
		}
		else if (strncmp(s, "f ", 2) == 0) {	// face
			int nr;
			nr = sscanf(s, "f %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s",
			subs[0], subs[1], subs[2], subs[3], subs[4],
			subs[5], subs[6], subs[7], subs[8], subs[9],
			subs[10], subs[11], subs[12],subs[13], subs[14]);
			int vertNr[maxVerticesPerFace], texNr[maxVerticesPerFace];
			int normalNr[maxVerticesPerFace];
			for (i = 0; i < nr; i++) {
				int refs[3];
				parseRef(subs[i], refs);
				vertNr[i] = refs[0]-1;
				texNr[i] = refs[1]-1;
				normalNr[i] = refs[2]-1;
			}
			if (nr <= 4) {	// simple non-singular triangle or quad
				if (vertNr[0] != vertNr[1] && vertNr[1] != vertNr[2] && vertNr[2] != vertNr[0]) {
					t.init();
					t.vertexNr[0] = vertNr[0];
					t.vertexNr[1] = vertNr[1];
					t.vertexNr[2] = vertNr[2];
					t.normalNr[0] = normalNr[0];
					t.normalNr[1] = normalNr[1];
					t.normalNr[2] = normalNr[2];
					t.texCoordNr[0] = texNr[0];
					t.texCoordNr[1] = texNr[1];
					t.texCoordNr[2] = texNr[2];
					t.materialNr = materialNr;
					mTriangles.push_back(t);
				}
				if (nr == 4) {	// non-singular quad -> generate a second triangle
					if (vertNr[2] != vertNr[3] && vertNr[3] != vertNr[0] && vertNr[0] != vertNr[2]) {
						t.init();
						t.vertexNr[0] = vertNr[2];
						t.vertexNr[1] = vertNr[3];
						t.vertexNr[2] = vertNr[0];
						t.normalNr[0] = normalNr[2];
						t.normalNr[1] = normalNr[3];
						t.normalNr[2] = normalNr[0];
						t.texCoordNr[0] = texNr[0];
						t.texCoordNr[1] = texNr[1];
						t.texCoordNr[2] = texNr[2];
						t.materialNr = materialNr;
						mTriangles.push_back(t);
					}
				}
			}
			else {	// polygonal face

				// compute center properties
				NxVec3 centerPos(0.0f, 0.0f, 0.0f);
				TexCoord centerTex; centerTex.zero();
				for (i = 0; i < nr; i++) {
					centerPos += mVertices[vertNr[i]];
					if (texNr[i] >= 0) centerTex += mTexCoords[texNr[i]];
				}
				centerPos /= (float)nr;
				centerTex /= (float)nr;
				NxVec3 d1 = centerPos - mVertices[vertNr[0]];
				NxVec3 d2 = centerPos - mVertices[vertNr[1]];
				NxVec3 centerNormal = d1.cross(d2); centerNormal.normalize();

				// add center vertex
				centermVertices.push_back(centerPos);
				centermTexCoords.push_back(centerTex);
				centerNormals.push_back(centerNormal);

				// add surrounding elements
				for (i = 0; i < nr; i++) {
					j = i+1; if (j >= nr) j = 0;
					t.init();
					t.vertexNr[0] = mVertices.size() + centermVertices.size()-1;
					t.vertexNr[1] = vertNr[i];
					t.vertexNr[2] = vertNr[j];

					t.normalNr[0] = mNormals.size() + centerNormals.size()-1;
					t.normalNr[1] = normalNr[i];
					t.normalNr[2] = normalNr[j];

					t.texCoordNr[0] = mTexCoords.size() + centermTexCoords.size()-1;
					t.texCoordNr[1] = texNr[i];
					t.texCoordNr[2] = texNr[j];
					t.materialNr = materialNr;
					mTriangles.push_back(t);
				}
			}
		}
	}
	fclose(f);

	// new center mVertices are inserted here.
	// If they were inserted when generated, the vertex numbering would be corrupted
	for (i = 0; i < (int)centermVertices.size(); i++)
		mVertices.push_back(centermVertices[i]);
	for (i = 0; i < (int)centerNormals.size(); i++)
		mNormals.push_back(centerNormals[i]);
	for (i = 0; i < (int)centermTexCoords.size(); i++)
		mTexCoords.push_back(centermTexCoords[i]);

	if (mTexCoords.size() > 0) mHasTextureCoords = true;
	if (mNormals.size() > 0) 
		mHasNormals = true;
	else
		updateNormals();

	updateBounds();
	return true;
}
Exemplo n.º 16
0
    bool CapsuleMesh::load(const float radius, const float height, const unsigned int rings, const bool normalizedTexCoords)
    {
        m_radius = radius;
        m_height = height;
        m_rings = rings;
        m_normTexCoords = normalizedTexCoords;

        const float half = height * 0.5f;
        const float stretch = radius / rings + 1.f;
        const float R = 1.0f / (rings - 1);
        const float S = 1.0f / (rings - 1);

        const unsigned int texCoordMultS = normalizedTexCoords ? 1u : rings;
        const unsigned int texCoordMultR = normalizedTexCoords ? 1u : rings;

        std::vector<Vertex> vertexArray(rings * rings);

        auto itr = vertexArray.begin();
        for (std::size_t s = 0; s < rings; ++s)
        {
            for (std::size_t r = 0; r < rings; ++r)
            {
                static const float pi1 = glm::pi<float>();
                static const float pi2 = glm::half_pi<float>();

                float y = std::sin(-pi2 + pi1 * r * R);
                const float x = std::cos(2 * pi1 * s * S) * std::sin(pi1 * r * R);
                const float z = std::sin(2 * pi1 * s * S) * std::sin(pi1 * r * R);

                if (y >= stretch)
                    y += half;
                else
                    y -= half;

                itr->position.x = x * radius;
                itr->position.y = y * radius;
                itr->position.z = z * radius;

                itr->texCoords.x = texCoordMultS * s * -S;
                itr->texCoords.y = texCoordMultR * r * R;

                itr->normal.x = x;
                itr->normal.y = y;
                itr->normal.z = z;

                ++itr;
            }
        }

        std::vector<unsigned int> indices(rings * rings * 6);

        auto i = indices.begin();
        for (std::size_t r = 0; r < rings - 1; ++r)
        {
            for (std::size_t s = 0; s < rings - 1; ++s)
            {
                // First triangle
                *i++ = r * rings + s;             // 0, 0          
                *i++ = r * rings + (s + 1);       // 1, 0
                *i++ = (r + 1) * rings + (s + 1); // 1, 1

                // Second triangle
                *i++ = r * rings + s;             // 0, 0    
                *i++ = (r + 1) * rings + (s + 1); // 1, 1
                *i++ = (r + 1) * rings + s;       // 0, 1
            }
        }

        updateBounds(glm::vec3(-radius, -half, -radius), glm::vec3(radius, half, radius));

        return Mesh::load(vertexArray, indices);
    }
Exemplo n.º 17
0
void AtlasOldMesher::write(Stream *s, const S8 level, bool doWriteCollision)
{
   AssertISV(mIndices.size(), "AtlasOldMesher::write - no indices to write?!?");

   // First, figure our bounds.
   updateBounds();

   // Then, run the tristripper, get our geometry a bit more optimal.
   ///optimize();

   // We start at the appropriate position in the TOC. It's great!

   // Write min & max y values.  This can be used to reconstruct
   // the bounding box.
   s->write(mMinZ);
   s->write(mMaxZ);

   // Write a placeholder for the mesh data file pos.
   U32 currentPos = s->getPosition();
   s->write(U32(0));

   // write out the vertex data at the *end* of the file.
   s->setPosition(s->getStreamSize());
   U32 meshPos = s->getPosition();

   // Write a sentinel.
   s->write(U32(0xbeef1234));

   // Make sure the vertex buffer is not too big.
   if(mVerts.size() > 0xFFFF)
   {
      AssertISV(false,
         "AtlasOldMesher::write - too many vertices! (> 65535) Try making a deeper tree!");
   }

   // Write vertices.  All verts contain morph info.
   s->write(U16(mVerts.size()));
   for (int i = 0; i < mVerts.size(); i++)
      writeVertex(s, &mVerts[i], level);

   // Write the index buffer.
   s->write(S32(mIndices.size()));
   for(S32 i=0; i<mIndices.size(); i++)
      s->write(mIndices[i]);

   // Write the triangle count.
   s->write(U32(mIndices.size()) / 3);

   gOldChunkGenStats.outputRealTriangles += mIndices.size() / 3;

   // Now, we have to make our collision info...
   if(doWriteCollision)
   {
      s->write(U8(1));
      writeCollision(s);
   }
   else
   {
      s->write(U8(0));
   }

   // write the postscript.
   s->write(U32(0xb1e2e3f4));

   // Rewind, and fill in the mesh data file pos.
   s->setPosition(currentPos);
   s->write(meshPos);

   // Con::printf("    - %d indices, %d verts, meshOffset=%d", mIndices.size(), mVerts.size(), meshPos);
}
Exemplo n.º 18
0
	virtual void updatePosition( Point3D new_pos ) { 
		m_pos_text = new_pos; 
		updateBounds();
	}
Exemplo n.º 19
0
void GameLevel::load(const std::string &levelFile) {
  unload();

  std::string buffer = levelFile.empty() ? sTemplateMap : JsonParser::getBuffer(levelFile);
  if (buffer.empty()) {
    load("");
    return;
  }
  JsonParser parser(buffer);
  if (!parser) {
    CCLOG("%s", buffer.c_str());
    CCLOGERROR("Cannot load the level file: %s", levelFile.c_str());
  }

  CCLOG("Loading level file: %s", levelFile.empty() ? "Template" : levelFile.c_str());

  auto& doc = parser.getCurrentDocument();

  std::string paletteFile = doc[LEVEL_PALETTE_FILE].GetString();
  CC_SAFE_DELETE(mPalette);
  mPalette = new ColorPalette(paletteFile);

  // Shadows.
  if (doc.HasMember(SHADOW_GROUP)) {
    mNumShadowGroup = doc[SHADOW_GROUP].Size();
    parser.parseArray(doc, SHADOW_GROUP, [&](JsonSizeT i, JsonValueT &val) {
      addShadowGroup();
      mShadows[i]->load(val);
      initShadowGroup(i);
    });
  }

  // Sprites.
  CC_ASSERT(mSpriteList.empty());
  if (doc.HasMember(GAME_SPRITES)) {
    parser.parseArray(doc, GAME_SPRITES, [&](JsonSizeT i, JsonValueT &val) {
      mSpriteList.push_back(new GameSprite());
      mSpriteList.back()->load(val);
      mGameLayer->getBlockRoot()->addChild(mSpriteList.back()->getSprite(),
                                           mSpriteList.back()->ZOrder);
    });
  }

  // Effects.
  CC_ASSERT(mEffects.empty());
  if (doc.HasMember(GAME_FX)) {
    parser.parseArray(doc, GAME_FX, [&](JsonSizeT i, JsonValueT &val) {
      mEffects.push_back(val.GetString());
    });
  }
  loadFx();

  // Objects.
  mHeroSpawnPos = doc[LEVEL_SPAWN_POS].GetVec2();
  createHero(mHeroSpawnPos);
  parser.parseArray(doc, LEVEL_BLOCK_ARRAY, [&](JsonSizeT i, JsonValueT& val) {
    mObjectManager->createObject(val);
  });

  // Update shadow right after loading objects.
  for (auto sm : mShadows) {
    sm->update(0);
  }
  
  // Time events.
  CC_ASSERT(mTimeEvents.empty());
  if (doc.HasMember(TIME_EVENTS)) {
    parser.parseArray(doc, TIME_EVENTS, [&](JsonSizeT i, JsonValueT &val) {
      auto timeEvent = new TimeEvent();
      timeEvent->load(val);
      mTimeEvents.push_back(timeEvent);
    });
  }

  updateBounds();
  mBackground->clear();
  mBackground->drawSolidRect({mBounds.getMinX(), mBounds.getMinY()},
                             {mBounds.getMaxX(), mBounds.getMaxY()},
                             Color4F(mPalette->getBackgroundColor()));

  setCurrentFile(levelFile);

  mGameLayer->afterLoad();
}
Exemplo n.º 20
0
/** Removes any transparent borders by reducing the boundaries.
 *
 *  This function reduces the bounds of an image until the top and
 *  bottom rows, and the left and right columns of pixels each
 *  contain at least one pixel with a non-zero alpha value
 *  (i.e. non-transparent pixel). Both mBounds and
 *  the size of #mImage are updated.
 *
 *  @pre mBounds.size() == mImage->size()
 *  @post Either the first and last rows and columns all contain a
 *        pixel with alpha > 0 or mBounds.isEmpty() == true
 *  @post isMinimallyBounded() == true
 */
void BitmapImage::autoCrop()
{
    if (!mEnableAutoCrop) return;
    if (mBounds.isEmpty()) return; // Exit if current bounds are null
    if (!mImage) return;

    Q_ASSERT(mBounds.size() == mImage->size());

    // Exit if already min bounded
    if (mMinBound) return;

    // Get image properties
    const int width = mImage->width();

    // Relative top and bottom row indices (inclusive)
    int relTop = 0;
    int relBottom = mBounds.height()-1;

    // Check top row
    bool isEmpty = true; // Used to track if a non-transparent pixel has been found
    while (isEmpty && relTop <= relBottom) // Loop through rows
    {
        // Point cursor to the first pixel in the current top row
        const QRgb* cursor = reinterpret_cast<const QRgb*>(mImage->constScanLine(relTop));
        for (int col = 0; col < width; col++) // Loop through pixels in row
        {
            // If the pixel is not transparent
            // (i.e. alpha channel > 0)
            if (qAlpha(*cursor) != 0)
            {
                // We've found a non-transparent pixel in row relTop,
                // so we can stop looking for one
                isEmpty = false;
                break;
            }
            // Move cursor to point to the next pixel in the row
            cursor++;
        }
        if (isEmpty)
        {
            // If the row we just checked was empty, increase relTop
            // to remove the empty row from the top of the bounding box
            ++relTop;
        }
    }

    // Check bottom row
    isEmpty = true; // Reset isEmpty
    while (isEmpty && relBottom >= relTop) // Loop through rows
    {
        // Point cursor to the first pixel in the current bottom row
        const QRgb* cursor = reinterpret_cast<const QRgb*>(mImage->constScanLine(relBottom));
        for (int col = 0; col < width; col++) // Loop through pixels in row
        {
            // If the pixel is not transparent
            // (i.e. alpha channel > 0)
            if(qAlpha(*cursor) != 0)
            {
                // We've found a non-transparent pixel in row relBottom,
                // so we can stop looking for one
                isEmpty = false;
                break;
            }
            // Move cursor to point to the next pixel in the row
            ++cursor;
        }
        if (isEmpty)
        {
            // If the row we just checked was empty, decrease relBottom
            // to remove the empty row from the bottom of the bounding box
            --relBottom;
        }
    }

    // Relative left and right column indices (inclusive)
    int relLeft = 0;
    int relRight = mBounds.width()-1;

    // Check left row
    isEmpty = (relBottom >= relTop); // Check left only when 
    while (isEmpty && relBottom >= relTop && relLeft <= relRight) // Loop through columns
    {
        // Point cursor to the pixel at row relTop and column relLeft
        const QRgb* cursor = reinterpret_cast<const QRgb*>(mImage->constScanLine(relTop)) + relLeft;
        // Loop through pixels in column
        // Note: we only need to loop from relTop to relBottom (inclusive)
        //       not the full image height, because rows 0 to relTop-1 and
        //       relBottom+1 to mBounds.height() have already been
        //       confirmed to contain only transparent pixels
        for (int row = relTop; row <= relBottom; row++)
        {
            // If the pixel is not transparent
            // (i.e. alpha channel > 0)
            if(qAlpha(*cursor) != 0)
            {
                // We've found a non-transparent pixel in column relLeft,
                // so we can stop looking for one
                isEmpty = false;
                break;
            }
            // Move cursor to point to next pixel in the column
            // Increment by width because the data is in row-major order
            cursor += width;
        }
        if (isEmpty)
        {
            // If the column we just checked was empty, increase relLeft
            // to remove the empty column from the left of the bounding box
            ++relLeft;
        }
    }

    // Check right row
    isEmpty = (relBottom >= relTop); // Reset isEmpty
    while (isEmpty && relRight >= relLeft) // Loop through columns
    {
        // Point cursor to the pixel at row relTop and column relRight
        const QRgb* cursor = reinterpret_cast<const QRgb*>(mImage->constScanLine(relTop)) + relRight;
        // Loop through pixels in column
        // Note: we only need to loop from relTop to relBottom (inclusive)
        //       not the full image height, because rows 0 to relTop-1 and
        //       relBottom+1 to mBounds.height()-1 have already been
        //       confirmed to contain only transparent pixels
        for (int row = relTop; row <= relBottom; row++)
        {
            // If the pixel is not transparent
            // (i.e. alpha channel > 0)
            if(qAlpha(*cursor) != 0)
            {
                // We've found a non-transparent pixel in column relRight,
                // so we can stop looking for one
                isEmpty = false;
                break;
            }
            // Move cursor to point to next pixel in the column
            // Increment by width because the data is in row-major order
            cursor += width;
        }
        if (isEmpty)
        {
            // If the column we just checked was empty, increase relRight
            // to remove the empty column from the left of the bounding box
            --relRight;
        }
    }

    //qDebug() << "Original" << mBounds;
    //qDebug() << "Autocrop" << relLeft << relTop << relRight - mBounds.width() + 1 << relBottom - mBounds.height() + 1;
    // Update mBounds and mImage if necessary
    updateBounds(mBounds.adjusted(relLeft, relTop, relRight - mBounds.width() + 1, relBottom - mBounds.height() + 1));

    //qDebug() << "New bounds" << mBounds;

    mMinBound = true;
}
Exemplo n.º 21
0
float DisplayObject::getWidth() {
    updateBounds();
    return absf(_max.x - _min.x);
}
Exemplo n.º 22
0
	bool msgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
									
		if(msg == WM_SIZE) {

			updateBounds(hwnd);

		}
		
		if(msg == WM_PAINT) {

			updateBounds(hwnd);

			updateGraph(hwnd);

		}

		if(msg == WM_DESTROY) {
			//SendMessage(GetParent(hwnd), WM_GRAPH_CHANGED, 0, 0);		
			bClosed = true;
		}
		
		if(msg == WM_CREATE) {

			updateGraph(hwnd);

		}

				
		if(msg == WM_LBUTTONDBLCLK) {

//			POINT point;
			//GetCursorPos(&point);


			int xPos = LOWORD(lParam);
			int yPos = HIWORD(lParam);
			
			RECT rect;
			GetClientRect(hwnd, &rect);
			
			if((xPos >= rect.left) && (xPos <= rect.right) && (yPos >= rect.top) && 
				(yPos <= rect.bottom)) 
			{

				float x = toGraphX(xPos);
				float y = toGraphY(rect.bottom - yPos);
				
				for(int i = 0; i < mChannels.size(); i++) {
					Channel* c = &mChannels[i];
					c->insertKey(x);
				}
			}

			updateGraph(hwnd);
		
		}

		if((msg == WM_MOUSEMOVE) && mLocked) {
									
			if(wParam != MK_LBUTTON) {
			
				mLocked = false;
						
			} else {
		
				POINT point;
				
				point.x = LOWORD(lParam);
				point.y = HIWORD(lParam);
				
/*				//GetCursorPos(&point);
								
				RECT rect;
				GetClientRect(hwnd, &rect);
				
				float x = (float)(point.x - rect.left) / (float)(rect.right - rect.left);
				float y = 1.0f - (float)(point.y - rect.top) / (float)(rect.bottom - rect.top);
				float dx = x - mOldX;
				float dy = y - mOldY;
*/				
			RECT rc;
			GetClientRect(hwnd, &rc);

				float x = toGraphX(point.x);
				float y = toGraphY(rc.bottom - point.y);
				
				Channel* c = &mChannels[mLockedChannel];
				
				c->moveKey(x,y,mXTreshold, ymin, ymax);
			
				mOldX = x;
				mOldY = y;

			}

			updateGraph(hwnd);

		}
		

		if((msg == WM_LBUTTONDOWN) & !mLocked) {
		
			POINT point;
			//GetCursorPos(&point);
								
			point.x = LOWORD(lParam);
			point.y = HIWORD(lParam);

			RECT rc;
			GetClientRect(hwnd, &rc);
				
//			float x = (float)(point.x - rect.left) / (float)(rect.right - rect.left);
//			float y = 1.0f - (float)(point.y - rect.top) / (float)(rect.bottom - rect.top);

				float x = toGraphX(point.x);
				float y = toGraphY(rc.bottom - point.y);


			for(int i = 0; i < mChannels.size(); i++) {
				Channel* c = &mChannels[i];
				if(c->lockKey(x, y, mXTreshold, mYTreshold)) {
					mLockedChannel = i;
					mLocked = true;
					mOldX = x;
					mOldY = y;
					break;
				}
			}
		
		}
		
		return false;
	}
Exemplo n.º 23
0
void ConvexShape::_updateGeometry( bool updateCollision )
{
   mPlanes.clear();

   for ( S32 i = 0; i < mSurfaces.size(); i++ )   
      mPlanes.push_back( PlaneF( mSurfaces[i].getPosition(), mSurfaces[i].getUpVector() ) );

	Vector< Point3F > tangents;
	for ( S32 i = 0; i < mSurfaces.size(); i++ )
		tangents.push_back( mSurfaces[i].getRightVector() );
   
   mGeometry.generate( mPlanes, tangents );

   AssertFatal( mGeometry.faces.size() <= mSurfaces.size(), "Got more faces than planes?" );

   const Vector< ConvexShape::Face > &faceList = mGeometry.faces;
   const Vector< Point3F > &pointList = mGeometry.points;

   // Reset our surface center points.

   for ( S32 i = 0; i < faceList.size(); i++ )
		mSurfaces[ faceList[i].id ].setPosition( faceList[i].centroid );

   mPlanes.clear();

   for ( S32 i = 0; i < mSurfaces.size(); i++ )   
      mPlanes.push_back( PlaneF( mSurfaces[i].getPosition(), mSurfaces[i].getUpVector() ) );

   // Update bounding box.   
   updateBounds( false );

	mVertexBuffer = NULL;
	mPrimitiveBuffer = NULL;
	mVertCount = 0;
	mPrimCount = 0;

   if ( updateCollision )
      _updateCollision();

   // Server does not need to generate vertex/prim buffers.
   if ( isServerObject() )
      return;

   if ( faceList.empty() )   
      return;


	// Get total vert and prim count.

	for ( S32 i = 0; i < faceList.size(); i++ )	
	{
		U32 count = faceList[i].triangles.size();
		mPrimCount += count;
		mVertCount += count * 3;		
	}

	// Allocate VB and copy in data.

	mVertexBuffer.set( GFX, mVertCount, GFXBufferTypeStatic );
	VertexType *pVert = mVertexBuffer.lock();

	for ( S32 i = 0; i < faceList.size(); i++ )
	{
		const ConvexShape::Face &face = faceList[i];
		const Vector< U32 > &facePntMap = face.points;
		const Vector< ConvexShape::Triangle > &triangles = face.triangles;
		const ColorI &faceColor = sgConvexFaceColors[ i % sgConvexFaceColorCount ];

		const Point3F binormal = mCross( face.normal, face.tangent );

		for ( S32 j = 0; j < triangles.size(); j++ )
		{
			for ( S32 k = 0; k < 3; k++ )
			{
				pVert->normal = face.normal;
				pVert->tangent = face.tangent;
				pVert->color = faceColor;			
				pVert->point = pointList[ facePntMap[ triangles[j][k] ] ];
				pVert->texCoord = face.texcoords[ triangles[j][k] ];

				pVert++;
			}
		}		
	}	

	mVertexBuffer.unlock();

	// Allocate PB

   mPrimitiveBuffer.set( GFX, mPrimCount * 3, mPrimCount, GFXBufferTypeStatic );

   U16 *pIndex;
   mPrimitiveBuffer.lock( &pIndex );

   for ( U16 i = 0; i < mPrimCount * 3; i++ )
   {
      *pIndex = i;
      pIndex++;
   }

   mPrimitiveBuffer.unlock();
}
Exemplo n.º 24
0
boost::uint32_t InPlaceReprojection::readBufferImpl(PointBuffer& buffer)
{

    
    const boost::uint32_t numPoints = getPrevIterator().read(buffer);

    const Schema& schema = buffer.getSchema();
    
    Dimension const& old_x = schema.getDimension(m_reprojectionFilter.getOldXId());
    Dimension const& old_y = schema.getDimension(m_reprojectionFilter.getOldYId());
    Dimension const& old_z = schema.getDimension(m_reprojectionFilter.getOldZId());

    Dimension const& new_x = schema.getDimension(m_reprojectionFilter.getNewXId());
    Dimension const& new_y = schema.getDimension(m_reprojectionFilter.getNewYId());
    Dimension const& new_z = schema.getDimension(m_reprojectionFilter.getNewZId());
    
    bool logOutput = m_reprojectionFilter.log()->getLevel() > logDEBUG3;
    

    if (logOutput)
    {
        m_reprojectionFilter.log()->floatPrecision(8);
        m_reprojectionFilter.log()->get(logDEBUG3) << "old_x: " << old_x;
        m_reprojectionFilter.log()->get(logDEBUG3) << "old_y: " << old_y;
        m_reprojectionFilter.log()->get(logDEBUG3) << "old_z: " << old_z;

        m_reprojectionFilter.log()->get(logDEBUG3) << "new_x: " << new_x;
        m_reprojectionFilter.log()->get(logDEBUG3) << "new_y: " << new_y;
        m_reprojectionFilter.log()->get(logDEBUG3) << "new_z: " << new_z;
        
    }

    logOutput = m_reprojectionFilter.log()->getLevel() > logDEBUG3;

    for (boost::uint32_t pointIndex=0; pointIndex<numPoints; pointIndex++)
    {
        double x = m_reprojectionFilter.getScaledValue(buffer, old_x, pointIndex);
        double y = m_reprojectionFilter.getScaledValue(buffer, old_y, pointIndex);
        double z = m_reprojectionFilter.getScaledValue(buffer, old_z, pointIndex);
        
        if (logOutput)
            m_reprojectionFilter.log()->get(logDEBUG5) << "input: " << x << " y: " << y << " z: " << z << std::endl;
        m_reprojectionFilter.transform(x,y,z);
        if (logOutput)
            m_reprojectionFilter.log()->get(logDEBUG5) << "output: " << x << " y: " << y << " z: " << z << std::endl;
    
        m_reprojectionFilter.setScaledValue(buffer, x, new_x, pointIndex);
        m_reprojectionFilter.setScaledValue(buffer, y, new_y, pointIndex);
        m_reprojectionFilter.setScaledValue(buffer, z, new_z, pointIndex);
        
        if (logOutput)
        {
            m_reprojectionFilter.log()->get(logDEBUG5) << "scaled: " << m_reprojectionFilter.getScaledValue(buffer, new_x, pointIndex)
                  << " y: " << m_reprojectionFilter.getScaledValue(buffer, new_y, pointIndex)
                  << " z: " << m_reprojectionFilter.getScaledValue(buffer, new_z, pointIndex) << std::endl;
        }
    
        buffer.setNumPoints(pointIndex+1);
    }
    if (logOutput)
        m_reprojectionFilter.log()->clearFloat();

    updateBounds(buffer);

    return numPoints;
}
Exemplo n.º 25
0
void ElectricBolt::update(float deltaTime, std::vector<std::unique_ptr<Creep>> &creeps, std::vector<std::unique_ptr<WorldPlatform>> &platforms, std::vector<std::unique_ptr<Projectile>> &projectiles)
{
	m_fStateTime += deltaTime;
	m_fFireTime += deltaTime;
	m_position->add(m_velocity->getX() * deltaTime, m_velocity->getY() * deltaTime);
	updateBounds();
	m_remove = ScreenUtils::isVectorOffScreen(*m_position);

	m_fAlpha -= deltaTime / m_iFadeTimeSeconds;

	m_remove = m_fAlpha < 0;

	if (!m_remove && m_fFireTime > m_fDamageTime)
	{
		m_iDamageSinceLastUpdate = 0;

		while (m_fFireTime > m_fDamageTime)
		{
			m_fFireTime -= m_fDamageTime;
			m_iDamageSinceLastUpdate += m_iDamage;
		}

		for (std::vector<std::unique_ptr<Creep>>::iterator itr = creeps.begin(); itr != creeps.end(); itr++)
		{
			if (OverlapTester::doRectanglesOverlap((*itr)->getBounds(), *m_bounds))
			{
				(*itr)->takeDamage(m_iDamageSinceLastUpdate, ELECTRIC);

				if(FlagUtil::isFlagSet((*itr)->getState(), ALIVE))
				{
					(*itr)->electrify();
				}
			}
		}

		for (std::vector<std::unique_ptr<Projectile>>::iterator itr = projectiles.begin(); itr != projectiles.end(); itr++)
		{
			if ((*itr)->getProjectileState() == Projectile_State::STUCK && OverlapTester::doRectanglesOverlap((*itr)->getBounds(), *m_bounds))
			{
				(*itr)->zap(m_iZapDamage);
			}
		}
	}

	if (m_hasEscapedTowerPlatform)
	{
		for (std::vector<std::unique_ptr<WorldPlatform>>::iterator itr = platforms.begin(); itr != platforms.end(); itr++)
		{
			if (OverlapTester::doRectanglesOverlap((*itr)->getBounds(), *m_bounds))
			{
				float deltaY = fabs((*itr)->getPosition().getY() - m_position->getY());
				float deltaX = fabs((*itr)->getPosition().getX() - m_position->getX());

				if (deltaY > deltaX)
				{
					m_velocity->set(m_velocity->getX(), -m_velocity->getY());
				}
				else
				{
					m_velocity->set(-m_velocity->getX(), m_velocity->getY());
				}

				m_fAngle = m_velocity->angle();

				return;
			}
		}
	}
	else
	{
		for (std::vector<std::unique_ptr<WorldPlatform>>::iterator itr = platforms.begin(); itr != platforms.end(); itr++)
		{
			if (OverlapTester::doRectanglesOverlap((*itr)->getBounds(), *m_bounds))
			{
				return;
			}
		}

		m_hasEscapedTowerPlatform = true;
	}
}
Exemplo n.º 26
0
Vector2D DisplayObject::getMin() {
    updateBounds(true);
    return _min;
}
QVariant GraphicsUserListItem::itemChange(GraphicsItemChange change, const QVariant& value) {
    if(change == ItemSceneHasChanged) {
        updateBounds();
    }
    return QGraphicsItem::itemChange(change, value);
}
Exemplo n.º 28
0
Vector2D DisplayObject::getMax() {
    updateBounds(true);
    return _max;
}
Exemplo n.º 29
0
float DisplayObject::getHeight() {
    updateBounds();
    return absf(_max.y - _min.y);
}
Exemplo n.º 30
0
	virtual void updateSize( Vector3D scale ) { 
		m_size_text = scale[0]; 
		updateBounds();
	}