Exemple #1
0
void ParkScene::_draw(float time)
{
	float camTime = time / Duration();
	mat4 mPersp = perspective(mix(45.0f, endFov, myx(camTime)), demo.aspect, 0.5f, 1000.0f);
	mat4 mCamera = lookAt(interpolatePath(oCamPath, endCamPos * 0.1f, camTime), interpolatePath(oLookPath, endLookAt * 0.1f, camTime), mix(vec3(0, 1, 0), endUp, myx(camTime)));

	setDepthMode(DEPTH_FULL);
	for (int i = 0; i < ARRAY_SIZE(tPark); i++) {
		GlslShader *sDraw = sPark[i];
		sDraw->bind();
		sDraw->uniform("u_matrix", mPersp * mCamera);
		sDraw->uniform("u_modelview", mCamera);
		sDraw->uniform("u_projection", mPersp);
		sDraw->uniform("u_alpha", 1.0f);
		sDraw->bindTexture("tex", tPark[i], 0);
		oPark->draw(i);
		sDraw->unbind();
	}
	if (time > Duration() - SceneTime::park2ink) {
		setBlendMode(BLEND_ALPHA);
		sDrawOverlay->bind();
		sDrawOverlay->uniform("u_matrix", mat4(1));
		sDrawOverlay->uniform("u_modelview", mCamera);
		sDrawOverlay->uniform("u_projection", mPersp);
		sDrawOverlay->bindFbo("tex", gFullScreenFbo, 0);
		blendOverlay(oInkBlotOverlay, mPersp * mCamera, pow(clamp((time - Duration() + ovlBlendTime) / ovlBlendTime, 0.0f, 1.0f), 2.0f));
		sDrawOverlay->unbind();
		setBlendMode(NO_BLEND);
	}
	setDepthMode(NO_DEPTH);
}
Exemple #2
0
//-----------------------------------------------------------------------------
//! デバッグ表示
//-----------------------------------------------------------------------------
void Sphere::DebugRender()
{
	glPushMatrix();
		glTranslatef( _position._x, _position._y, _position._z );
		setBlendMode(BM_ADD_ALPHA);		//================================ 【半透明処理開始】
		glutSolidSphere(_radius,16,16);
		setBlendMode(BM_NONE);			//================================ 【半透明処理終了】
	glPopMatrix();
}
Exemple #3
0
//-----------------------------------------------------------------------------
//! 描画
//-----------------------------------------------------------------------------
void SystemPerformance::drawPerformanceBar()
{

	glDepthMask(GL_FALSE);
	setBlendMode(BM_BLEND_ALPHA);

	// 描画座標
	Vector3 drawPos = Vector3(1860.0f, 0.0f, 0.0f);

	// フレームの数
	static u32 frameCount = 3;
	// 線形補完する
	static f32 height = 1000.0f;
	// 1フレーム分の高さ
	static f32 oneFrameHeight = height / (f32)frameCount;
	

	// 枠を描画
	glColor4f(0.0f,0.0f,0.0f, 0.8f);
	glBegin(GL_TRIANGLE_STRIP);
		glVertex3f(drawPos._x	     , drawPos._y	 	  , 0.0f);
		glVertex3f(drawPos._x + 40.0f, drawPos._y		  , 0.0f);
		glVertex3f(drawPos._x		 , drawPos._y + height, 0.0f);
		glVertex3f(drawPos._x + 40.0f, drawPos._y + height, 0.0f);
	glEnd();

	// 枠の分だけずらす
	drawPos._x += 5.0f;

	

	// 描画
	for( list<Performance*>::iterator itr = _pPerformList.begin(); itr != _pPerformList.end(); itr++ )
	{
		Performance*	drawPef = *itr;
		// 描画
		drawPef->DrawPerformance(drawPos, oneFrameHeight, _maxSecond);
		// 次の描画位置を求める
		drawPos._y += drawPef->getHeight();
	}

	//---- フレームの分割線の描画
	drawPos._x -= 5.0f;
	glBegin(GL_LINES);
	glColor4f(0.0f, 1.0f, 0.5f, 1.0f);
	for( u32 i=0; i<frameCount; ++i ){
		glVertex3f(drawPos._x		 , i * oneFrameHeight, 0.0f);
		glVertex3f(drawPos._x + 40.0f, i * oneFrameHeight, 0.0f);
	}
	glEnd();

	// 白で設定しなおす
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

	setBlendMode(BM_NONE);
	glDepthMask(GL_TRUE);
}
    void MovieSprite::initPlayer()
    {
        if (_initialized)
            return;

        _initialized = true;

        _initPlayer();

        Point sz = _bufferSize;
        //sz = Point(nextPOT(sz.x), nextPOT(sz.y));

        Point uvSize = _bufferSize / 2;
        //uvSize = Point(nextPOT(uvSize.x), nextPOT(uvSize.y));
        //uvSize = sz;

        _mtUV.init(uvSize.x, uvSize.y, TF_A8L8);
        _mtUV.fill_zero();
        _textureUV = IVideoDriver::instance->createTexture();
        _textureUV->init(uvSize.x, uvSize.y, _mtUV.getFormat(), false);

        _mtYA.init(sz.x, sz.y, _hasAlphaChannel ? TF_A8L8 : TF_L8);
        _mtYA.fill_zero();
        _textureYA = IVideoDriver::instance->createTexture();
        _textureYA->init(sz.x, sz.y, _mtYA.getFormat(), false);

        if (_hasAlphaChannel)
            setBlendMode(blend_premultiplied_alpha);
        else
            setBlendMode(blend_disabled);

        Diffuse d;
        d.base = _textureYA;
        d.alpha = _textureUV;
        d.premultiplied = true;

        AnimationFrame frame;
        RectF mr = _movieRect.cast<RectF>();

        Vector2 szf = sz.cast<Vector2>();
        RectF tcYA = RectF(mr.pos.div(szf), mr.size.div(szf));
        frame.init(0, d, tcYA, mr, mr.size);

        _yaScale = Vector2(uvSize.x / szf.x, uvSize.y / szf.y);
        _yaScale = Vector2(0.5f, 0.5f);
        _yaScale = Vector2(1, 1);
        Vector2 s = getSize();
        setAnimFrame(frame);
        setSize(s);
    }
void ofCairoRenderer::setStyle(const ofStyle & style){
	//color
	setColor((int)style.color.r, (int)style.color.g, (int)style.color.b, (int)style.color.a);

	//bg color
	//setBackgroundColor(style.bgColor);

	//circle resolution - don't worry it only recalculates the display list if the res has changed
	setCircleResolution(style.circleResolution);

	setSphereResolution(style.sphereResolution);

	//setCurveResolution(style.curveResolution);

	//line width - finally!
	setLineWidth(style.lineWidth);

	//rect mode: corner/center
	setRectMode(style.rectMode);

	//poly mode: winding type
	//setPolyMode(style.polyMode);

	//fill
	setFillMode(style.bFill?OF_FILLED:OF_OUTLINE);

	//smoothing
	//setSmoothingEnabled(style.smoothing);

	//blending
	setBlendMode(style.blendingMode);

	//bitmap draw mode
	//setDrawBitmapMode(style.drawBitmapMode);
}
Exemple #6
0
	int32_t LuaDrawable::setBlendMode(lua_State *L)
	{
		auto drawable = Lua::getObject<Drawable>(L, 1, LuaType::Drawable);
		auto blendMode = Lua::getEnum<BlendMode>(L, 2);
		drawable->setBlendMode(blendMode);
		return 0;
	}
SelectorBase::SelectorBase( const Rectf &bounds )
	: Control( bounds )
{
	setBlendMode( BlendMode::PREMULT_ALPHA );

	mTextLabel = TextManager::loadText( FontFace::NORMAL );
}
//----------------------------------------------------------------------------//
IrrlichtGeometryBuffer::IrrlichtGeometryBuffer(irr::video::IVideoDriver& driver):
    d_driver(driver),
    d_activeTexture(0),
    d_clipRect(0, 0, 0, 0),
    d_clippingActive(true),
    d_translation(0, 0, 0),
    d_rotation(0, 0, 0),
    d_pivot(0, 0, 0),
    d_effect(0),
    d_matrixValid(false),
#if IRRLICHT_VERSION_MAJOR > 1 || (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8)
    d_xViewDir(1.0f),
#else
    d_xViewDir(driver.getDriverType() != irr::video::EDT_OPENGL ? 1.0f : -1.0f),
#endif
    d_texelOffset(driver.getDriverType() != irr::video::EDT_OPENGL ? -0.5f : 0.0f)
{
    d_material.BackfaceCulling = false;
    d_material.Lighting = false;
    d_material.ZBuffer = 0;
    d_material.ZWriteEnable = false;

    // force upate of blending options to suit the default 'normal' mode
    d_blendMode = BM_INVALID;
    setBlendMode(BM_NORMAL);
}
Frame::Frame(QFrame *parent)
    : DBlurEffectWidget(parent),
      m_wallpaperList(new WallpaperList(this)),
      m_closeButton(new DImageButton(":/images/close_round_normal.svg",
                                 ":/images/close_round_hover.svg",
                                 ":/images/close_round_press.svg", this)),
      m_dbusAppearance(new ComDeepinDaemonAppearanceInterface(AppearanceServ,
                                                              AppearancePath,
                                                              QDBusConnection::sessionBus(),
                                                              this)),
      m_mouseArea(new DRegionMonitor(this))
{
    // 截止到dtkwidget 2.0.10版本,在多个屏幕设置不同缩放比时
    // DRegionMonitor 计算的缩放后的坐标可能是错误的
    m_mouseArea->setCoordinateType(DRegionMonitor::Original);

    setFocusPolicy(Qt::StrongFocus);
    setWindowFlags(Qt::BypassWindowManagerHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    setBlendMode(DBlurEffectWidget::BehindWindowBlend);
    setMaskColor(DBlurEffectWidget::DarkColor);

    initUI();
    initSize();

    connect(m_mouseArea, &DRegionMonitor::buttonPress, [this](const QPoint &p, const int button){
        if (button == 4) {
            m_wallpaperList->prevPage();
        } else if (button == 5) {
            m_wallpaperList->nextPage();
        } else {
            qDebug() << "button pressed on blank area, quit.";

            qreal scale = devicePixelRatioF();
            const QRect sRect = this->windowHandle()->screen()->geometry();
            QRect nativeRect = geometry();

            // 获取窗口真实的geometry
            nativeRect.moveTopLeft((nativeRect.topLeft() - sRect.topLeft()) * scale + sRect.topLeft());
            nativeRect.setSize(nativeRect.size() * scale);

            if (!nativeRect.contains(p)) {
                hide();
            }
        }
    });

    m_closeButton->hide();
    connect(m_wallpaperList, &WallpaperList::mouseOverItemChanged,
            this, &Frame::handleNeedCloseButton);
    connect(m_wallpaperList, &WallpaperList::itemPressed,
            this, &Frame::onItemPressed);

    QTimer::singleShot(0, this, &Frame::initListView);
}
Exemple #10
0
Sprite::Sprite(const std::string& path_) :
	sdlTexture(nullptr),
	width(0),
	height(0),
	path(path_),
	flipHorizontal(false)
{
	loadFrom(this->path);

	setBlendMode(SDL_BLENDMODE_BLEND);
	setAlpha(255);
}
//------------------------------------------------------------------------------
//## BlendMode
TEST_F(Test_Visual_VisualComponent, BlendMode)
{
    {
        auto tex1 = Assets::loadTexture(LN_ASSETFILE("Sprite1.png"));

        //* [ ] Normal
        auto sprite1 = Sprite::create(tex1, 3, 3);
        sprite1->setShadingModel(ShadingModel::UnLighting);
        sprite1->setPosition(-6, 0, 0);
        sprite1->setBlendMode(BlendMode::Normal);

        //* [ ] Alpha
        auto sprite2 = Sprite::create(tex1, 3, 3);
        sprite2->setShadingModel(ShadingModel::UnLighting);
        sprite2->setPosition(-3, 0, 0);
        sprite2->setBlendMode(BlendMode::Alpha);

        //* [ ] Add
        auto sprite3 = Sprite::create(tex1, 3, 3);
        sprite3->setShadingModel(ShadingModel::UnLighting);
        sprite3->setPosition(0, 0, 0);
        sprite3->setBlendMode(BlendMode::Add);

        //* [ ] Subtract
        auto sprite4 = Sprite::create(tex1, 3, 3);
        sprite4->setShadingModel(ShadingModel::UnLighting);
        sprite4->setPosition(3, 0, 0);
        sprite4->setBlendMode(BlendMode::Subtract);

        //* [ ] Multiply
        auto sprite5 = Sprite::create(tex1, 3, 3);
        sprite5->setShadingModel(ShadingModel::UnLighting);
        sprite5->setPosition(6, 0, 0);
        sprite5->setBlendMode(BlendMode::Multiply);

        TestEnv::updateFrame();
        ASSERT_SCREEN(LN_ASSETFILE("Visual/Result/Test_Visual_VisualComponent-BlendMode-1.png"));
        LN_TEST_CLEAN_SCENE;
    }
}
void PlayerVitalityParticle::render(double edt) {
    Engine::VideoSystem *videoSystem =
        Engine::Core::getInstance()->getVideoSystem();
    
    setBlendMode();
    videoSystem->bindTexture("Particles");

    double size = getSize();
    double opacity = getOpacity();
    double rotation = getRotation();
    int texture = getTexture();

    double pw = 1.0 / TEX_IMAGE_PARTICLE_WIDTH;
    double ph = 1.0 / TEX_IMAGE_PARTICLE_HEIGHT;

    double particleWidth = 8.0 * pw;
    double particleHeight = 8.0 * ph;

    int row = texture / 12;
    int col = texture % 12;

    double hOffset = col * (particleWidth + 2.0 * pw) + pw;
    double vOffset = 1.0 - ((row + 1) * (particleHeight + 2.0 * ph)) + ph;

    glColor4f(1.0f, 1.0f, 0.0f, opacity);

    glPushMatrix();
    glTranslatef(pos.x, pos.y, 0.0f);
    glRotatef(rotation, 0.0f, 0.0f, 1.0f);

    glBegin(GL_TRIANGLE_STRIP);

    glTexCoord2f(hOffset + particleWidth, vOffset);
    glVertex3f( 0.5 * size, -0.5 * size, 0.0f);

    glTexCoord2f(hOffset + particleWidth, vOffset + particleHeight);
    glVertex3f( 0.5 * size,  0.5 * size, 0.0f);

    glTexCoord2f(hOffset, vOffset);
    glVertex3f(-0.5 * size, -0.5 * size, 0.0f);

    glTexCoord2f(hOffset, vOffset + particleHeight);
    glVertex3f(-0.5 * size,  0.5 * size, 0.0f);

    glEnd();

    glPopMatrix();

    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
Exemple #13
0
void ncGraphics::renderTriple(ncTriple const* triple) {
    if ((curPrimType_   != PRIM_TRIPLES)
    ||  (curBlendMode_  != triple->blendMode)
    ||  (numPrim_       >= VERTEX_BUFFER_SIZE/PRIM_TRIPLES)
    ||  (curTexture_    != triple->tex)) {
        this->renderBatch();
        curPrimType_ = PRIM_TRIPLES;
        setBlendMode(triple->blendMode);
        setTexture(triple->tex);
    }
    memcpy(&vertArray_[numPrim_*PRIM_TRIPLES], triple->v, sizeof(ncVertex)*PRIM_TRIPLES);
    ++numPrim_;
}
Exemple #14
0
void ncGraphics::renderQuad(ncQuad const* quad) {
    if ((curPrimType_   != PRIM_QUADS)
    ||  (curBlendMode_  != quad->blendMode)
    ||  (numPrim_       >= VERTEX_BUFFER_SIZE/PRIM_QUADS)
    ||  (curTexture_    != quad->tex)) {
        this->renderBatch();
        curPrimType_ = PRIM_QUADS;
        setBlendMode(quad->blendMode);
        setTexture(quad->tex);
    }
    memcpy(&vertArray_[numPrim_*PRIM_QUADS], quad->v, sizeof(ncVertex)*PRIM_QUADS);
    ++numPrim_;
}
Exemple #15
0
void ImpostorPage::init(PagedGeometry *geom, const Ogre::Any &data)
{
	//Save pointers to PagedGeometry object
	sceneMgr = geom->getSceneManager();
	this->geom = geom;

	//Init. variables
	setBlendMode(ALPHA_REJECT_IMPOSTOR);
		
	if (++selfInstances == 1){
		//Set up a single instance of a scene node which will be used when rendering impostor textures
		geom->getSceneNode()->createChildSceneNode("ImpostorPage::renderNode");
		geom->getSceneNode()->createChildSceneNode("ImpostorPage::cameraNode");
        ResourceGroupManager::getSingleton().createResourceGroup("Impostors");
	}
}
Exemple #16
0
//------------------------------------------------------------------------------
//## Basic
TEST_F(Test_UI_UIElement, RenderEffects)
{
    //* [ ] UISprite はデフォルトで BlendMode=Alpha
	{
        auto tex1 = Assets::loadTexture(LN_ASSETFILE("Sprite1.png"));

        //* [ ] Visible
        auto sprite1 = newObject<UISprite>();
        sprite1->setTexture(tex1);
        sprite1->setPosition(0, 0, 0);
        sprite1->setVisible(false);

        //* [ ] BlendMode
        auto sprite2 = newObject<UISprite>();
        sprite2->setTexture(tex1);
        sprite2->setBlendMode(BlendMode::Add);
        sprite2->setPosition(32, 0, 0);

        //* [ ] Opacity
        auto sprite3 = newObject<UISprite>();
        sprite3->setTexture(tex1);
        sprite3->setPosition(64, 0, 0);
        sprite3->setOpacity(0.5);

        //* [ ] ColorScale
        auto sprite4 = newObject<UISprite>();
        sprite4->setTexture(tex1);
        sprite4->setPosition(96, 0, 0);
        sprite4->setColorScale(Color(1, 0, 0, 1));

        //* [ ] BlendColor
        auto sprite5 = newObject<UISprite>();
        sprite5->setTexture(tex1);
        sprite5->setPosition(0, 32, 0);
        sprite5->setBlendColor(Color(1, 0, 0, 1));

        //* [ ] Tone
        auto sprite6 = newObject<UISprite>();
        sprite6->setTexture(tex1);
        sprite6->setPosition(32, 32, 0);
        sprite6->setTone(ColorTone(0.5, 0.3, 0.1, 1.0));

        TestEnv::updateFrame();
        ASSERT_SCREEN(LN_ASSETFILE("Result/Test_UI_UIElement-RenderEffects-1.png"));
        LN_TEST_CLEAN_SCENE;
	}
}
//------------------------------------------------------------------------------
//## Basic
TEST_F(Test_Visual_VisualComponent, BuiltinEffects)
{
    // TODO: Builtin shader ごとに行う
	{
        auto tex1 = Assets::loadTexture(LN_ASSETFILE("Sprite1.png"));

        //* [ ] Hide
        auto sprite1 = Sprite::create(tex1, 3, 3);
        //sprite1->setShadingModel(ShadingModel::UnLighting);
        sprite1->setPosition(-6, 0, 0);
        sprite1->setVisible(false);

        //* [ ] Normal
        auto sprite2 = Sprite::create(tex1, 3, 3);
        //sprite2->setShadingModel(ShadingModel::UnLighting);
        sprite2->setPosition(-3, 0, 0);

        //* [ ] Opacity
        auto sprite3 = Sprite::create(tex1, 3, 3);
        //sprite3->setShadingModel(ShadingModel::UnLighting);
        sprite3->setPosition(-6, 3, 0);
        sprite3->setBlendMode(BlendMode::Alpha);
        sprite3->setOpacity(0.5);

        //* [ ] ColorScale
        auto sprite4 = Sprite::create(tex1, 3, 3);
        //sprite4->setShadingModel(ShadingModel::UnLighting);
        sprite4->setPosition(-3, 3, 0);
        sprite4->setColorScale(Color(1, 0, 0, 1));

        //* [ ] BlendColor
        auto sprite5 = Sprite::create(tex1, 3, 3);
        //sprite5->setShadingModel(ShadingModel::UnLighting);
        sprite5->setPosition(0, 3, 0);
        sprite5->setBlendColor(Color(1, 0, 0, 1));

        //* [ ] Tone
        auto sprite6 = Sprite::create(tex1, 3, 3);
        //sprite6->setShadingModel(ShadingModel::UnLighting);
        sprite6->setPosition(3, 3, 0);
        sprite6->setTone(ColorTone(0.5, 0.3, 0.1, 1.0));

        TestEnv::updateFrame();
        ASSERT_SCREEN(LN_ASSETFILE("Visual/Result/Test_Visual_VisualComponent-BuiltinEffects-1.png"));
        LN_TEST_CLEAN_SCENE;
	}
}
Exemple #18
0
Graphics::Graphics(Profile &profile)
: mMinAspect(0.0f), mMaxAspect(0.0f), mVSync(true), mFPSTime(0), mNumFrames(0), mFPS(0.0f), mBlendMode(BLEND_ALPHA)
{
	// setup the graphics settings
	CL_DisplayWindowDescription desc;
	desc.set_title("Balance");
	desc.set_size(CL_Size(profile.getInt("width", 1024), profile.getInt("height", 768)), true);
	desc.set_swap_interval(mVSync ? 1 : 0);
	if (profile.getBool("fullscreen", true))
	{
		desc.set_decorations(false);
		desc.set_fullscreen(true);
	}
	else
	{
		desc.set_allow_resize(true);
	}
	mWindow = CL_DisplayWindow(desc);

	// make window visible while debugging under SciTE
	mWindow.show();

	// connect window signals
	mSlots.connect(Application::getSingleton().getSigUpdate(), this, &Graphics::onUpdate);
	mSlots.connect(mWindow.get_ic().get_mouse().sig_key_down(), this, &Graphics::onMouseDown);
	mSlots.connect(mWindow.get_ic().get_mouse().sig_key_dblclk(), this, &Graphics::onMouseDown);
	mSlots.connect(mWindow.get_ic().get_mouse().sig_key_up(), this, &Graphics::onMouseUp);
	mSlots.connect(mWindow.sig_resize(), this, &Graphics::onResize);
	mSlots.connect(mWindow.sig_window_close(), this, &Graphics::onClose);

	// initialize the graphics settings
	mWindow.get_gc().set_map_mode(cl_user_projection);
	setScreenSize(1024.0f, 768.0f);
	setBlendMode(mBlendMode);

	// save the current settings
	profile.setBool("fullscreen", desc.is_fullscreen());
	profile.setInt("width", desc.get_size().width);
	profile.setInt("height", desc.get_size().height);
}
Bubble::Bubble(NotificationEntity *entity)
    : DBlurEffectWidget(nullptr)
    , m_entity(entity)
    , m_icon(new AppIcon(this))
    , m_body(new AppBody(this))
    , m_actionButton(new ActionButton(this))
    , m_quitTimer(new QTimer(this))

{
    m_quitTimer->setInterval(60 * 1000);
    m_quitTimer->setSingleShot(true);

    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);

    m_wmHelper = DWindowManagerHelper::instance();

    m_handle = new DPlatformWindowHandle(this);
    m_handle->setTranslucentBackground(true);
    m_handle->setShadowRadius(14);
    m_handle->setShadowOffset(QPoint(0, 4));

    compositeChanged();

    setBlendMode(DBlurEffectWidget::BehindWindowBlend);
    setMaskColor(DBlurEffectWidget::LightColor);

    initUI();
    initAnimations();
    initTimers();

    setEntity(entity);

    connect(m_wmHelper, &DWindowManagerHelper::hasCompositeChanged, this, &Bubble::compositeChanged);
    connect(m_quitTimer, &QTimer::timeout, this, &Bubble::onDelayQuit);
}
void ParticleEmitter::setTexture(Texture* texture, BlendMode blendMode)
{
    // Create new batch before releasing old one, in case the same texture
    // is used for both (so it's not released before passing to the new batch).
    SpriteBatch* batch =  SpriteBatch::create(texture, NULL, _particleCountMax);
    batch->getSampler()->setFilterMode(Texture::LINEAR_MIPMAP_LINEAR, Texture::LINEAR);

    // Free existing batch
    SAFE_DELETE(_spriteBatch);

    _spriteBatch = batch;
    _spriteBatch->getStateBlock()->setDepthWrite(false);
    _spriteBatch->getStateBlock()->setDepthTest(true);

    setBlendMode(blendMode);
    _spriteTextureWidth = texture->getWidth();
    _spriteTextureHeight = texture->getHeight();
    _spriteTextureWidthRatio = 1.0f / (float)texture->getWidth();
    _spriteTextureHeightRatio = 1.0f / (float)texture->getHeight();

    // By default assume only one frame which uses the entire texture.
    Rectangle texCoord((float)texture->getWidth(), (float)texture->getHeight());
    setSpriteFrameCoords(1, &texCoord);
}
void StelQGLRenderer::drawText(const TextParams& params)
{
	statistics[TEXT_DRAWS] += 1.0;
	StelQGLTextureBackend* currentTexture = currentlyBoundTextures[0];

	if(params.string_.length() == 0)
	{
		return;
	}

	viewport.enablePainting();
	if(currentFontSet)
	{
		viewport.setFont(currentFont);
	}
	QPainter* painter = viewport.getPainter();
	Q_ASSERT_X(NULL != painter, Q_FUNC_INFO, 
	           "Trying to draw text but painting is disabled");

	QFontMetrics fontMetrics = painter->fontMetrics();

	StelProjectorP projector = NULL == params.projector_
	                         ? StelApp::getInstance().getCore()->getProjection2d() 
	                         : params.projector_;
	Vec3f win;
	if(params.doNotProject_) 
	{
		win = params.position_;
	}
	else if(!projector->project(params.position_, win))
	{
		viewport.disablePainting();
		return;
	}

	const int x = win[0];
	const int y = win[1];

	// Avoid drawing if outside viewport.
	// We do a worst-case approximation as getting exact text dimensions is expensive.
	// We also account for rotation by assuming the worst case in bot X and Y 
	// (culling with a rotating rectangle would be expensive)
	const int cullDistance = 
		std::max(fontMetrics.height(), params.string_.size() * fontMetrics.maxWidth());
	const Vec4i viewXywh = projector->getViewportXywh();
	const int viewMinX = viewXywh[0];
	const int viewMinY = viewXywh[1];
	const int viewMaxX = viewMinX + viewXywh[2];
	const int viewMaxY = viewMinY + viewXywh[3];

	if(y + cullDistance < viewMinY || y - cullDistance > viewMaxY ||
	   x + cullDistance < viewMinX || x - cullDistance > viewMaxX)
	{
		viewport.disablePainting();
		return;
	}

	if(projector->useGravityLabels() && !params.noGravity_)
	{
		drawTextGravityHelper(params, *painter, x, y, projector);
		return;
	}
	
	const int pixelSize   = painter->font().pixelSize();
	// Strings drawn by drawText() can differ by text, font size, or the font itself.
	const QByteArray hash = params.string_.toUtf8() + QByteArray::number(pixelSize) + 
	                        painter->font().family().toUtf8();
	StelQGLTextureBackend* textTexture = textTextureCache.object(hash);

	// No texture in cache for this string, need to draw it.
	if (NULL == textTexture) 
	{
		const QRect extents = fontMetrics.boundingRect(params.string_);

		// Width and height of the text. 
		// Texture width/height is required to be at least equal to this.
		//
		// Both X and Y need to be at least 1 so we don't create an empty image 
		// (doesn't work with textures)
		const int requiredWidth  = std::max(1, extents.width() + 1 + static_cast<int>(0.02f * extents.width()));
		const int requiredHeight = std::max(1, extents.height());
		// Create temporary image and render text into it

		// QImage is used solely to reuse existing QGLTextureBackend constructor 
		// function. QPixmap could be used as well (not sure which is faster, 
		// needs profiling)
		QImage image = areNonPowerOfTwoTexturesSupported() 
		             ? QImage(requiredWidth, requiredHeight, QImage::Format_ARGB32_Premultiplied) 
		             : QImage(StelUtils::smallestPowerOfTwoGreaterOrEqualTo(requiredWidth), 
		                      StelUtils::smallestPowerOfTwoGreaterOrEqualTo(requiredHeight),
		                      QImage::Format_ARGB32);
		image.fill(Qt::transparent);

		QPainter fontPainter(&image);
		fontPainter.setFont(painter->font());
		fontPainter.setRenderHints(QPainter::TextAntialiasing, true);
		fontPainter.setPen(Qt::white);

		// The second argument ensures the text is positioned correctly even if 
		// the image is enlarged to power-of-two.
		fontPainter.drawText(-extents.x(), 
		                     image.height() - requiredHeight - extents.y(), 
		                     params.string_);

		textTexture = StelQGLTextureBackend::constructFromImage
			(this, QString(), TextureParams().filtering(TextureFiltering_Linear), image);
		const QSize size = textTexture->getDimensions();
		if(!textTexture->getStatus() == TextureStatus_Loaded)
		{
			qWarning() << "Texture error: " << textTexture->getErrorMessage();
			Q_ASSERT_X(false, Q_FUNC_INFO, "Failed to construct a text texture");
		}
		textTextureCache.insert(hash, textTexture, 4 * size.width() * size.height());
	}

	// Even if NPOT textures are not supported, we always draw the full rectangle 
	// of the texture. The extra space is fully transparent, so it's not an issue.

	// Shortcut variables to calculate the rectangle.
	const QSize size   = textTexture->getDimensions();
	const float w      = size.width();
	const float h      = size.height();
	const float xShift = params.xShift_;
	const float yShift = params.yShift_;

	const float angleDegrees = 
		params.angleDegrees_ + 
		(params.noGravity_ ? 0.0f : projector->getDefaultAngleForGravityText());
	// Zero out very small angles.
	// 
	// (this could also be used to optimize the case with zero angled
	//  to avoid sin/cos if needed)
	const bool  angled = std::fabs(angleDegrees) >= 1.0f * M_PI / 180.f;
	const float cosr   = angled  ? std::cos(angleDegrees * M_PI / 180.0) : 1.0f;
	const float sinr   = angled  ? std::sin(angleDegrees * M_PI / 180.0) : 0.0f;

	// Corners of the (possibly rotated) texture rectangle.
	const Vec2f ne(round(x + cosr * xShift       - sinr * yShift),
	               round(y + sinr * xShift       + cosr * yShift));
	const Vec2f nw(round(x + cosr * (w + xShift) - sinr * yShift),
	               round(y + sinr * (w + xShift) + cosr * yShift));
	const Vec2f se(round(x + cosr * xShift       - sinr * (h + yShift)),
	               round(y + sinr * xShift       + cosr * (h + yShift)));
	const Vec2f sw(round(x + cosr * (w + xShift) - sinr * (h + yShift)),
	               round(y + sinr * (w + xShift) + cosr * (h + yShift)));

	// Construct the text vertex buffer if it doesn't exist yet, otherwise clear it.
	if(NULL == textBuffer)
	{
		textBuffer = createVertexBuffer<TexturedVertex>(PrimitiveType_TriangleStrip);
	}
	else
	{
		textBuffer->unlock();
		textBuffer->clear();
	}

	textBuffer->addVertex(TexturedVertex(ne, Vec2f(0.0f, 0.0f)));
	textBuffer->addVertex(TexturedVertex(nw, Vec2f(1.0f, 0.0f)));
	textBuffer->addVertex(TexturedVertex(se, Vec2f(0.0f, 1.0f)));
	textBuffer->addVertex(TexturedVertex(sw, Vec2f(1.0f, 1.0f)));
	textBuffer->lock();

	// Draw.
	const BlendMode oldBlendMode = blendMode;
	setBlendMode(BlendMode_Alpha);
	textTexture->bind(0);
	drawVertexBuffer(textBuffer);
	setBlendMode(oldBlendMode);

	// Reset user-bound texture.
	if(NULL != currentTexture)
	{
		currentTexture->bind(0);
	}
	viewport.disablePainting();
}
bool QgsComposerItem::_readXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  Q_UNUSED( doc );
  if ( itemElem.isNull() )
  {
    return false;
  }

  //rotation
  setItemRotation( itemElem.attribute( "itemRotation", "0" ).toDouble() );

  //uuid
  mUuid = itemElem.attribute( "uuid", QUuid::createUuid().toString() );

  // temporary for groups imported from templates
  mTemplateUuid = itemElem.attribute( "templateUuid" );

  //id
  QString id = itemElem.attribute( "id", "" );
  setId( id );

  //frame
  QString frame = itemElem.attribute( "frame" );
  if ( frame.compare( "true", Qt::CaseInsensitive ) == 0 )
  {
    mFrame = true;
  }
  else
  {
    mFrame = false;
  }

  //frame
  QString background = itemElem.attribute( "background" );
  if ( background.compare( "true", Qt::CaseInsensitive ) == 0 )
  {
    mBackground = true;
  }
  else
  {
    mBackground = false;
  }

  //position lock for mouse moves/resizes
  QString positionLock = itemElem.attribute( "positionLock" );
  if ( positionLock.compare( "true", Qt::CaseInsensitive ) == 0 )
  {
    setPositionLock( true );
  }
  else
  {
    setPositionLock( false );
  }

  //position
  int page;
  double x, y, pagex, pagey, width, height;
  bool xOk, yOk, pageOk, pagexOk, pageyOk, widthOk, heightOk, positionModeOK;

  x = itemElem.attribute( "x" ).toDouble( &xOk );
  y = itemElem.attribute( "y" ).toDouble( &yOk );
  page = itemElem.attribute( "page" ).toInt( &pageOk );
  pagex = itemElem.attribute( "pagex" ).toDouble( &pagexOk );
  pagey = itemElem.attribute( "pagey" ).toDouble( &pageyOk );
  width = itemElem.attribute( "width" ).toDouble( &widthOk );
  height = itemElem.attribute( "height" ).toDouble( &heightOk );
  mLastUsedPositionMode = ( ItemPositionMode )itemElem.attribute( "positionMode" ).toInt( &positionModeOK );
  if ( !positionModeOK )
  {
    mLastUsedPositionMode = UpperLeft;
  }
  if ( pageOk && pagexOk && pageyOk )
  {
    xOk = true;
    yOk = true;
    x = pagex;
    y = ( page - 1 ) * ( mComposition->paperHeight() + composition()->spaceBetweenPages() ) + pagey;
  }

  if ( !xOk || !yOk || !widthOk || !heightOk )
  {
    return false;
  }

  mLastValidViewScaleFactor = itemElem.attribute( "lastValidViewScaleFactor", "-1" ).toDouble();

  setSceneRect( QRectF( x, y, width, height ) );
  setZValue( itemElem.attribute( "zValue" ).toDouble() );

  //pen
  QDomNodeList frameColorList = itemElem.elementsByTagName( "FrameColor" );
  if ( frameColorList.size() > 0 )
  {
    QDomElement frameColorElem = frameColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk, widthOk;
    int penRed, penGreen, penBlue, penAlpha;
    double penWidth;

    penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk );
    penRed = frameColorElem.attribute( "red" ).toDouble( &redOk );
    penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk );
    penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk );
    penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk );
    mFrameJoinStyle = QgsSymbolLayerV2Utils::decodePenJoinStyle( itemElem.attribute( "frameJoinStyle", "miter" ) );

    if ( redOk && greenOk && blueOk && alphaOk && widthOk )
    {
      QPen framePen( QColor( penRed, penGreen, penBlue, penAlpha ) );
      framePen.setWidthF( penWidth );
      framePen.setJoinStyle( mFrameJoinStyle );
      setPen( framePen );
    }
  }

  //brush
  QDomNodeList bgColorList = itemElem.elementsByTagName( "BackgroundColor" );
  if ( bgColorList.size() > 0 )
  {
    QDomElement bgColorElem = bgColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk;
    int bgRed, bgGreen, bgBlue, bgAlpha;
    bgRed = bgColorElem.attribute( "red" ).toDouble( &redOk );
    bgGreen = bgColorElem.attribute( "green" ).toDouble( &greenOk );
    bgBlue = bgColorElem.attribute( "blue" ).toDouble( &blueOk );
    bgAlpha = bgColorElem.attribute( "alpha" ).toDouble( &alphaOk );
    if ( redOk && greenOk && blueOk && alphaOk )
    {
      QColor brushColor( bgRed, bgGreen, bgBlue, bgAlpha );
      setBackgroundColor( brushColor );
    }
  }

  //blend mode
  setBlendMode( QgsMapRenderer::getCompositionMode(( QgsMapRenderer::BlendMode ) itemElem.attribute( "blendMode", "0" ).toUInt() ) );

  //transparency
  setTransparency( itemElem.attribute( "transparency" , "0" ).toInt() );

  return true;
}
Exemple #23
0
void BlendModeCommand::readProperties(boost::property_tree::wptree& pt)
{
    AbstractCommand::readProperties(pt);

    if (pt.count(L"blendmode") > 0) setBlendMode(QString::fromStdWString(pt.get<std::wstring>(L"blendmode")));
}
Exemple #24
0
void GLRenderer::init(Device *device, Renderer *other) {
	Renderer::init(device, other);

	m_driverRenderer = (char *) glGetString(GL_RENDERER);
	m_driverVendor = (char *) glGetString(GL_VENDOR);
	m_driverVersion = (char *) glGetString(GL_VERSION);

	Log(m_logLevel, "OpenGL renderer : %s", m_driverRenderer.c_str());
	Log(m_logLevel, "OpenGL vendor   : %s", m_driverVendor.c_str());
	Log(m_logLevel, "OpenGL version  : %s", m_driverVersion.c_str());

	/* OpenGL extensions */
	GLenum err = glewInit();
	if (err != GLEW_OK)
		Log(EError, "GLEW Error: %s\n", glewGetErrorString(err));

	if (glewIsSupported("GL_EXT_framebuffer_object")) {
		m_capabilities->setSupported(
			RendererCapabilities::ERenderToTexture, true);
		Log(m_logLevel, "Capabilities: Framebuffers objects are supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Framebuffers objects are NOT supported!");
	}

	if (glewIsSupported("GL_ARB_shading_language_100")) {
		m_capabilities->setSupported(
			RendererCapabilities::EShadingLanguage, true);
		Log(m_logLevel, "Capabilities: GLSL is supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: GLSL is NOT supported!");
	}

	if (glewIsSupported("GL_ARB_texture_float")) {
		m_capabilities->setSupported(
			RendererCapabilities::EFloatingPointTextures, true);
		Log(m_logLevel, "Capabilities: Floating point textures are supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Floating point textures are NOT supported!");
	}

	if (glewIsSupported("GL_ARB_color_buffer_float")) {
		m_capabilities->setSupported(
			RendererCapabilities::EFloatingPointBuffer, true);
		Log(m_logLevel, "Capabilities: Floating point color buffers are supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Floating point color buffers are NOT supported!");
	}

	if (glewIsSupported("GL_EXT_framebuffer_blit")) {
		m_capabilities->setSupported(
			RendererCapabilities::EBufferBlit, true);
		Log(m_logLevel, "Capabilities: Fast buffer blitting is supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Fast buffer blitting is NOT supported!");
	}

	if (glewIsSupported("GL_EXT_framebuffer_multisample") &&
		glewIsSupported("GL_EXT_framebuffer_blit") &&
		glewIsSupported("GL_ARB_texture_multisample")) {
		m_capabilities->setSupported(
			RendererCapabilities::EMultisampleRenderToTexture, true);
		Log(m_logLevel, "Capabilities: Multisample framebuffer objects are supported.");
	} else {
		Log((m_warnLogLevel == EWarn) ? EInfo : m_warnLogLevel,
			"Capabilities: Multisample framebuffer objects are NOT supported!");
	}

	if (glewIsSupported("GL_ARB_vertex_buffer_object")) {
		m_capabilities->setSupported(
			RendererCapabilities::EVertexBufferObjects, true);
		Log(m_logLevel, "Capabilities: Vertex buffer objects are supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Vertex buffer objects are NOT supported!");
	}

	if (glewIsSupported("GL_EXT_geometry_shader4") && glewIsSupported("GL_EXT_gpu_shader4")) {
		m_capabilities->setSupported(
			RendererCapabilities::EGeometryShaders, true);
		Log(m_logLevel, "Capabilities: Geometry shaders are supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Geometry shaders are NOT supported!");
	}

	if (glewIsSupported("GL_ARB_shader_texture_lod") || glewIsSupported("GL_EXT_gpu_shader4")) {
		m_capabilities->setSupported(
			RendererCapabilities::ECustomTextureFiltering, true);
		Log(m_logLevel, "Capabilities: Custom texture filtering is supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Custom texture filtering is NOT supported.");
	}

	bool radeonOnOSX = false;

#if defined(__OSX__)
	/* Synchronization objects cause problem with ATI cards on OSX -- ignore
	   them even if the driver claims to support it */
	radeonOnOSX = boost::to_lower_copy(m_driverRenderer).find("radeon") != std::string::npos;
#endif

	if (glewIsSupported("GL_ARB_sync") && !radeonOnOSX) {
		m_capabilities->setSupported(
			RendererCapabilities::ESyncObjects, true);
		Log(m_logLevel, "Capabilities: Synchronization objects are supported.");
	} else {
		Log(m_warnLogLevel, "Capabilities: Synchronization objects are NOT supported!");
	}

	if (glewIsSupported("GL_NV_vertex_buffer_unified_memory")) {
		m_capabilities->setSupported(
			RendererCapabilities::EBindless, true);
		Log(m_logLevel, "Capabilities: Bindless rendering is supported.");
	} else {
		Log((m_warnLogLevel == EWarn) ? EInfo : m_warnLogLevel,
			"Capabilities: Bindless rendering is NOT supported!");
	}

	/* Hinting */
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
	glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
	glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
	glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

	/* Disable color value clamping */
	if (m_capabilities->isSupported(
			RendererCapabilities::EFloatingPointBuffer)) {
		glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, GL_FALSE);
		glClampColorARB(GL_CLAMP_READ_COLOR_ARB, GL_FALSE);
		glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB, GL_FALSE);
	}

	/* Clip to viewport */
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	setBlendMode(EBlendNone);

	glEnable(GL_POINT_SMOOTH);

	m_normalsEnabled = false;
	m_texcoordsEnabled = false;
	m_tangentsEnabled = false;
	m_colorsEnabled = false;
	m_stride = -1;
	m_queuedTriangles = 0;
	m_transmitOnlyPositions = false;

	checkError();
}
Exemple #25
0
void GameState::addMapBody(const Map::Node& n)
{
    switch (n.type)
    {
    case Category::Block:
        addBlock(n.position, n.size);
        break;
    case Category::Solid:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Solid, n.size));
        m_scene.addNode(node, Scene::Solid);
    }
        break;
    case Category::Water:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        auto drawable = static_cast<WaterDrawable*>(m_mapController.getDrawable(MapController::MapDrawable::Water));
        drawable->setSize(n.size);
        node->setDrawable(drawable);
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Water, n.size));
        node->addObserver(m_particleController);
        m_scene.addNode(node, Scene::Water);
    }
        break;
    case Category::Item:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setCategory(Category::Item);
        node->setDrawable(m_mapController.getDrawable(MapController::MapDrawable::Item));
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Item, n.size));
        node->addObserver(m_particleController);
        node->addObserver(m_audioController);

        auto light = m_scene.addLight(sf::Vector3f(0.34f, 0.96f, 1.f), 400.f);
        if (light)
        {
            light->setDepth(50.f);
            node->setLight(light);
        }
        node->setBlendMode(sf::BlendAdd);
        m_scene.addNode(node, Scene::DynamicFront);
    }
        break;
    case Category::Light:
    {
        auto node = std::make_unique<Node>();
        node->setCategory(Category::Light);
        //TODO magix0r numb0rz
        auto light = m_scene.addLight(colourToVec3(n.colour), 700.f);
        light->setDepth(50.f);
        node->setLight(light);
        node->setPosition(n.position + (n.size / 2.f));
        node->addObserver(*light);
        node->setDrawable(&lightDrawable);
        node->setBlendMode(sf::BlendAlpha);

        //if (n.anchorOffset) //TODO make not broken (see contraint solve())
        //{
        //    //we want a constraint on this light
        //    node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Type::FreeForm, { lightDrawable.getRadius(), lightDrawable.getRadius() }));

        //    auto anchorNode = std::make_unique<Node>();
        //    anchorNode->setPosition(n.position);
        //    anchorNode->move(0.f, -n.anchorOffset);
        //    anchorNode->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Type::Anchor, { lightDrawable.getRadius(), lightDrawable.getRadius() }));
        //    anchorNode->setDrawable(&c1);

        //    m_collisionWorld.addConstraint(anchorNode->getCollisionBody(), node->getCollisionBody(), n.anchorOffset);
        //    m_scene.addNode(anchorNode);
        //}

        m_scene.addNode(node, Scene::Background);
        break;
    }

    case Category::HatDropped:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setDrawable(m_mapController.getDrawable(MapController::MapDrawable::Hat));
        node->setCollisionBody(m_collisionWorld.addBody(CollisionWorld::Body::Type::FreeForm, n.size));
        node->setCategory(n.type);
        auto light = m_scene.addLight(sf::Vector3f(1.f, 0.9f, 0.f), 200.f);
        light->setDepth(50.f);
        node->setLight(light);

        node->addObserver(m_particleController);
        node->addObserver(m_audioController);
        node->addObserver(m_mapController);
        node->addObserver(m_scoreBoard);
        node->addObserver(m_players[0]);
        node->addObserver(m_players[1]);

        m_scene.addNode(node, Scene::DynamicFront);
        break;
    }
    case Category::Bat:
    case Category::Bird:
    {
        auto node = std::make_unique<Node>();
        node->setPosition(n.position);
        node->setCategory(n.type);
        node->setDrawable(m_mapController.getDrawable((n.type == Category::Bat) ? MapController::MapDrawable::Bat : MapController::MapDrawable::Bird));
        m_scene.addNode(node, Scene::FrontDetail);
        break;
    }
    default: break;
    }
}
Exemple #26
0
ParticleSystem::Ptr ParticleSystem::create(Particle::Type type, MessageBus& mb)
{
    auto ps = std::make_unique<ParticleSystem>(mb);

    switch (type)
    {
    case Particle::Type::Trail:
    {
        const float scale = Util::Random::value(2.f, 4.f);
        ScaleAffector sa({ scale, scale });
        ps->addAffector<ScaleAffector>(sa);

        ForceAffector fa({ 0.f, -190.f });
        ps->addAffector<ForceAffector>(fa);

        ps->setEmitRate(Util::Random::value(0.5f, 2.5f));
        ps->setBlendMode(sf::BlendAdd);
        ps->setEmitRate(3.f);
        ps->setRandomInitialVelocity(trailVelocities);
        ps->start(1u, Util::Random::value(0.2f, 1.f));
    }
        break;

    case Particle::Type::Echo:
    {
        ScaleAffector sa({ 1.6f, 1.6f });
        ps->addAffector<ScaleAffector>(sa);

        ps->setBlendMode(sf::BlendAdd);
        ps->setParticleLifetime(0.95f);
        ps->followParent(true);
    }
        break;

    case Particle::Type::Sparkle:
    {
        sparkPositions = createPoints(sf::Vector2f(), 20, 18.f);

        ps->setParticleLifetime(0.6f);
        ps->setParticleSize({ 10.f, 10.f });
        ps->setRandomInitialVelocity(sparkVelocities);
        ps->setRandomInitialPosition(sparkPositions);
        ps->setBlendMode(sf::BlendAdd);

        ScaleAffector sa({ 2.f, 2.f });
        ps->addAffector(sa);

        RotateAffector ra(140.f);
        ps->addAffector(ra);
    }
    break;
    case Particle::Type::Ident:
    {
        identPositions = createPoints({}, 20, 20.f);

        ps->setParticleLifetime(0.6f);
        ps->setParticleSize({ 20.f, 20.f });
        ps->setInitialVelocity({ 0.f, 0.f });
        ps->setRandomInitialPosition(identPositions);
        ps->setBlendMode(sf::BlendAdd);
        ps->followParent(true);
        ps->setEmitRate(7.f);
        ps->start();
    }
    default: break;
    }


    return std::move(ps);
}
 void VStyleActor::deserialize(const deserializedata* data)
 {
     inherited::deserialize(data);
     setColor(hex2color(data->node.attribute("color").as_string("ffffffff")));
     setBlendMode((blend_mode)(data->node.attribute("blend").as_int(blend_premultiplied_alpha)));
 }
    std::shared_ptr<gameplay::Node> Room::createSceneNode(gameplay::Game* game,
                                                          size_t roomId,
                                                          const level::Level& level,
                                                          const std::vector<std::shared_ptr<gameplay::Texture>>& textures,
                                                          const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& materials,
                                                          const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& waterMaterials,
                                                          const std::vector<std::shared_ptr<gameplay::Model>>& staticMeshes,
                                                          render::TextureAnimator& animator)
    {
        RenderModel renderModel;
        std::map<TextureLayoutProxy::TextureKey, size_t> texBuffers;
        std::vector<RenderVertex> vbuf;
        auto mesh = std::make_shared<gameplay::Mesh>(RenderVertex::getFormat(), vbuf.size(), true);

        for( const QuadFace& quad : rectangles )
        {
            const TextureLayoutProxy& proxy = level.m_textureProxies.at(quad.proxyId);

            if( texBuffers.find(proxy.textureKey) == texBuffers.end() )
            {
                texBuffers[proxy.textureKey] = renderModel.m_parts.size();
                renderModel.m_parts.emplace_back();
                auto it = isWaterRoom() ? waterMaterials.find(proxy.textureKey) : materials.find(proxy.textureKey);
                Expects(it != (isWaterRoom() ? waterMaterials.end() : materials.end()));
                renderModel.m_parts.back().material = it->second;
            }
            const auto partId = texBuffers[proxy.textureKey];

            const auto firstVertex = vbuf.size();
            for( int i = 0; i < 4; ++i )
            {
                RenderVertex iv;
                iv.position = vertices[quad.vertices[i]].position.toRenderSystem();
                iv.color = vertices[quad.vertices[i]].color;
                iv.texcoord0 = proxy.uvCoordinates[i].toGl();
                vbuf.push_back(iv);
            }

            animator.registerVertex(quad.proxyId, {mesh, partId}, 0, firstVertex + 0);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 0);
            animator.registerVertex(quad.proxyId, {mesh, partId}, 1, firstVertex + 1);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 1);
            animator.registerVertex(quad.proxyId, {mesh, partId}, 2, firstVertex + 2);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 2);
            animator.registerVertex(quad.proxyId, {mesh, partId}, 0, firstVertex + 0);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 0);
            animator.registerVertex(quad.proxyId, {mesh, partId}, 2, firstVertex + 2);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 2);
            animator.registerVertex(quad.proxyId, {mesh, partId}, 3, firstVertex + 3);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 3);
        }
        for( const Triangle& tri : triangles )
        {
            const TextureLayoutProxy& proxy = level.m_textureProxies.at(tri.proxyId);

            if( texBuffers.find(proxy.textureKey) == texBuffers.end() )
            {
                texBuffers[proxy.textureKey] = renderModel.m_parts.size();
                renderModel.m_parts.emplace_back();
                auto it = isWaterRoom() ? waterMaterials.find(proxy.textureKey) : materials.find(proxy.textureKey);
                Expects(it != (isWaterRoom() ? waterMaterials.end() : materials.end()));
                renderModel.m_parts.back().material = it->second;
            }
            const auto partId = texBuffers[proxy.textureKey];

            const auto firstVertex = vbuf.size();
            for( int i = 0; i < 3; ++i )
            {
                RenderVertex iv;
                iv.position = vertices[tri.vertices[i]].position.toRenderSystem();
                iv.color = vertices[tri.vertices[i]].color;
                iv.texcoord0 = proxy.uvCoordinates[i].toGl();
                vbuf.push_back(iv);
            }

            animator.registerVertex(tri.proxyId, {mesh, partId}, 0, firstVertex + 0);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 0);
            animator.registerVertex(tri.proxyId, {mesh, partId}, 1, firstVertex + 1);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 1);
            animator.registerVertex(tri.proxyId, {mesh, partId}, 2, firstVertex + 2);
            renderModel.m_parts[partId].indices.emplace_back(firstVertex + 2);
        }

        mesh->rebuild(reinterpret_cast<float*>(vbuf.data()), vbuf.size());
        auto resModel = renderModel.toModel(mesh);
        node = std::make_shared<gameplay::Node>("Room:" + boost::lexical_cast<std::string>(roomId));
        node->setDrawable(resModel);

        for( Light& light : lights )
        {
            const auto f = std::abs(light.specularIntensity) / 8191.0f;
            BOOST_ASSERT(f >= 0 && f <= 1);

            switch( light.getLightType() )
            {
                case LightType::Shadow:
                    BOOST_LOG_TRIVIAL(debug) << "Light: Shadow";
                    light.node = gameplay::Light::createPoint(light.color.r / 255.0f * f, light.color.g / 255.0f * f, light.color.b / 255.0f * f, light.specularFade);
                    break;
                case LightType::Null:
                case LightType::Point:
                    BOOST_LOG_TRIVIAL(debug) << "Light: Null/Point";
                    light.node = gameplay::Light::createPoint(light.color.r / 255.0f * f, light.color.g / 255.0f * f, light.color.b / 255.0f * f, light.specularFade);
                    break;
                case LightType::Spotlight:
                    BOOST_LOG_TRIVIAL(debug) << "Light: Spot";
                    light.node = gameplay::Light::createSpot(light.color.r / 255.0f * f, light.color.g / 255.0f * f, light.color.b / 255.0f * f, light.specularFade, light.r_inner, light.r_outer);
                    break;
                case LightType::Sun:
                    BOOST_LOG_TRIVIAL(debug) << "Light: Sun";
                    light.node = gameplay::Light::createDirectional(light.color.r / 255.0f * f, light.color.g / 255.0f * f, light.color.b / 255.0f * f);
                    break;
            }

            BOOST_LOG_TRIVIAL(debug) << "  - Position: " << light.position.X << "/" << light.position.Y << "/" << light.position.Z;
            BOOST_LOG_TRIVIAL(debug) << "  - Length: " << light.length;
            BOOST_LOG_TRIVIAL(debug) << "  - Color: " << light.color.a / 255.0f << "/" << light.color.r / 255.0f << "/" << light.color.g / 255.0f << "/" << light.color.b / 255.0f;
            BOOST_LOG_TRIVIAL(debug) << "  - Specular Fade: " << light.specularFade;
            BOOST_LOG_TRIVIAL(debug) << "  - Specular Intensity: " << light.specularIntensity;
            BOOST_LOG_TRIVIAL(debug) << "  - Inner: " << light.r_inner;
            BOOST_LOG_TRIVIAL(debug) << "  - Outer: " << light.r_outer;
            BOOST_LOG_TRIVIAL(debug) << "  - Intensity: " << light.intensity;
        }

        for( const RoomStaticMesh& sm : this->staticMeshes )
        {
            auto idx = level.findStaticMeshIndexById(sm.meshId);
            BOOST_ASSERT(idx >= 0);
            BOOST_ASSERT(static_cast<size_t>(idx) < staticMeshes.size());
            auto subNode = std::make_shared<gameplay::Node>("");
            subNode->setDrawable(staticMeshes[idx]);
            subNode->setLocalMatrix(glm::translate(glm::mat4{1.0f}, (sm.position - position).toRenderSystem()) * glm::rotate(glm::mat4{1.0f}, util::auToRad(sm.rotation), glm::vec3{0,-1,0}));
            node->addChild(subNode);
        }
        node->setLocalMatrix(glm::translate(glm::mat4{1.0f}, position.toRenderSystem()));

        for( const Sprite& sprite : sprites )
        {
            BOOST_ASSERT(sprite.vertex < vertices.size());
            BOOST_ASSERT(sprite.texture < level.m_spriteTextures.size());

            const SpriteTexture& tex = level.m_spriteTextures[sprite.texture];

            auto spriteNode = std::make_shared<gameplay::Sprite>(game, textures[tex.texture], tex.right_side - tex.left_side + 1, tex.bottom_side - tex.top_side + 1, tex.buildSourceRectangle());
            spriteNode->setBlendMode(gameplay::Sprite::BLEND_ADDITIVE);

            auto n = std::make_shared<gameplay::Node>("");
            n->setDrawable(spriteNode);
            n->setLocalMatrix(glm::translate(glm::mat4{1.0f}, (vertices[sprite.vertex].position - core::TRCoordinates{0, tex.bottom_side / 2, 0}).toRenderSystem()));

            node->addChild(n);
        }

        // resultNode->addShadowVolumeSceneNode();

        return node;
    }
Exemple #29
0
bool QgsComposerItem::_readXml( const QDomElement &itemElem, const QDomDocument &doc )
{
  Q_UNUSED( doc );
  if ( itemElem.isNull() )
  {
    return false;
  }

  QgsComposerObject::readXml( itemElem, doc );

  //rotation
  setItemRotation( itemElem.attribute( QStringLiteral( "itemRotation" ), QStringLiteral( "0" ) ).toDouble() );

  //uuid
  mUuid = itemElem.attribute( QStringLiteral( "uuid" ), QUuid::createUuid().toString() );

  // temporary for groups imported from templates
  mTemplateUuid = itemElem.attribute( QStringLiteral( "templateUuid" ) );

  //id
  QString id = itemElem.attribute( QStringLiteral( "id" ), QLatin1String( "" ) );
  setId( id );

  //frame
  QString frame = itemElem.attribute( QStringLiteral( "frame" ) );
  if ( frame.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 )
  {
    mFrame = true;
  }
  else
  {
    mFrame = false;
  }

  //frame
  QString background = itemElem.attribute( QStringLiteral( "background" ) );
  if ( background.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 )
  {
    mBackground = true;
  }
  else
  {
    mBackground = false;
  }

  //position lock for mouse moves/resizes
  QString positionLock = itemElem.attribute( QStringLiteral( "positionLock" ) );
  if ( positionLock.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 )
  {
    setPositionLock( true );
  }
  else
  {
    setPositionLock( false );
  }

  //visibility
  setVisibility( itemElem.attribute( QStringLiteral( "visibility" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );

  //position
  int page;
  double x, y, pagex, pagey, width, height;
  bool xOk, yOk, pageOk, pagexOk, pageyOk, widthOk, heightOk, positionModeOK;

  x = itemElem.attribute( QStringLiteral( "x" ) ).toDouble( &xOk );
  y = itemElem.attribute( QStringLiteral( "y" ) ).toDouble( &yOk );
  page = itemElem.attribute( QStringLiteral( "page" ) ).toInt( &pageOk );
  pagex = itemElem.attribute( QStringLiteral( "pagex" ) ).toDouble( &pagexOk );
  pagey = itemElem.attribute( QStringLiteral( "pagey" ) ).toDouble( &pageyOk );
  width = itemElem.attribute( QStringLiteral( "width" ) ).toDouble( &widthOk );
  height = itemElem.attribute( QStringLiteral( "height" ) ).toDouble( &heightOk );
  mLastUsedPositionMode = static_cast< ItemPositionMode >( itemElem.attribute( QStringLiteral( "positionMode" ) ).toInt( &positionModeOK ) );
  if ( !positionModeOK )
  {
    mLastUsedPositionMode = UpperLeft;
  }
  if ( pageOk && pagexOk && pageyOk )
  {
    xOk = true;
    yOk = true;
    x = pagex;
    y = ( page - 1 ) * ( mComposition->paperHeight() + composition()->spaceBetweenPages() ) + pagey;
  }

  if ( !xOk || !yOk || !widthOk || !heightOk )
  {
    return false;
  }

  mLastValidViewScaleFactor = itemElem.attribute( QStringLiteral( "lastValidViewScaleFactor" ), QStringLiteral( "-1" ) ).toDouble();

  setZValue( itemElem.attribute( QStringLiteral( "zValue" ) ).toDouble() );

  QgsExpressionContext context = createExpressionContext();

  //pen
  QDomNodeList frameColorList = itemElem.elementsByTagName( QStringLiteral( "FrameColor" ) );
  if ( !frameColorList.isEmpty() )
  {
    QDomElement frameColorElem = frameColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk, widthOk;
    int penRed, penGreen, penBlue, penAlpha;
    double penWidth;

    penWidth = itemElem.attribute( QStringLiteral( "outlineWidth" ) ).toDouble( &widthOk );
    penRed = frameColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk );
    penGreen = frameColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk );
    penBlue = frameColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk );
    penAlpha = frameColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk );
    mFrameJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( QStringLiteral( "frameJoinStyle" ), QStringLiteral( "miter" ) ) );

    if ( redOk && greenOk && blueOk && alphaOk && widthOk )
    {
      mFrameColor = QColor( penRed, penGreen, penBlue, penAlpha );
      mFrameWidth = penWidth;
      QPen framePen( mFrameColor );
      framePen.setWidthF( mFrameWidth );
      framePen.setJoinStyle( mFrameJoinStyle );
      setPen( framePen );
      //apply any data defined settings
      refreshFrameColor( false, context );
    }
  }

  //brush
  QDomNodeList bgColorList = itemElem.elementsByTagName( QStringLiteral( "BackgroundColor" ) );
  if ( !bgColorList.isEmpty() )
  {
    QDomElement bgColorElem = bgColorList.at( 0 ).toElement();
    bool redOk, greenOk, blueOk, alphaOk;
    int bgRed, bgGreen, bgBlue, bgAlpha;
    bgRed = bgColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk );
    bgGreen = bgColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk );
    bgBlue = bgColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk );
    bgAlpha = bgColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk );
    if ( redOk && greenOk && blueOk && alphaOk )
    {
      mBackgroundColor = QColor( bgRed, bgGreen, bgBlue, bgAlpha );
      setBrush( QBrush( mBackgroundColor, Qt::SolidPattern ) );
    }
    //apply any data defined settings
    refreshBackgroundColor( false, context );
  }

  //blend mode
  setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( QStringLiteral( "blendMode" ), QStringLiteral( "0" ) ).toUInt() ) ) );

  //opacity
  if ( itemElem.hasAttribute( QStringLiteral( "opacity" ) ) )
  {
    setItemOpacity( itemElem.attribute( QStringLiteral( "opacity" ), QStringLiteral( "1" ) ).toDouble() );
  }
  else
  {
    setItemOpacity( 1.0 - itemElem.attribute( QStringLiteral( "transparency" ), QStringLiteral( "0" ) ).toInt() / 100.0 );
  }

  mExcludeFromExports = itemElem.attribute( QStringLiteral( "excludeFromExports" ), QStringLiteral( "0" ) ).toInt();
  mEvaluatedExcludeFromExports = mExcludeFromExports;

  QRectF evaluatedRect = evalItemRect( QRectF( x, y, width, height ) );
  setSceneRect( evaluatedRect );

  return true;
}
Exemple #30
0
void EndScene::_draw(float time)
{
	std::vector<vec3> path;

	skrand(625734);
	for (int i = 0; i < 10; i++)
		path.push_back(endCamPos + vec3(rand(-1.f, 1.f), rand(-1.f, 1.f), rand(-1.f, 1.f)));

	mat4 mPersp = perspective(45.0f, demo.aspect, 0.5f, 1000.0f);
	mat4 mCamera = lookAt(interpolatePath(path, time / Duration()) * 0.1f, endLookAt * 0.1f, vec3(0, 1, 0));

	setDepthMode(DEPTH_FULL);
	for (int i = 0; i < ARRAY_SIZE(tPark); i++) {
		GlslShader *sDraw = sPark[i];
		sDraw->bind();
		sDraw->uniform("u_matrix", mPersp * mCamera);
		sDraw->uniform("u_modelview", mCamera);
		sDraw->uniform("u_projection", mPersp);
		sDraw->uniform("u_alpha", 1.0f);
		sDraw->bindTexture("tex", tPark[i], 0);
		oPark->draw(i);
		sDraw->unbind();
	}

	sDrawFlat->bind();
	sDrawFlat->bindTexture("tex", tSmoke, 0);
	setBlendMode(BLEND_ALPHA);
	sDrawFlat->uniform("u_alpha", smokeAlpha);
	mat4 sm(1);
	sm = translate(sm, smokeCenter * 0.1f);
	sm = rotate(sm, smokeRot, vec3(0, 1, 0));
	sm = scale(sm, vec3(smokeSize, 1));
	sDrawFlat->uniform("u_matrix", mPersp * mCamera * sm);

	int animStep = int(floor(time * 24.0f));
	int animX = animStep & 7;
	int animY = (animStep >> 3) & 3;
	float l = float(animX) / 8, r = float(animX + 1) / 8;
	float b = float(animY) / 4, t = float(animY + 1) / 4;

	drawRect(vec2(-0.5, -0.5), vec2(0.5, 0.5), vec2(l, t), vec2(r, b));
	sDrawFlat->unbind();

	setDepthMode(NO_DEPTH);

	float logoFade = clamp((time - logoFadeStart) / (logoFadeEnd - logoFadeStart), 0.f, 1.f);

	setBlendMode(BLEND_ALPHA);
	sDrawFlat->bind();
	sDrawFlat->bindTexture("tex", tLogo, 0);
	sDrawFlat->uniform("u_alpha", logoFade);
	mat4 lm(demo.fix_aspect(mat4(1)));
	lm = translate(lm, logoCenter + vec3(sin(time) * 2, cos(2 * time), 0) * .01f);
	lm = scale(lm, vec3(tLogo->aspect, 1, 1) * logoSize);
	sDrawFlat->uniform("u_matrix", lm);
	drawUnitQuad();
	lm = demo.fix_aspect(mat4(1));
	lm = translate(lm, textCenter + vec3(cos(time + .6135), sin(-2 * time - .6135), 0) * .003f);
	lm = scale(lm, vec3(tText->aspect, 1, 1) * textSize);
	sDrawFlat->uniform("u_matrix", lm);
	sDrawFlat->bindTexture("tex", tText, 0);
	drawUnitQuad();
	sDrawFlat->unbind();
	setBlendMode(NO_BLEND);
}