<commit_before>/*************************************************************************
 *
 *  $RCSfile: resourceprovider.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: tra $ $Date: 2001-06-26 18:36:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include "filedlghelper.hrc"

//------------------------------------------------------------
//
//------------------------------------------------------------

#define RES_NAME sfx

// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_CB_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_CB_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_CB_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_CB_READONLY },
    { CHECKBOX_LINK,                            STR_CB_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_CB_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_PB_PLAY },
    { LISTBOX_VERSION + LB_LABEL_OFFSET,        STR_LB_VERSION },
    { LISTBOX_TEMPLATE + LB_LABEL_OFFSET,       STR_LB_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_LB_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_CB_SELECTION },
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

//------------------------------------------------------------
//
//------------------------------------------------------------

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

//------------------------------------------------------------
//
//------------------------------------------------------------

class CResourceProvider_Impl
{
public:

    //-------------------------------------
    //
    //-------------------------------------

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

    //-------------------------------------
    //
    //-------------------------------------

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

    //-------------------------------------
    //
    //-------------------------------------

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );

                // filter ~
                #pragma message( "#########################" )
                #pragma message( "implement filter ~" )
                #pragma message( "#########################" )
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

//------------------------------------------------------------
//
//------------------------------------------------------------

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

//------------------------------------------------------------
//
//------------------------------------------------------------

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

//------------------------------------------------------------
//
//------------------------------------------------------------

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}<commit_msg>#86986#removing tilde signes from control labels<commit_after>/*************************************************************************
 *
 *  $RCSfile: resourceprovider.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: tra $ $Date: 2001-06-27 07:16:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include "filedlghelper.hrc"

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

//------------------------------------------------------------
//
//------------------------------------------------------------

#define RES_NAME sfx

// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100

const rtl::OUString TILDE = OUString::createFromAscii( "~" );
const sal_Unicode TILDE_SIGN = L'~';

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_CB_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_CB_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_CB_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_CB_READONLY },
    { CHECKBOX_LINK,                            STR_CB_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_CB_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_PB_PLAY },
    { LISTBOX_VERSION + LB_LABEL_OFFSET,        STR_LB_VERSION },
    { LISTBOX_TEMPLATE + LB_LABEL_OFFSET,       STR_LB_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_LB_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_CB_SELECTION },
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

//------------------------------------------------------------
//
//------------------------------------------------------------

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

//------------------------------------------------------------
//
//------------------------------------------------------------

class CResourceProvider_Impl
{
public:

    //-------------------------------------
    //
    //-------------------------------------

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

    //-------------------------------------
    //
    //-------------------------------------

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

    //-------------------------------------
    //
    //-------------------------------------

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );

                // remove '~' signs, if there are two '~' signs
                // in a row we remove only one of them
                if ( aResOUString.indexOf( TILDE ) > -1 )
                {
                    sal_Int32 nStrLen = aResOUString.getLength( );
                    rtl::OUStringBuffer aBuffer( nStrLen );
                    sal_Int32 i = 0;
                    const sal_Unicode* pPos  = aResOUString.getStr( );
                    const sal_Unicode* pNext = aResOUString.getStr( ) + 1;
                    const sal_Unicode* pEnd  = aResOUString.getStr( ) + nStrLen;

                    while( pPos < pEnd )
                    {
                        // we insert the next character only if the current character
                        // in not a '~' or the following character is also a '~'
                        if ( (*pPos != TILDE_SIGN) ||
                             ((*pPos == TILDE_SIGN) && (pNext < pEnd) && (*pNext == TILDE_SIGN)) )
                        {
                            aBuffer.insert( i, *pPos );
                            i++;
                        }

                        pPos++;
                        pNext++;
                    }

                    aResOUString = aBuffer.makeStringAndClear( );
                }
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

//------------------------------------------------------------
//
//------------------------------------------------------------

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

//------------------------------------------------------------
//
//------------------------------------------------------------

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

//------------------------------------------------------------
//
//------------------------------------------------------------

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}<|endoftext|>


<commit_before>#include "DynamicPacker.h"
#include "ShaderMgr.h"

#include "common/Exception.h"
#include "common/Vector.h"
#include "common/config.h"
#include "common/SettingData.h"
#include "dataset/TPNode.h"
#include "render/PrimitiveDraw.h"
#include "render/style_config.h"

#include <gl/glew.h>
#include <wx/wx.h>

// debug
#include <dtex.h>

namespace d2d
{

DynamicPacker::DynamicPacker(int width, int height, int padding, int extrude)
	: m_width(width)
	, m_height(height)
	, m_padding(padding)
	, m_extrude(extrude)
{
	//initOpenGLExtensions();

	InitTexture();
	InitFBO();
	InitRoot();
}

DynamicPacker::~DynamicPacker()
{
	glDeleteTextures(1, &m_tex);
	glDeleteFramebuffersEXT(1, &m_fbo);

	delete m_root;
}

void DynamicPacker::ReloadTexture()
{
	wxLogDebug(_T("DynamicPacker ReloadTexture"));

	InitTexture(m_tex);
	InitFBO(m_fbo);
	ReloadPixels();
}

void DynamicPacker::DebugDrawStatic() const
{
	ShaderMgr* shader = ShaderMgr::Instance();
	shader->SetFBO(0);
	shader->sprite();
	shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));

	float vb[16];

	vb[0] = 0, vb[1] = 0;
	vb[2] = 0, vb[3] = 0;

	vb[4] = 0, vb[5] = 1;
	vb[6] = 0, vb[7] = 1;

	vb[8] = 1, vb[9] = 1;
	vb[10] = 1, vb[11] = 1;

	vb[12] = 1, vb[13] = 0;
	vb[14] = 1, vb[15] = 0;

	ShaderMgr::Instance()->Draw(vb, m_tex);
}

void DynamicPacker::DebugDraw() const
{
	const int EDGE = 1024;

	Vector vertices[4];
	vertices[0].set(0, 0);
	vertices[1].set(0, EDGE);
	vertices[2].set(EDGE, EDGE);
	vertices[3].set(EDGE, 0);

	ShaderMgr* shader = ShaderMgr::Instance();
	shader->sprite();
	shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));
	shader->SetSpriteColorTrans(Colorf(1, 0, 0, 0), Colorf(0, 1, 0, 0), Colorf(0, 0, 1, 0));

	float vb[16];

	vb[0] = vertices[0].x, vb[1] = vertices[0].y;
	vb[2] = 0, vb[3] = 0;

	vb[4] = vertices[1].x, vb[5] = vertices[1].y;
	vb[6] = 0, vb[7] = 1;

	vb[8] = vertices[2].x, vb[9] = vertices[2].y;
	vb[10] = 1, vb[11] = 1;

	vb[12] = vertices[3].x, vb[13] = vertices[3].y;
	vb[14] = 1, vb[15] = 0;

	if (dtex_cg* cg = dtexf_get_cg()) {
		int id = dtex_cg_get_texid(cg);
//		int id = m_tex;
		shader->Draw(vb, id);
	}

	PrimitiveDraw::rect(Vector(0, 0), Vector(EDGE, EDGE), LIGHT_RED_THIN_LINE);
}

void DynamicPacker::InitTexture(int tex_id)
{
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

	if (tex_id == 0) {
		glGenTextures(1, (GLuint*)&tex_id);
	}
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, tex_id);

	if (Config::Instance()->GetSettings().linear_filter) {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	} else {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
	}
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)m_width, (GLsizei)m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// 	uint8_t* empty_data = new uint8_t[m_width*m_height*4];
// 	memset(empty_data, 0, m_width*m_height*4);
// 	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)m_width, (GLsizei)m_height, GL_RGBA, GL_UNSIGNED_BYTE, &empty_data[0]);
// 	delete[] empty_data;

	m_tex = tex_id;

//	ClearTexture();
}

void DynamicPacker::InitFBO(int fbo_id)
{
	ShaderMgr* shader = ShaderMgr::Instance();

	if (fbo_id == 0) {
		glGenFramebuffersEXT(1, (GLuint*)&fbo_id);
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_tex, 0);

	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
		throw Exception("Create FBO error: %d", status);
	}

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShaderMgr::Instance()->GetFboID());

	m_fbo = fbo_id;
}

void DynamicPacker::InitRoot()
{
	m_root = new TPNode(m_width, m_height);
	TPNode* c = new TPNode(m_width, m_height);
	m_root->SetChild(c);
}

void DynamicPacker::ClearTexture()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
	glBindTexture(GL_TEXTURE_2D, m_tex);
	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	ShaderMgr* shader = ShaderMgr::Instance();
	glBindTexture(GL_TEXTURE_2D, shader->GetTexID());
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, shader->GetFboID());
}

}<commit_msg>debug draw<commit_after>#include "DynamicPacker.h"
#include "ShaderMgr.h"

#include "common/Exception.h"
#include "common/Vector.h"
#include "common/config.h"
#include "common/SettingData.h"
#include "dataset/TPNode.h"
#include "render/PrimitiveDraw.h"
#include "render/style_config.h"

#include <gl/glew.h>
#include <wx/wx.h>

// debug
#include <dtex.h>

namespace d2d
{

DynamicPacker::DynamicPacker(int width, int height, int padding, int extrude)
	: m_width(width)
	, m_height(height)
	, m_padding(padding)
	, m_extrude(extrude)
{
	//initOpenGLExtensions();

	InitTexture();
	InitFBO();
	InitRoot();
}

DynamicPacker::~DynamicPacker()
{
	glDeleteTextures(1, &m_tex);
	glDeleteFramebuffersEXT(1, &m_fbo);

	delete m_root;
}

void DynamicPacker::ReloadTexture()
{
	wxLogDebug(_T("DynamicPacker ReloadTexture"));

	InitTexture(m_tex);
	InitFBO(m_fbo);
	ReloadPixels();
}

void DynamicPacker::DebugDrawStatic() const
{
	ShaderMgr* shader = ShaderMgr::Instance();
	shader->SetFBO(0);
	shader->sprite();
	shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));

	float vb[16];

	vb[0] = 0, vb[1] = 0;
	vb[2] = 0, vb[3] = 0;

	vb[4] = 0, vb[5] = 1;
	vb[6] = 0, vb[7] = 1;

	vb[8] = 1, vb[9] = 1;
	vb[10] = 1, vb[11] = 1;

	vb[12] = 1, vb[13] = 0;
	vb[14] = 1, vb[15] = 0;

	ShaderMgr::Instance()->Draw(vb, m_tex);
}

void DynamicPacker::DebugDraw() const
{
	const int EDGE = 1024;

	Vector vertices[4];
	vertices[0].set(0, 0);
	vertices[1].set(0, EDGE);
	vertices[2].set(EDGE, EDGE);
	vertices[3].set(EDGE, 0);

	ShaderMgr* shader = ShaderMgr::Instance();
	shader->sprite();
	shader->SetSpriteColor(Colorf(1, 1, 1, 1), Colorf(0, 0, 0, 0));
	shader->SetSpriteColorTrans(Colorf(1, 0, 0, 0), Colorf(0, 1, 0, 0), Colorf(0, 0, 1, 0));

	float vb[16];

	vb[0] = vertices[0].x, vb[1] = vertices[0].y;
	vb[2] = 0, vb[3] = 0;

	vb[4] = vertices[1].x, vb[5] = vertices[1].y;
	vb[6] = 0, vb[7] = 1;

	vb[8] = vertices[2].x, vb[9] = vertices[2].y;
	vb[10] = 1, vb[11] = 1;

	vb[12] = vertices[3].x, vb[13] = vertices[3].y;
	vb[14] = 1, vb[15] = 0;

	if (dtex_cg* cg = dtexf_get_cg()) {
		int id = dtex_cg_get_texid(cg);
		shader->Draw(vb, id);
	}

// 	int id = m_tex;
// 	shader->Draw(vb, id);

	PrimitiveDraw::rect(Vector(0, 0), Vector(EDGE, EDGE), LIGHT_RED_THIN_LINE);
}

void DynamicPacker::InitTexture(int tex_id)
{
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

	if (tex_id == 0) {
		glGenTextures(1, (GLuint*)&tex_id);
	}
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, tex_id);

	if (Config::Instance()->GetSettings().linear_filter) {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	} else {
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
		glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
	}
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)m_width, (GLsizei)m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// 	uint8_t* empty_data = new uint8_t[m_width*m_height*4];
// 	memset(empty_data, 0, m_width*m_height*4);
// 	glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)m_width, (GLsizei)m_height, GL_RGBA, GL_UNSIGNED_BYTE, &empty_data[0]);
// 	delete[] empty_data;

	m_tex = tex_id;

//	ClearTexture();
}

void DynamicPacker::InitFBO(int fbo_id)
{
	ShaderMgr* shader = ShaderMgr::Instance();

	if (fbo_id == 0) {
		glGenFramebuffersEXT(1, (GLuint*)&fbo_id);
	}
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id);

	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_tex, 0);

	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
		throw Exception("Create FBO error: %d", status);
	}

	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ShaderMgr::Instance()->GetFboID());

	m_fbo = fbo_id;
}

void DynamicPacker::InitRoot()
{
	m_root = new TPNode(m_width, m_height);
	TPNode* c = new TPNode(m_width, m_height);
	m_root->SetChild(c);
}

void DynamicPacker::ClearTexture()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo);
	glBindTexture(GL_TEXTURE_2D, m_tex);
	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	ShaderMgr* shader = ShaderMgr::Instance();
	glBindTexture(GL_TEXTURE_2D, shader->GetTexID());
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, shader->GetFboID());
}

}<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/python/grappler/model_analyzer.h"

#include <iomanip>
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/grappler_item.h"

namespace tensorflow {
namespace grappler {

ModelAnalyzer::ModelAnalyzer(const GrapplerItem& item) : item_(item) {}

Status ModelAnalyzer::GenerateReport(std::ostream& os) {
  GraphProperties properties(item_);
  TF_RETURN_IF_ERROR(properties.InferStatically());

  for (const auto& node : item_.MainOpsFanin()) {
    PrintNodeInfo(node, properties, os);
  }
  for (const auto& node : item_.EnqueueOpsFanin()) {
    PrintNodeInfo(node, properties, os);
  }

  return Status::OK();
}

void ModelAnalyzer::PrintNodeInfo(const NodeDef* node,
                                  const GraphProperties& properties,
                                  std::ostream& os) const {
  os << node->name() << " [" << node->op() << "]" << std::endl;
  if (properties.HasOutputProperties(node->name())) {
    std::vector<OpInfo::TensorProperties> props =
        properties.GetOutputProperties(node->name());
    for (int i = 0; i < props.size(); ++i) {
      const OpInfo::TensorProperties& prop = props[i];
      os << "\t"
         << "output " << i << " (" << DataTypeString(prop.dtype())
         << ") has shape ";
      if (prop.shape().unknown_rank()) {
        os << "?";
      } else {
        os << "[";
        for (int i = 0; i < prop.shape().dim_size(); ++i) {
          if (i > 0) {
            os << ", ";
          }
          if (prop.shape().dim(i).size() < 0) {
            os << "?";
          } else {
            os << prop.shape().dim(i).size();
          }
        }
        os << "]";
      }
      os << std::endl;
    }
  }
}

}  // end namespace grappler
}  // end namespace tensorflow
<commit_msg>Improved the reporting of dimensions<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/python/grappler/model_analyzer.h"

#include <iomanip>
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/grappler_item.h"

namespace tensorflow {
namespace grappler {

ModelAnalyzer::ModelAnalyzer(const GrapplerItem& item) : item_(item) {}

Status ModelAnalyzer::GenerateReport(std::ostream& os) {
  GraphProperties properties(item_);
  TF_RETURN_IF_ERROR(properties.InferStatically());

  for (const auto& node : item_.MainOpsFanin()) {
    PrintNodeInfo(node, properties, os);
  }
  for (const auto& node : item_.EnqueueOpsFanin()) {
    PrintNodeInfo(node, properties, os);
  }

  return Status::OK();
}

void ModelAnalyzer::PrintNodeInfo(const NodeDef* node,
                                  const GraphProperties& properties,
                                  std::ostream& os) const {
  os << node->name() << " [" << node->op() << "]" << std::endl;
  if (properties.HasOutputProperties(node->name())) {
    std::vector<OpInfo::TensorProperties> props =
        properties.GetOutputProperties(node->name());
    for (int i = 0; i < props.size(); ++i) {
      const OpInfo::TensorProperties& prop = props[i];
      os << "\t"
         << "output " << i << " (" << DataTypeString(prop.dtype())
         << ") has shape ";
      if (prop.shape().unknown_rank()) {
        os << "?";
      } else {
        os << "[";
        for (int i = 0; i < prop.shape().dim_size(); ++i) {
          if (i > 0) {
            os << ", ";
          }
          if (prop.shape().dim(i).size() >= 0) {
            // Print the actual dimension.
            os << prop.shape().dim(i).size();
          } else if (prop.shape().dim(i).size() == -1) {
            // We don't know anything about the dimension.
            os << "?";
          } else {
            // Symbolic dimension.
            os << "x" << -prop.shape().dim(i).size();
          }
        }
        os << "]";
      }
      os << std::endl;
    }
  }
}

}  // end namespace grappler
}  // end namespace tensorflow
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2014 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014)

#ifndef DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
#define DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH

#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/dd/subdomains/grid.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>

namespace Dune {
namespace GDT {

template <class LocalSpaceImp>
class BlockMapper;

namespace internal {

template <class LocalSpaceType>
class BlockMapperTraits
{
  static_assert(is_space<LocalSpaceType>::value, "LocalSpaceType has to be derived from SpaceInterface!");

public:
  typedef BlockMapper<LocalSpaceType> derived_type;
  typedef typename LocalSpaceType::EntityType EntityType;
  typedef std::vector<std::shared_ptr<const LocalSpaceType>> BackendType;
}; // class BlockMapperTraits

} // namespace internal

template <class LocalSpaceImp>
class BlockMapper : public MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>>
{
  typedef MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>> BaseType;
  typedef BlockMapper<LocalSpaceImp> ThisType;

public:
  typedef internal::BlockMapperTraits<LocalSpaceImp> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::EntityType EntityType;
  typedef LocalSpaceImp LocalSpaceType;

  typedef XT::Grid::DD::SubdomainGrid<XT::Grid::extract_grid_t<typename LocalSpaceType::GridLayerType>>
      DdSubdomainsGridType;

private:
  typedef typename DdSubdomainsGridType::GlobalGridPartType GridLayerType;
  typedef typename DdSubdomainsGridType::EntityToSubdomainMapType EntityToSubdomainMapType;

  template <class L, class E>
  class Compute
  {
    static_assert(AlwaysFalse<L>::value, "Not implemented for this kind of entity (only codim 0)!");
  };

  template <class L>
  class Compute<L, typename DdSubdomainsGridType::EntityType>
  {
    typedef typename DdSubdomainsGridType::EntityType Comdim0EntityType;

  public:
    static size_t numDofs(const ThisType& self, const Comdim0EntityType& entity)
    {
      const size_t block = find_block_of(self, entity);
      if (self.backend()[block] == nullptr)
        DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
      return self.backend()[block]->mapper().numDofs(entity);
    }

    static void globalIndices(const ThisType& self, const Comdim0EntityType& entity, Dune::DynamicVector<size_t>& ret)
    {
      const size_t block = find_block_of(self, entity);
      if (self.backend()[block] == nullptr)
        DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
      self.backend()[block]->mapper().globalIndices(entity, ret);
      const size_t num_dofs = self.backend()[block]->mapper().numDofs(entity);
      assert(ret.size() >= num_dofs);
      for (size_t ii = 0; ii < num_dofs; ++ii)
        ret[ii] += self.global_start_indices_[block];
    }

    static size_t mapToGlobal(const ThisType& self, const Comdim0EntityType& entity, const size_t& localIndex)
    {
      const size_t block = find_block_of(self, entity);
      if (self.backend()[block] == nullptr)
        DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
      const size_t block_local_index = self.backend()[block]->mapper().mapToGlobal(entity, localIndex);
      return self.global_start_indices_[block] + block_local_index;
    }

  private:
    static size_t find_block_of(const ThisType& self, const Comdim0EntityType& entity)
    {
      const auto global_entity_index = self.global_grid_part_->indexSet().index(entity);
      const auto result = self.entity_to_subdomain_map_->find(global_entity_index);
#ifndef NDEBUG
      if (result == self.entity_to_subdomain_map_->end())
        DUNE_THROW(XT::Common::Exceptions::internal_error,
                   "Entity " << global_entity_index
                             << " of the global grid part was not found in the dd subdomain grid!");
#endif // NDEBUG
      const size_t subdomain = result->second;
#ifndef NDEBUG
      if (subdomain >= self.num_blocks_)
        DUNE_THROW(XT::Common::Exceptions::internal_error,
                   "The DD subdomains grid is corrupted!\nIt reports Entity " << global_entity_index
                                                                              << " to be in subdomain "
                                                                              << subdomain
                                                                              << " while only having "
                                                                              << self.num_blocks_
                                                                              << " subdomains!");
#endif // NDEBUG
      return subdomain;
    } // ... find_block_of(...)
  }; // class Compute< ..., EntityType >

public:
  BlockMapper(const DdSubdomainsGridType& dd_grid,
              const std::shared_ptr<GridLayerType> grid_layer,
              const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces)
    : global_grid_part_(grid_layer)
    , entity_to_subdomain_map_(dd_grid.entityToSubdomainMap())
    , local_spaces_(local_spaces)
    , num_blocks_(local_spaces_->size())
    , size_(0)
    , max_num_dofs_(0)
  {
    if (local_spaces_->size() != dd_grid.size())
      DUNE_THROW(XT::Common::Exceptions::shapes_do_not_match,
                 "You have to provide a local space for each subdomain of the DD subdomains grid!\n"
                     << "  Number of subdomains: "
                     << dd_grid.size()
                     << "\n"
                     << "  Number of local spaces given: "
                     << local_spaces_->size());
    for (size_t bb = 0; bb < num_blocks_; ++bb) {
      if (backend()[bb] != nullptr) {
        max_num_dofs_ = std::max(max_num_dofs_, backend()[bb]->mapper().maxNumDofs());
        global_start_indices_.push_back(size_);
        size_ += backend()[bb]->mapper().size();
      } else {
        global_start_indices_.push_back(size_);
      }
    }
  } // BlockMapper(...)

  BlockMapper(const ThisType& other) = default;
  BlockMapper(ThisType&& source) = default;

  ThisType& operator=(const ThisType& other) = delete;
  ThisType& operator=(ThisType&& source) = delete;

  size_t numBlocks() const
  {
    return num_blocks_;
  }

  size_t localSize(const size_t block) const
  {
    assert(block < num_blocks_);
    return backend()[block]->mapper().size();
  }

  size_t mapToGlobal(const size_t block, const size_t localIndex) const
  {
    assert(block < num_blocks_);
    return global_start_indices_[block] + localIndex;
  }

  const BackendType& backend() const
  {
    return *local_spaces_;
  }

  size_t size() const
  {
    return size_;
  }

  size_t maxNumDofs() const
  {
    return max_num_dofs_;
  }

  size_t numDofs(const EntityType& entity) const
  {
    return Compute<LocalSpaceType, EntityType>::numDofs(*this, entity);
  }

  void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
  {
    Compute<LocalSpaceType, EntityType>::globalIndices(*this, entity, ret);
  }

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    return Compute<LocalSpaceType, EntityType>::mapToGlobal(*this, entity, localIndex);
  }

private:
  template <class L, class E>
  friend class Compute;

  const std::shared_ptr<GridLayerType> global_grid_part_;
  const std::shared_ptr<const typename DdSubdomainsGridType::EntityToSubdomainMapType> entity_to_subdomain_map_;
  const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces_;
  size_t num_blocks_;
  size_t size_;
  size_t max_num_dofs_;
  std::vector<size_t> global_start_indices_;
}; // class BlockMapper

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
<commit_msg>[spaces.mapper.block] do not hide convenience method from base<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2014 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014)

#ifndef DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
#define DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH

#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/dd/subdomains/grid.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>

namespace Dune {
namespace GDT {

template <class LocalSpaceImp>
class BlockMapper;

namespace internal {

template <class LocalSpaceType>
class BlockMapperTraits
{
  static_assert(is_space<LocalSpaceType>::value, "LocalSpaceType has to be derived from SpaceInterface!");

public:
  typedef BlockMapper<LocalSpaceType> derived_type;
  typedef typename LocalSpaceType::EntityType EntityType;
  typedef std::vector<std::shared_ptr<const LocalSpaceType>> BackendType;
}; // class BlockMapperTraits

} // namespace internal

template <class LocalSpaceImp>
class BlockMapper : public MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>>
{
  typedef MapperInterface<internal::BlockMapperTraits<LocalSpaceImp>> BaseType;
  typedef BlockMapper<LocalSpaceImp> ThisType;

public:
  typedef internal::BlockMapperTraits<LocalSpaceImp> Traits;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::EntityType EntityType;
  typedef LocalSpaceImp LocalSpaceType;

  typedef XT::Grid::DD::SubdomainGrid<XT::Grid::extract_grid_t<typename LocalSpaceType::GridLayerType>>
      DdSubdomainsGridType;

private:
  typedef typename DdSubdomainsGridType::GlobalGridPartType GridLayerType;
  typedef typename DdSubdomainsGridType::EntityToSubdomainMapType EntityToSubdomainMapType;

  template <class L, class E>
  class Compute
  {
    static_assert(AlwaysFalse<L>::value, "Not implemented for this kind of entity (only codim 0)!");
  };

  template <class L>
  class Compute<L, typename DdSubdomainsGridType::EntityType>
  {
    typedef typename DdSubdomainsGridType::EntityType Comdim0EntityType;

  public:
    static size_t numDofs(const ThisType& self, const Comdim0EntityType& entity)
    {
      const size_t block = find_block_of(self, entity);
      if (self.backend()[block] == nullptr)
        DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
      return self.backend()[block]->mapper().numDofs(entity);
    }

    static void globalIndices(const ThisType& self, const Comdim0EntityType& entity, Dune::DynamicVector<size_t>& ret)
    {
      const size_t block = find_block_of(self, entity);
      if (self.backend()[block] == nullptr)
        DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
      self.backend()[block]->mapper().globalIndices(entity, ret);
      const size_t num_dofs = self.backend()[block]->mapper().numDofs(entity);
      assert(ret.size() >= num_dofs);
      for (size_t ii = 0; ii < num_dofs; ++ii)
        ret[ii] += self.global_start_indices_[block];
    }

    static size_t mapToGlobal(const ThisType& self, const Comdim0EntityType& entity, const size_t& localIndex)
    {
      const size_t block = find_block_of(self, entity);
      if (self.backend()[block] == nullptr)
        DUNE_THROW(InvalidStateException, "You did not provide a local space for block " << block << "!");
      const size_t block_local_index = self.backend()[block]->mapper().mapToGlobal(entity, localIndex);
      return self.global_start_indices_[block] + block_local_index;
    }

  private:
    static size_t find_block_of(const ThisType& self, const Comdim0EntityType& entity)
    {
      const auto global_entity_index = self.global_grid_part_->indexSet().index(entity);
      const auto result = self.entity_to_subdomain_map_->find(global_entity_index);
#ifndef NDEBUG
      if (result == self.entity_to_subdomain_map_->end())
        DUNE_THROW(XT::Common::Exceptions::internal_error,
                   "Entity " << global_entity_index
                             << " of the global grid part was not found in the dd subdomain grid!");
#endif // NDEBUG
      const size_t subdomain = result->second;
#ifndef NDEBUG
      if (subdomain >= self.num_blocks_)
        DUNE_THROW(XT::Common::Exceptions::internal_error,
                   "The DD subdomains grid is corrupted!\nIt reports Entity " << global_entity_index
                                                                              << " to be in subdomain "
                                                                              << subdomain
                                                                              << " while only having "
                                                                              << self.num_blocks_
                                                                              << " subdomains!");
#endif // NDEBUG
      return subdomain;
    } // ... find_block_of(...)
  }; // class Compute< ..., EntityType >

public:
  BlockMapper(const DdSubdomainsGridType& dd_grid,
              const std::shared_ptr<GridLayerType> grid_layer,
              const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces)
    : global_grid_part_(grid_layer)
    , entity_to_subdomain_map_(dd_grid.entityToSubdomainMap())
    , local_spaces_(local_spaces)
    , num_blocks_(local_spaces_->size())
    , size_(0)
    , max_num_dofs_(0)
  {
    if (local_spaces_->size() != dd_grid.size())
      DUNE_THROW(XT::Common::Exceptions::shapes_do_not_match,
                 "You have to provide a local space for each subdomain of the DD subdomains grid!\n"
                     << "  Number of subdomains: "
                     << dd_grid.size()
                     << "\n"
                     << "  Number of local spaces given: "
                     << local_spaces_->size());
    for (size_t bb = 0; bb < num_blocks_; ++bb) {
      if (backend()[bb] != nullptr) {
        max_num_dofs_ = std::max(max_num_dofs_, backend()[bb]->mapper().maxNumDofs());
        global_start_indices_.push_back(size_);
        size_ += backend()[bb]->mapper().size();
      } else {
        global_start_indices_.push_back(size_);
      }
    }
  } // BlockMapper(...)

  BlockMapper(const ThisType& other) = default;
  BlockMapper(ThisType&& source) = default;

  ThisType& operator=(const ThisType& other) = delete;
  ThisType& operator=(ThisType&& source) = delete;

  size_t numBlocks() const
  {
    return num_blocks_;
  }

  size_t localSize(const size_t block) const
  {
    assert(block < num_blocks_);
    return backend()[block]->mapper().size();
  }

  size_t mapToGlobal(const size_t block, const size_t localIndex) const
  {
    assert(block < num_blocks_);
    return global_start_indices_[block] + localIndex;
  }

  const BackendType& backend() const
  {
    return *local_spaces_;
  }

  size_t size() const
  {
    return size_;
  }

  size_t maxNumDofs() const
  {
    return max_num_dofs_;
  }

  size_t numDofs(const EntityType& entity) const
  {
    return Compute<LocalSpaceType, EntityType>::numDofs(*this, entity);
  }

  using BaseType::globalIndices;

  void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const
  {
    Compute<LocalSpaceType, EntityType>::globalIndices(*this, entity, ret);
  }

  size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const
  {
    return Compute<LocalSpaceType, EntityType>::mapToGlobal(*this, entity, localIndex);
  }

private:
  template <class L, class E>
  friend class Compute;

  const std::shared_ptr<GridLayerType> global_grid_part_;
  const std::shared_ptr<const typename DdSubdomainsGridType::EntityToSubdomainMapType> entity_to_subdomain_map_;
  const std::shared_ptr<std::vector<std::shared_ptr<const LocalSpaceType>>> local_spaces_;
  size_t num_blocks_;
  size_t size_;
  size_t max_num_dofs_;
  std::vector<size_t> global_start_indices_;
}; // class BlockMapper

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_SPACES_MAPPER_BLOCK_HH
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH

#include <type_traits>

#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/common/disable_warnings.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/geometry/genericreferenceelements.hh>
#endif
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/common/exceptions.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

// forward, to allow for specialization
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class ContinuousLagrangeBase
{
  static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!");
};

template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim>
class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits>
{
  typedef SpaceInterface<ImpTraits> BaseType;
  typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType;

  static constexpr RangeFieldImp compare_tolerance_ = 1e-13;

public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  typedef typename Traits::RangeFieldType RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::EntityType;
  using typename BaseType::IntersectionType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::PatternType;

  virtual ~ContinuousLagrangeBase()
  {
  }

  using BaseType::compute_pattern;

  template <class G, class S>
  PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
  }

  virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    // get the basis and reference element
    const auto basis              = this->base_function_set(entity);
    const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
    const int num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    // loop over all vertices
    for (int ii = 0; ii < num_vertices; ++ii) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, this->tmp_basis_values_);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points(...)

  virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_view()->indexSet().contains(entity));
    // prepare
    std::set<size_t> localDirichletDofs;
    std::vector<DomainType> dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_view()->iend(entity);
    for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end;
         ++intersection_it) {
      // only work on dirichlet ones
      const auto& intersection = *intersection_it;
      // actual dirichlet intersections + process boundaries for parallel runs
      if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (int cc = 0; cc < geometry.corners(); ++cc)
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
      } // only work on dirichlet ones
    } // loop over all intersections
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs(...)

private:
  template <class T, bool set_row>
  void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity,
                                 Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = this->mapper().numDofs(entity);
      ret.set_size(numRows, numCols);
      this->mapper().globalIndices(entity, tmpMappedRows_);
      other.mapper().globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      for (const size_t& localDirichletDofIndex : localDirichletDofs) {
        ret.global_row(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.global_col(jj) = tmpMappedCols_[jj];
          if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
            ret.value(localRow, jj) = set_row ? RangeFieldType(1) : RangeFieldType(0);
          else
            ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.set_size(0, 0);
    }
  } // ... compute_local_constraints(..., Dirichlet< ..., true >)

public:
  using BaseType::local_constraints;

  template <bool set>
  void local_constraints(const EntityType& entity,
                         Constraints::Dirichlet<IntersectionType, RangeFieldType, set>& ret) const
  {
    local_constraints(*this, entity, ret);
  }

  virtual void local_constraints(const ThisType& other, const EntityType& entity,
                                 Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

  virtual void local_constraints(const ThisType& other, const EntityType& entity,
                                 Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

protected:
  mutable Dune::DynamicVector<size_t> tmpMappedRows_;
  mutable Dune::DynamicVector<size_t> tmpMappedCols_;
}; // class ContinuousLagrangeBase

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<commit_msg>[spaces.cg.bsae] updated constraints<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH

#include <type_traits>

#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/common/disable_warnings.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE
#include <dune/geometry/referenceelements.hh>
#else
#include <dune/geometry/genericreferenceelements.hh>
#endif
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/reenable_warnings.hh>

#include <dune/stuff/common/exceptions.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

// forward, to allow for specialization
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class ContinuousLagrangeBase
{
  static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!");
};

template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim>
class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits>
{
  typedef SpaceInterface<ImpTraits> BaseType;
  typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType;

  static constexpr RangeFieldImp compare_tolerance_ = 1e-13;

public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  typedef typename Traits::RangeFieldType RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::EntityType;
  using typename BaseType::IntersectionType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::PatternType;

  virtual ~ContinuousLagrangeBase()
  {
  }

  using BaseType::compute_pattern;

  template <class G, class S>
  PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
  }

  virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    // get the basis and reference element
    const auto basis              = this->base_function_set(entity);
    const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
    const int num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    // loop over all vertices
    for (int ii = 0; ii < num_vertices; ++ii) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, this->tmp_basis_values_);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points(...)

  virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_view()->indexSet().contains(entity));
    // prepare
    std::set<size_t> localDirichletDofs;
    std::vector<DomainType> dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_view()->iend(entity);
    for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end;
         ++intersection_it) {
      // only work on dirichlet ones
      const auto& intersection = *intersection_it;
      // actual dirichlet intersections + process boundaries for parallel runs
      if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (int cc = 0; cc < geometry.corners(); ++cc)
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
      } // only work on dirichlet ones
    } // loop over all intersections
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
      size_t ones     = 0;
      size_t zeros    = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs(...)

private:
  template <class T, bool set_row>
  void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity,
                                 Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = this->mapper().numDofs(entity);
      ret.set_size(numRows, numCols);
      this->mapper().globalIndices(entity, tmpMappedRows_);
      other.mapper().globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      for (const size_t& localDirichletDofIndex : localDirichletDofs) {
        ret.global_row(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.global_col(jj) = tmpMappedCols_[jj];
          if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
            ret.value(localRow, jj) = set_row ? RangeFieldType(1) : RangeFieldType(0);
          else
            ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.set_size(0, 0);
    }
  } // ... compute_local_constraints(..., Dirichlet< ..., true >)

public:
  using BaseType::local_constraints;

  template <class C, class R>
  void local_constraints(const ThisType& /*other*/, const EntityType& /*entity*/,
                         ConstraintsInterface<C, R>& /*ret*/) const
  {
    static_assert(AlwaysFalse<C>::value, "Not implemented for arbitrary constraints!");
  }

  virtual void local_constraints(const ThisType& other, const EntityType& entity,
                                 Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

  virtual void local_constraints(const ThisType& other, const EntityType& entity,
                                 Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

protected:
  mutable Dune::DynamicVector<size_t> tmpMappedRows_;
  mutable Dune::DynamicVector<size_t> tmpMappedCols_;
}; // class ContinuousLagrangeBase

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<|endoftext|>


<commit_before>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "escher/shaders/material/material_shader.h"

#include "escher/shaders/glsl_generator.h"

namespace escher {
namespace {

constexpr char g_decls[] = R"GLSL(
  #define BINDING_NONE 0
  #define BINDING_CONSTANT 1
  #define MASK_NONE 0
  #define MASK_CIRCULAR 1
)GLSL";

constexpr char g_vertex_shader[] = R"GLSL(
  attribute vec3 a_position;
  uniform mat4 u_matrix;

#if MASK == MASK_CIRCULAR
  attribute vec2 a_mask_uv;
  varying vec2 v_mask_uv;
  void mask() {
    v_mask_uv = a_mask_uv;
  }
#else
  void mask() {}
#endif

  void main() {
    gl_Position = u_matrix * vec4(a_position, 1.0);
    mask();
  }
)GLSL";

constexpr char g_fragment_shader[] = R"GLSL(
  precision mediump float;

#if COLOR_BINDING == BINDING_NONE
  vec4 color() {
    return vec4(0.0, 0.0, 0.0, 1.0); // should alpha be 0?
  }
#elif COLOR_BINDING == BINDING_CONSTANT
  uniform vec4 u_color;
  vec4 color() {
    return u_color;
  }
#endif

#if MASK == MASK_CIRCULAR
  varying vec2 v_mask_uv;
  bool mask() {
    return v_mask_uv.x * v_mask_uv.x + v_mask_uv.y * v_mask_uv.y <= 1.0;
  }
#else
  bool mask() { return true; }
#endif

  void main() {
    if (!mask()) discard; // FIXME(jeffbrown): inefficient!
    gl_FragColor = color();
  }
)GLSL";

void DefineBindingSymbol(GLSLGenerator& generator,
                         const std::string& symbol,
                         BindingType binding_type) {
  switch (binding_type) {
    case BindingType::kNone:
      generator.DefineSymbol(symbol, "BINDING_NONE");
      break;
    case BindingType::kConstant:
      generator.DefineSymbol(symbol, "BINDING_CONSTANT");
      break;
  }
}

void DefineMaskSymbol(GLSLGenerator& generator, Modifier::Mask mask) {
  switch (mask) {
    case Modifier::Mask::kNone:
      generator.DefineSymbol("MASK", "MASK_NONE");
      break;
    case Modifier::Mask::kCircular:
      generator.DefineSymbol("MASK", "MASK_CIRCULAR");
      break;
  }
}

}  // namespace

MaterialShader::MaterialShader(const MaterialShaderDescriptor& descriptor)
    : descriptor_(descriptor) {}

MaterialShader::~MaterialShader() {}

void MaterialShader::Use(const glm::mat4& matrix) const {
  glUseProgram(program_.id());
  glEnableVertexAttribArray(position_);
  if (descriptor_.mask == Modifier::Mask::kCircular)
    glEnableVertexAttribArray(mask_uv_);
  glUniformMatrix4fv(matrix_, 1, GL_FALSE, &matrix[0][0]);
}

void MaterialShader::Bind(const Material& material,
                          const Modifier& modifier) const {
  if (descriptor_.color_binding_type == BindingType::kConstant) {
    const glm::vec4& color = material.color().constant_value();
    glUniform4fv(color_, 1, &color[0]);
  }
}

bool MaterialShader::Compile() {
  std::string prologue = GeneratePrologue();
  std::vector<std::string> vertex_shader_sources{g_decls, prologue,
                                                 g_vertex_shader};
  std::vector<std::string> fragment_shader_sources{g_decls, prologue,
                                                   g_fragment_shader};
  UniqueShader vertex_shader =
      MakeUniqueShader(GL_VERTEX_SHADER, vertex_shader_sources);
  UniqueShader fragment_shader =
      MakeUniqueShader(GL_FRAGMENT_SHADER, fragment_shader_sources);
  if (!vertex_shader || !fragment_shader)
    return false;

  program_ =
      MakeUniqueProgram(std::move(vertex_shader), std::move(fragment_shader));
  if (!program_)
    return false;

  matrix_ = glGetUniformLocation(program_.id(), "u_matrix");
  ESCHER_DCHECK(matrix_ != -1);

  if (descriptor_.color_binding_type == BindingType::kConstant) {
    color_ = glGetUniformLocation(program_.id(), "u_color");
    ESCHER_DCHECK(color_ != -1);
  }

  if (descriptor_.mask == Modifier::Mask::kCircular) {
    mask_uv_ = glGetAttribLocation(program_.id(), "a_mask_uv");
    ESCHER_DCHECK(mask_uv_ != -1);
  }
  return true;
}

std::string MaterialShader::GeneratePrologue() {
  GLSLGenerator generator;
  DefineBindingSymbol(generator, "COLOR_BINDING",
                      descriptor_.color_binding_type);
  DefineMaskSymbol(generator, descriptor_.mask);
  return generator.GenerateCode();
}

}  // namespace escher
<commit_msg>Use dot() operator (#19)<commit_after>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "escher/shaders/material/material_shader.h"

#include "escher/shaders/glsl_generator.h"

namespace escher {
namespace {

constexpr char g_decls[] = R"GLSL(
  #define BINDING_NONE 0
  #define BINDING_CONSTANT 1
  #define MASK_NONE 0
  #define MASK_CIRCULAR 1
)GLSL";

constexpr char g_vertex_shader[] = R"GLSL(
  attribute vec3 a_position;
  uniform mat4 u_matrix;

#if MASK == MASK_CIRCULAR
  attribute vec2 a_mask_uv;
  varying vec2 v_mask_uv;
  void mask() {
    v_mask_uv = a_mask_uv;
  }
#else
  void mask() {}
#endif

  void main() {
    gl_Position = u_matrix * vec4(a_position, 1.0);
    mask();
  }
)GLSL";

constexpr char g_fragment_shader[] = R"GLSL(
  precision mediump float;

#if COLOR_BINDING == BINDING_NONE
  vec4 color() {
    return vec4(0.0, 0.0, 0.0, 1.0); // should alpha be 0?
  }
#elif COLOR_BINDING == BINDING_CONSTANT
  uniform vec4 u_color;
  vec4 color() {
    return u_color;
  }
#endif

#if MASK == MASK_CIRCULAR
  varying vec2 v_mask_uv;
  bool mask() {
    return dot(v_mask_uv, v_mask_uv) <= 1.0;
  }
#else
  bool mask() { return true; }
#endif

  void main() {
    if (!mask()) discard; // FIXME(jeffbrown): inefficient!
    gl_FragColor = color();
  }
)GLSL";

void DefineBindingSymbol(GLSLGenerator& generator,
                         const std::string& symbol,
                         BindingType binding_type) {
  switch (binding_type) {
    case BindingType::kNone:
      generator.DefineSymbol(symbol, "BINDING_NONE");
      break;
    case BindingType::kConstant:
      generator.DefineSymbol(symbol, "BINDING_CONSTANT");
      break;
  }
}

void DefineMaskSymbol(GLSLGenerator& generator, Modifier::Mask mask) {
  switch (mask) {
    case Modifier::Mask::kNone:
      generator.DefineSymbol("MASK", "MASK_NONE");
      break;
    case Modifier::Mask::kCircular:
      generator.DefineSymbol("MASK", "MASK_CIRCULAR");
      break;
  }
}

}  // namespace

MaterialShader::MaterialShader(const MaterialShaderDescriptor& descriptor)
    : descriptor_(descriptor) {}

MaterialShader::~MaterialShader() {}

void MaterialShader::Use(const glm::mat4& matrix) const {
  glUseProgram(program_.id());
  glEnableVertexAttribArray(position_);
  if (descriptor_.mask == Modifier::Mask::kCircular)
    glEnableVertexAttribArray(mask_uv_);
  glUniformMatrix4fv(matrix_, 1, GL_FALSE, &matrix[0][0]);
}

void MaterialShader::Bind(const Material& material,
                          const Modifier& modifier) const {
  if (descriptor_.color_binding_type == BindingType::kConstant) {
    const glm::vec4& color = material.color().constant_value();
    glUniform4fv(color_, 1, &color[0]);
  }
}

bool MaterialShader::Compile() {
  std::string prologue = GeneratePrologue();
  std::vector<std::string> vertex_shader_sources{g_decls, prologue,
                                                 g_vertex_shader};
  std::vector<std::string> fragment_shader_sources{g_decls, prologue,
                                                   g_fragment_shader};
  UniqueShader vertex_shader =
      MakeUniqueShader(GL_VERTEX_SHADER, vertex_shader_sources);
  UniqueShader fragment_shader =
      MakeUniqueShader(GL_FRAGMENT_SHADER, fragment_shader_sources);
  if (!vertex_shader || !fragment_shader)
    return false;

  program_ =
      MakeUniqueProgram(std::move(vertex_shader), std::move(fragment_shader));
  if (!program_)
    return false;

  matrix_ = glGetUniformLocation(program_.id(), "u_matrix");
  ESCHER_DCHECK(matrix_ != -1);

  if (descriptor_.color_binding_type == BindingType::kConstant) {
    color_ = glGetUniformLocation(program_.id(), "u_color");
    ESCHER_DCHECK(color_ != -1);
  }

  if (descriptor_.mask == Modifier::Mask::kCircular) {
    mask_uv_ = glGetAttribLocation(program_.id(), "a_mask_uv");
    ESCHER_DCHECK(mask_uv_ != -1);
  }
  return true;
}

std::string MaterialShader::GeneratePrologue() {
  GLSLGenerator generator;
  DefineBindingSymbol(generator, "COLOR_BINDING",
                      descriptor_.color_binding_type);
  DefineMaskSymbol(generator, descriptor_.mask);
  return generator.GenerateCode();
}

}  // namespace escher
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

#include <dune/stuff/la/container/interface.hh>

#include <dune/gdt/space/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
    : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                                 SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                                 SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ElementType>::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                              SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                              SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  static const unsigned int dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType DomainFieldType;
  typedef typename BaseType::DomainType DomainType;

  static const unsigned int dimRange     = BaseType::dimRange;
  static const unsigned int dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType RangeFieldType;
  typedef typename BaseType::RangeType RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other)
    : space_(other.space_)
    , vector_(other.vector_)
    , name_(other.name_)
  {
  }

  ConstDiscreteFunction(ThisType&& source)
    : space_(source.space_)
    , vector_(source.vector_)
    , name_(std::move(source.name_))
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  ~ConstDiscreteFunction()
  {
  }

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.gridPart()->indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr<ConstLocalDiscreteFunctionType>(
        new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
  }

  void visualize(const std::string filename) const
  {
    typedef typename SpaceType::GridPartType::GridViewType GridViewType;
    if (filename.empty())
      DUNE_THROW(RangeError, "Empty filename given!");
    auto adapter = std::make_shared<Stuff::Function::VisualizationAdapter<GridViewType, dimRange>>(*this);
    VTKWriter<GridViewType> vtk_writer(space_.gridPart()->gridView(), VTK::nonconforming);
    vtk_writer.addVertexData(adapter);
    vtk_writer.write(filename);
  } // ... visualize(...)

protected:
  const SpaceType& space_;

private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class SpaceImp, class VectorImp>
class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vec, nm)
    , vector_(vec)
  {
  }

  DiscreteFunction(const ThisType& other)
    : BaseType(other)
    , vector_(other.vector_)
  {
  }

  DiscreteFunction(ThisType&& source)
    : BaseType(std::move(source))
    , vector_(source.vector_)
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  ~DiscreteFunction()
  {
  }

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.gridPart()->indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, vector_, entity);
  }

private:
  using BaseType::space_;
  VectorType& vector_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<commit_msg>[discretefunction.default] use SubsamplingVTKWriter<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
#define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH

#include <memory>
#include <type_traits>

#include <dune/common/exceptions.hh>
#include <dune/common/fvector.hh>

#include <dune/grid/io/file/vtk.hh>

#include <dune/stuff/la/container/interface.hh>

#include <dune/gdt/space/interface.hh>

#include "local.hh"

namespace Dune {
namespace GDT {

template <class SpaceImp, class VectorImp>
class ConstDiscreteFunction
    : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                                 SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                                 SpaceImp::dimRange, SpaceImp::dimRangeCols>
{
  static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
                "SpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
                "VectorImp has to be derived from Stuff::LA::VectorInterface!");
  static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ElementType>::value,
                "Types do not match!");
  typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
                                              SpaceImp::dimDomain, typename SpaceImp::RangeFieldType,
                                              SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType;
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef SpaceImp SpaceType;
  typedef VectorImp VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  static const unsigned int dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainFieldType DomainFieldType;
  typedef typename BaseType::DomainType DomainType;

  static const unsigned int dimRange     = BaseType::dimRange;
  static const unsigned int dimRangeCols = BaseType::dimRangeCols;
  typedef typename BaseType::RangeFieldType RangeFieldType;
  typedef typename BaseType::RangeType RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType;

  ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec,
                        const std::string nm = "dune.gdt.constdiscretefunction")
    : space_(sp)
    , vector_(vec)
    , name_(nm)
  {
    assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!");
  }

  ConstDiscreteFunction(const ThisType& other)
    : space_(other.space_)
    , vector_(other.vector_)
    , name_(other.name_)
  {
  }

  ConstDiscreteFunction(ThisType&& source)
    : space_(source.space_)
    , vector_(source.vector_)
    , name_(std::move(source.name_))
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  ~ConstDiscreteFunction()
  {
  }

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  virtual std::string name() const DS_OVERRIDE
  {
    return name_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

  ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const
  {
    assert(space_.gridPart()->indexSet().contains(entity));
    return ConstLocalDiscreteFunctionType(space_, vector_, entity);
  }

  virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE
  {
    return std::unique_ptr<ConstLocalDiscreteFunctionType>(
        new ConstLocalDiscreteFunctionType(local_discrete_function(entity)));
  }

  void visualize(const std::string filename) const
  {
    typedef typename SpaceType::GridPartType::GridViewType GridViewType;
    if (filename.empty())
      DUNE_THROW(RangeError, "Empty filename given!");
    auto adapter = std::make_shared<Stuff::Function::VisualizationAdapter<GridViewType, dimRange>>(*this);
    SubsamplingVTKWriter<GridViewType> vtk_writer(space_.gridPart()->gridView(), VTK::nonconforming);
    vtk_writer.addVertexData(adapter);
    vtk_writer.write(filename);
  } // ... visualize(...)

protected:
  const SpaceType& space_;

private:
  const VectorType& vector_;
  const std::string name_;
}; // class ConstDiscreteFunction

template <class SpaceImp, class VectorImp>
class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp>
{
  typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType;
  typedef DiscreteFunction<SpaceImp, VectorImp> ThisType;

public:
  typedef typename BaseType::SpaceType SpaceType;
  typedef typename BaseType::VectorType VectorType;
  typedef typename BaseType::EntityType EntityType;
  typedef typename BaseType::LocalfunctionType LocalfunctionType;

  typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType;

  DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction")
    : BaseType(sp, vec, nm)
    , vector_(vec)
  {
  }

  DiscreteFunction(const ThisType& other)
    : BaseType(other)
    , vector_(other.vector_)
  {
  }

  DiscreteFunction(ThisType&& source)
    : BaseType(std::move(source))
    , vector_(source.vector_)
  {
  }

  ThisType& operator=(const ThisType& other) = delete;

  ~DiscreteFunction()
  {
  }

  virtual ThisType* copy() const DS_OVERRIDE
  {
    return new ThisType(*this);
  }

  VectorType& vector()
  {
    return vector_;
  }

  LocalDiscreteFunctionType local_discrete_function(const EntityType& entity)
  {
    assert(space_.gridPart()->indexSet().contains(entity));
    return LocalDiscreteFunctionType(space_, vector_, entity);
  }

private:
  using BaseType::space_;
  VectorType& vector_;
}; // class DiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH
<|endoftext|>