<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hfi_struct.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 13:59:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_struct.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_struct.hxx>
#include <ary/idl/ik_exception.hxx>
#include <ary/idl/ik_struct.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_navi_sub.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_property.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"

extern const String
    C_sCePrefix_Struct("struct");
extern const String
    C_sCePrefix_Exception("exception");

namespace
{

const String
    C_sBaseStruct("Base Hierarchy");
const String
    C_sBaseException("Base Hierarchy");

const String
    C_sList_Elements("Elements' Summary");
const String
    C_sList_Elements_Label("Elements");

const String
    C_sList_ElementDetails("Elements' Details");
const String
    C_sList_ElementDetails_Label("ElementDetails");

enum E_SubListIndices
{
    sli_ElementsSummary = 0,
    sli_ElementsDetails = 1
};

}   // anonymous namespace

HF_IdlStruct::HF_IdlStruct( Environment &         io_rEnv,
                            Xml::Element &        o_rOut,
                            bool                  i_bIsException )
    :   HtmlFactory_Idl(io_rEnv, &o_rOut),
        bIsException(i_bIsException)
{
}

HF_IdlStruct::~HF_IdlStruct()
{
}

void
HF_IdlStruct::Produce_byData( const client & i_ce ) const
{
    const ary::idl::Struct *
        pStruct =
            bIsException
                ?   0
                :   static_cast< const ary::idl::Struct* >(&i_ce);
    bool bIsTemplate =
            pStruct != 0
                ?   pStruct->TemplateParameterType().IsValid()
                :   false;

    Dyn<HF_NaviSubRow>
        pNaviSubRow( &make_Navibar(i_ce) );

    HF_TitleTable
        aTitle(CurOut());
    HF_LinkedNameChain
        aNameChain(aTitle.Add_Row());

    aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);

    // Title:
    StreamLock
        slAnnotations(200);
    get_Annotations(slAnnotations(), i_ce);

    StreamLock rTitle(200);
    if (bIsTemplate)
        rTitle() << "template ";
    rTitle()
        << (bIsException
            ?   C_sCePrefix_Exception
            :   C_sCePrefix_Struct)
        << " "
        << i_ce.LocalName();
    if (bIsTemplate)
    {
        csv_assert(pStruct != 0);
        rTitle()
            << "<"
            << pStruct->TemplateParameter()
            << ">";
    }
    aTitle.Produce_Title(slAnnotations().c_str(), rTitle().c_str());

    // Bases:
    produce_Bases( aTitle.Add_Row(),
                   i_ce,
                   bIsException
                    ?   C_sBaseException
                    :   C_sBaseStruct );

    // Docu:
    write_Docu(aTitle.Add_Row(), i_ce);
    CurOut() << new Html::HorizontalLine();

    // Elements:
    dyn_ce_list
        dpElements;
    if (bIsException)
        ary::idl::ifc_exception::attr::Get_Elements(dpElements, i_ce);
    else
        ary::idl::ifc_struct::attr::Get_Elements(dpElements, i_ce);

    if ( (*dpElements).operator bool() )
    {
        produce_Members( *dpElements,
                         C_sList_Elements,
                         C_sList_Elements_Label,
                         C_sList_ElementDetails,
                         C_sList_ElementDetails_Label );
        pNaviSubRow->SwitchOn(sli_ElementsSummary);
        pNaviSubRow->SwitchOn(sli_ElementsDetails);
    }
    pNaviSubRow->Produce_Row();
}

HtmlFactory_Idl::type_id
HF_IdlStruct::inq_BaseOf( const client & i_ce ) const
{
    return bIsException
                ?   ary::idl::ifc_exception::attr::Base(i_ce)
                :   ary::idl::ifc_struct::attr::Base(i_ce);
}

HF_NaviSubRow &
HF_IdlStruct::make_Navibar( const client & i_ce ) const
{
    HF_IdlNavigationBar
        aNaviBar(Env(), CurOut());
    aNaviBar.Produce_CeMainRow(i_ce);

    DYN HF_NaviSubRow &
        ret = aNaviBar.Add_SubRow();
    ret.AddItem(C_sList_Elements, C_sList_Elements_Label, false);
    ret.AddItem(C_sList_ElementDetails, C_sList_ElementDetails_Label, false);

    CurOut() << new Html::HorizontalLine();
    return ret;
}

void
HF_IdlStruct::produce_MemberDetails( HF_SubTitleTable &  o_table,
                                     const client &      i_ce) const
{
    HF_IdlStructElement
        aElement( Env(), o_table );
    aElement.Produce_byData(i_ce);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.26); FILE MERGED 2008/03/28 16:02:05 rt 1.8.26.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: hfi_struct.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_struct.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_struct.hxx>
#include <ary/idl/ik_exception.hxx>
#include <ary/idl/ik_struct.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_navi_sub.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_property.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"

extern const String
    C_sCePrefix_Struct("struct");
extern const String
    C_sCePrefix_Exception("exception");

namespace
{

const String
    C_sBaseStruct("Base Hierarchy");
const String
    C_sBaseException("Base Hierarchy");

const String
    C_sList_Elements("Elements' Summary");
const String
    C_sList_Elements_Label("Elements");

const String
    C_sList_ElementDetails("Elements' Details");
const String
    C_sList_ElementDetails_Label("ElementDetails");

enum E_SubListIndices
{
    sli_ElementsSummary = 0,
    sli_ElementsDetails = 1
};

}   // anonymous namespace

HF_IdlStruct::HF_IdlStruct( Environment &         io_rEnv,
                            Xml::Element &        o_rOut,
                            bool                  i_bIsException )
    :   HtmlFactory_Idl(io_rEnv, &o_rOut),
        bIsException(i_bIsException)
{
}

HF_IdlStruct::~HF_IdlStruct()
{
}

void
HF_IdlStruct::Produce_byData( const client & i_ce ) const
{
    const ary::idl::Struct *
        pStruct =
            bIsException
                ?   0
                :   static_cast< const ary::idl::Struct* >(&i_ce);
    bool bIsTemplate =
            pStruct != 0
                ?   pStruct->TemplateParameterType().IsValid()
                :   false;

    Dyn<HF_NaviSubRow>
        pNaviSubRow( &make_Navibar(i_ce) );

    HF_TitleTable
        aTitle(CurOut());
    HF_LinkedNameChain
        aNameChain(aTitle.Add_Row());

    aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);

    // Title:
    StreamLock
        slAnnotations(200);
    get_Annotations(slAnnotations(), i_ce);

    StreamLock rTitle(200);
    if (bIsTemplate)
        rTitle() << "template ";
    rTitle()
        << (bIsException
            ?   C_sCePrefix_Exception
            :   C_sCePrefix_Struct)
        << " "
        << i_ce.LocalName();
    if (bIsTemplate)
    {
        csv_assert(pStruct != 0);
        rTitle()
            << "<"
            << pStruct->TemplateParameter()
            << ">";
    }
    aTitle.Produce_Title(slAnnotations().c_str(), rTitle().c_str());

    // Bases:
    produce_Bases( aTitle.Add_Row(),
                   i_ce,
                   bIsException
                    ?   C_sBaseException
                    :   C_sBaseStruct );

    // Docu:
    write_Docu(aTitle.Add_Row(), i_ce);
    CurOut() << new Html::HorizontalLine();

    // Elements:
    dyn_ce_list
        dpElements;
    if (bIsException)
        ary::idl::ifc_exception::attr::Get_Elements(dpElements, i_ce);
    else
        ary::idl::ifc_struct::attr::Get_Elements(dpElements, i_ce);

    if ( (*dpElements).operator bool() )
    {
        produce_Members( *dpElements,
                         C_sList_Elements,
                         C_sList_Elements_Label,
                         C_sList_ElementDetails,
                         C_sList_ElementDetails_Label );
        pNaviSubRow->SwitchOn(sli_ElementsSummary);
        pNaviSubRow->SwitchOn(sli_ElementsDetails);
    }
    pNaviSubRow->Produce_Row();
}

HtmlFactory_Idl::type_id
HF_IdlStruct::inq_BaseOf( const client & i_ce ) const
{
    return bIsException
                ?   ary::idl::ifc_exception::attr::Base(i_ce)
                :   ary::idl::ifc_struct::attr::Base(i_ce);
}

HF_NaviSubRow &
HF_IdlStruct::make_Navibar( const client & i_ce ) const
{
    HF_IdlNavigationBar
        aNaviBar(Env(), CurOut());
    aNaviBar.Produce_CeMainRow(i_ce);

    DYN HF_NaviSubRow &
        ret = aNaviBar.Add_SubRow();
    ret.AddItem(C_sList_Elements, C_sList_Elements_Label, false);
    ret.AddItem(C_sList_ElementDetails, C_sList_ElementDetails_Label, false);

    CurOut() << new Html::HorizontalLine();
    return ret;
}

void
HF_IdlStruct::produce_MemberDetails( HF_SubTitleTable &  o_table,
                                     const client &      i_ce) const
{
    HF_IdlStructElement
        aElement( Env(), o_table );
    aElement.Produce_byData(i_ce);
}
<|endoftext|>


<commit_before>#include <cstdio>

long int f[39];
long int r[39];

long int fib(long int n) {
    if (f[n] != -1)
        return f[n];
    if (n <= 1) {
        f[n] = n;
    } else {
        f[n] = fib(n - 1) + fib(n - 2);
        if (n >= 3)
            r[n] = r[n - 1] + r[n - 2] + 2;
    }
    return f[n];
}

int main() {
    int i, j;
    long int n;
    for (j = 0; j <= 39; j++) {
        f[j] = -1;
        r[j] = -1;
    }

    r[0] = 0;
    r[1] = 0;
    r[2] = 2;

    scanf("%d", &i);
    while (i--) {
        scanf("%ld", &n);
        printf("fib(%ld) = %ld calls = %ld\n", n, r[n], fib(n));
    }
    return 0;
}
<commit_msg>Improves Fibonacci function.<commit_after>#include <cstdio>

long int f[39];
long int r[39];

long int fib(long int n) {
    if (f[n] != -1) return f[n];

    if (n <= 1) {
        f[n] = n;
        r[n] = 0;
    } else {
        f[n] = fib(n - 1) + fib(n - 2);
        r[n] = r[n - 1] + r[n - 2] + 2;
    }

    return f[n];
}

int main() {
    int i, j;
    long int n;

    for (j = 0; j <= 39; j++) {
        f[j] = -1;
        r[j] = -1;
    }

    scanf("%d", &i);
    while (i--) {
        scanf("%ld", &n);
        printf("fib(%ld) = %ld calls = %ld\n", n, r[n], fib(n));
    }

    return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "sot/stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#include <rtl/instance.hxx>

///////////////////////////// class StgIo

// This class holds the storage header and all internal streams.

StgIo::StgIo() : StgCache()
{
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    bCopied   = false;
}

StgIo::~StgIo()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
}

// Load the header. Do not set an error code if the header is invalid.

bool StgIo::Load()
{
    if( pStrm )
    {
        if( aHdr.Load( *this ) )
        {
            if( aHdr.Check() )
                SetupStreams();
            else
                return false;
        }
        else
            return false;
    }
    return Good();
}

// Set up an initial, empty storage

bool StgIo::Init()
{
    aHdr.Init();
    SetupStreams();
    return CommitAll();
}

void StgIo::SetupStreams()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    ResetError();
    SetPhysPageSize( 1 << aHdr.GetPageSize() );
    pFAT = new StgFATStrm( *this );
    pTOC = new StgDirStrm( *this );
    if( !GetError() )
    {
        StgDirEntry* pRoot = pTOC->GetRoot();
        if( pRoot )
        {
            pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 );
            pDataStrm = new StgDataStrm( *this, *pRoot );
            pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() );
            pDataStrm->SetIncrement( GetDataPageSize() );
            pDataStrm->SetEntry( *pRoot );
        }
        else
            SetError( SVSTREAM_FILEFORMAT_ERROR );
    }
}

// get the logical data page size

short StgIo::GetDataPageSize()
{
    return 1 << aHdr.GetDataPageSize();
}

// Commit everything

bool StgIo::CommitAll()
{
    // Store the data (all streams and the TOC)
    if( pTOC && pTOC->Store() && pDataFAT )
    {
        if( Commit() )
        {
            aHdr.SetDataFATStart( pDataFAT->GetStart() );
            aHdr.SetDataFATSize( pDataFAT->GetPages() );
            aHdr.SetTOCStart( pTOC->GetStart() );
            if( aHdr.Store( *this ) )
            {
                pStrm->Flush();
                sal_uLong n = pStrm->GetError();
                SetError( n );
#ifdef DBG_UTIL
                if( n==0 ) ValidateFATs();
#endif
                return n == 0;
            }
        }
    }
    SetError( SVSTREAM_WRITE_ERROR );
    return false;
}

class EasyFat
{
    sal_Int32 *pFat;
    bool  *pFree;
    sal_Int32 nPages;
    sal_Int32 nPageSize;

public:
    EasyFat( StgIo & rIo, StgStrm *pFatStream, sal_Int32 nPSize );
    ~EasyFat() { delete[] pFat; delete[] pFree; }

    sal_Int32 GetPageSize() { return nPageSize; }
    sal_Int32 Count() { return nPages; }
    sal_Int32 operator[]( sal_Int32 nOffset )
    {
        OSL_ENSURE( nOffset >= 0 && nOffset < nPages, "Unexpected offset!" );
        return nOffset >= 0 && nOffset < nPages ? pFat[ nOffset ] : -2;
    }

    sal_uLong Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect );
    bool HasUnrefChains();
};

EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, sal_Int32 nPSize )
{
    nPages = pFatStream->GetSize() >> 2;
    nPageSize = nPSize;
    pFat = new sal_Int32[ nPages ];
    pFree = new bool[ nPages ];

    rtl::Reference< StgPage > pPage;
    sal_Int32 nFatPageSize = (1 << rIo.aHdr.GetPageSize()) - 2;

    for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( ! (nPage % nFatPageSize) )
        {
            pFatStream->Pos2Page( nPage << 2 );
            sal_Int32 nPhysPage = pFatStream->GetPage();
            pPage = rIo.Get( nPhysPage, true );
        }

        pFat[ nPage ] = rIo.GetFromPage( pPage, short( nPage % nFatPageSize ) );
        pFree[ nPage ] = true;
    }
}

bool EasyFat::HasUnrefChains()
{
    for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( pFree[ nPage ] && pFat[ nPage ] != -1 )
            return true;
    }
    return false;
}

sal_uLong EasyFat::Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect )
{
    if( nCount > 0 )
        --nCount /= GetPageSize(), nCount++;

    sal_Int32 nCurPage = nPage;
    while( nCount != 0 )
    {
        if( nCurPage < 0 || nCurPage >= nPages )
            return FAT_OUTOFBOUNDS;
        pFree[ nCurPage ] = false;
        nCurPage = pFat[ nCurPage ];
        //Stream zu lang
        if( nCurPage != nExpect && nCount == 1 )
            return FAT_WRONGLENGTH;
        //Stream zu kurz
        if( nCurPage == nExpect && nCount != 1 && nCount != -1 )
            return FAT_WRONGLENGTH;
        // letzter Block bei Stream ohne Laenge
        if( nCurPage == nExpect && nCount == -1 )
            nCount = 1;
        if( nCount != -1 )
            nCount--;
    }
    return FAT_OK;
}

class Validator
{
    sal_uLong nError;

    EasyFat aSmallFat;
    EasyFat aFat;

    StgIo &rIo;

    sal_uLong ValidateMasterFATs();
    sal_uLong ValidateDirectoryEntries();
    sal_uLong FindUnrefedChains();
    sal_uLong MarkAll( StgDirEntry *pEntry );

public:

    Validator( StgIo &rIo );
    bool IsError() { return nError != 0; }
};

Validator::Validator( StgIo &rIoP )
    : aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ),
      aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ),
      rIo( rIoP )
{
    sal_uLong nErr = nError = FAT_OK;

    if( ( nErr = ValidateMasterFATs() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = ValidateDirectoryEntries() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = FindUnrefedChains()) != FAT_OK )
        nError = nErr;
}

sal_uLong Validator::ValidateMasterFATs()
{
    sal_Int32 nCount = rIo.aHdr.GetFATSize();
    sal_uLong nErr;
    if ( !rIo.pFAT )
        return FAT_INMEMORYERROR;

    for( sal_Int32 i = 0; i < nCount; i++ )
    {
        if( ( nErr = aFat.Mark(rIo.pFAT->GetPage( short(i), false ), aFat.GetPageSize(), -3 )) != FAT_OK )
            return nErr;
    }
    if( rIo.aHdr.GetMasters() )
        if( ( nErr = aFat.Mark(rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK )
            return nErr;

    return FAT_OK;
}

sal_uLong Validator::MarkAll( StgDirEntry *pEntry )
{
    if ( !pEntry )
        return FAT_INMEMORYERROR;

    StgIterator aIter( *pEntry );
    sal_uLong nErr = FAT_OK;
    for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() )
    {
        if( p->aEntry.GetType() == STG_STORAGE )
        {
            nErr = MarkAll( p );
            if( nErr != FAT_OK )
                return nErr;
        }
        else
        {
            sal_Int32 nSize = p->aEntry.GetSize();
            if( nSize < rIo.aHdr.GetThreshold()  )
                nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            else
                nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            if( nErr != FAT_OK )
                return nErr;
        }
    }
    return FAT_OK;
}

sal_uLong Validator::ValidateDirectoryEntries()
{
    if ( !rIo.pTOC )
        return FAT_INMEMORYERROR;

    // Normale DirEntries
    sal_uLong nErr = MarkAll( rIo.pTOC->GetRoot() );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data
    nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(),
                 rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data FAT
    nErr = aFat.Mark(
        rIo.aHdr.GetDataFATStart(),
        rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // TOC
    nErr = aFat.Mark(
        rIo.aHdr.GetTOCStart(), -1, -2 );
    return nErr;
}

sal_uLong Validator::FindUnrefedChains()
{
    if( aSmallFat.HasUnrefChains() ||
        aFat.HasUnrefChains() )
        return FAT_UNREFCHAIN;
    else
        return FAT_OK;
}

namespace { struct ErrorLink : public rtl::Static<Link, ErrorLink > {}; }

void StgIo::SetErrorLink( const Link& rLink )
{
    ErrorLink::get() = rLink;
}

const Link& StgIo::GetErrorLink()
{
    return ErrorLink::get();
}

sal_uLong StgIo::ValidateFATs()
{
    if( bFile )
    {
        Validator *pV = new Validator( *this );
        bool bRet1 = !pV->IsError(), bRet2 = true ;
        delete pV;

        SvFileStream *pFileStrm = ( SvFileStream *) GetStrm();
        if ( !pFileStrm )
            return FAT_INMEMORYERROR;

        StgIo aIo;
        if( aIo.Open( pFileStrm->GetFileName(),
                      STREAM_READ  | STREAM_SHARE_DENYNONE) &&
            aIo.Load() )
        {
            pV = new Validator( aIo );
            bRet2 = !pV->IsError();
            delete pV;
        }

        sal_uLong nErr;
        if( bRet1 != bRet2 )
            nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR;
        else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR;
        if( nErr != FAT_OK && !bCopied )
        {
            StgLinkArg aArg;
            aArg.aFile = pFileStrm->GetFileName();
            aArg.nErr = nErr;
            ErrorLink::get().Call( &aArg );
            bCopied = true;
        }
//      DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt");
        return nErr;
    }
//  OSL_FAIL("Validiere nicht (kein FileStorage)");
    return FAT_OK;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused functions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "sot/stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#include <rtl/instance.hxx>

///////////////////////////// class StgIo

// This class holds the storage header and all internal streams.

StgIo::StgIo() : StgCache()
{
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    bCopied   = false;
}

StgIo::~StgIo()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
}

// Load the header. Do not set an error code if the header is invalid.

bool StgIo::Load()
{
    if( pStrm )
    {
        if( aHdr.Load( *this ) )
        {
            if( aHdr.Check() )
                SetupStreams();
            else
                return false;
        }
        else
            return false;
    }
    return Good();
}

// Set up an initial, empty storage

bool StgIo::Init()
{
    aHdr.Init();
    SetupStreams();
    return CommitAll();
}

void StgIo::SetupStreams()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    ResetError();
    SetPhysPageSize( 1 << aHdr.GetPageSize() );
    pFAT = new StgFATStrm( *this );
    pTOC = new StgDirStrm( *this );
    if( !GetError() )
    {
        StgDirEntry* pRoot = pTOC->GetRoot();
        if( pRoot )
        {
            pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 );
            pDataStrm = new StgDataStrm( *this, *pRoot );
            pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() );
            pDataStrm->SetIncrement( GetDataPageSize() );
            pDataStrm->SetEntry( *pRoot );
        }
        else
            SetError( SVSTREAM_FILEFORMAT_ERROR );
    }
}

// get the logical data page size

short StgIo::GetDataPageSize()
{
    return 1 << aHdr.GetDataPageSize();
}

// Commit everything

bool StgIo::CommitAll()
{
    // Store the data (all streams and the TOC)
    if( pTOC && pTOC->Store() && pDataFAT )
    {
        if( Commit() )
        {
            aHdr.SetDataFATStart( pDataFAT->GetStart() );
            aHdr.SetDataFATSize( pDataFAT->GetPages() );
            aHdr.SetTOCStart( pTOC->GetStart() );
            if( aHdr.Store( *this ) )
            {
                pStrm->Flush();
                sal_uLong n = pStrm->GetError();
                SetError( n );
#ifdef DBG_UTIL
                if( n==0 ) ValidateFATs();
#endif
                return n == 0;
            }
        }
    }
    SetError( SVSTREAM_WRITE_ERROR );
    return false;
}

class EasyFat
{
    sal_Int32 *pFat;
    bool  *pFree;
    sal_Int32 nPages;
    sal_Int32 nPageSize;

public:
    EasyFat( StgIo & rIo, StgStrm *pFatStream, sal_Int32 nPSize );
    ~EasyFat() { delete[] pFat; delete[] pFree; }

    sal_Int32 GetPageSize() { return nPageSize; }

    sal_uLong Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect );
    bool HasUnrefChains();
};

EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, sal_Int32 nPSize )
{
    nPages = pFatStream->GetSize() >> 2;
    nPageSize = nPSize;
    pFat = new sal_Int32[ nPages ];
    pFree = new bool[ nPages ];

    rtl::Reference< StgPage > pPage;
    sal_Int32 nFatPageSize = (1 << rIo.aHdr.GetPageSize()) - 2;

    for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( ! (nPage % nFatPageSize) )
        {
            pFatStream->Pos2Page( nPage << 2 );
            sal_Int32 nPhysPage = pFatStream->GetPage();
            pPage = rIo.Get( nPhysPage, true );
        }

        pFat[ nPage ] = rIo.GetFromPage( pPage, short( nPage % nFatPageSize ) );
        pFree[ nPage ] = true;
    }
}

bool EasyFat::HasUnrefChains()
{
    for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( pFree[ nPage ] && pFat[ nPage ] != -1 )
            return true;
    }
    return false;
}

sal_uLong EasyFat::Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect )
{
    if( nCount > 0 )
        --nCount /= GetPageSize(), nCount++;

    sal_Int32 nCurPage = nPage;
    while( nCount != 0 )
    {
        if( nCurPage < 0 || nCurPage >= nPages )
            return FAT_OUTOFBOUNDS;
        pFree[ nCurPage ] = false;
        nCurPage = pFat[ nCurPage ];
        //Stream zu lang
        if( nCurPage != nExpect && nCount == 1 )
            return FAT_WRONGLENGTH;
        //Stream zu kurz
        if( nCurPage == nExpect && nCount != 1 && nCount != -1 )
            return FAT_WRONGLENGTH;
        // letzter Block bei Stream ohne Laenge
        if( nCurPage == nExpect && nCount == -1 )
            nCount = 1;
        if( nCount != -1 )
            nCount--;
    }
    return FAT_OK;
}

class Validator
{
    sal_uLong nError;

    EasyFat aSmallFat;
    EasyFat aFat;

    StgIo &rIo;

    sal_uLong ValidateMasterFATs();
    sal_uLong ValidateDirectoryEntries();
    sal_uLong FindUnrefedChains();
    sal_uLong MarkAll( StgDirEntry *pEntry );

public:

    Validator( StgIo &rIo );
    bool IsError() { return nError != 0; }
};

Validator::Validator( StgIo &rIoP )
    : aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ),
      aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ),
      rIo( rIoP )
{
    sal_uLong nErr = nError = FAT_OK;

    if( ( nErr = ValidateMasterFATs() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = ValidateDirectoryEntries() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = FindUnrefedChains()) != FAT_OK )
        nError = nErr;
}

sal_uLong Validator::ValidateMasterFATs()
{
    sal_Int32 nCount = rIo.aHdr.GetFATSize();
    sal_uLong nErr;
    if ( !rIo.pFAT )
        return FAT_INMEMORYERROR;

    for( sal_Int32 i = 0; i < nCount; i++ )
    {
        if( ( nErr = aFat.Mark(rIo.pFAT->GetPage( short(i), false ), aFat.GetPageSize(), -3 )) != FAT_OK )
            return nErr;
    }
    if( rIo.aHdr.GetMasters() )
        if( ( nErr = aFat.Mark(rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK )
            return nErr;

    return FAT_OK;
}

sal_uLong Validator::MarkAll( StgDirEntry *pEntry )
{
    if ( !pEntry )
        return FAT_INMEMORYERROR;

    StgIterator aIter( *pEntry );
    sal_uLong nErr = FAT_OK;
    for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() )
    {
        if( p->aEntry.GetType() == STG_STORAGE )
        {
            nErr = MarkAll( p );
            if( nErr != FAT_OK )
                return nErr;
        }
        else
        {
            sal_Int32 nSize = p->aEntry.GetSize();
            if( nSize < rIo.aHdr.GetThreshold()  )
                nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            else
                nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            if( nErr != FAT_OK )
                return nErr;
        }
    }
    return FAT_OK;
}

sal_uLong Validator::ValidateDirectoryEntries()
{
    if ( !rIo.pTOC )
        return FAT_INMEMORYERROR;

    // Normale DirEntries
    sal_uLong nErr = MarkAll( rIo.pTOC->GetRoot() );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data
    nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(),
                 rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data FAT
    nErr = aFat.Mark(
        rIo.aHdr.GetDataFATStart(),
        rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // TOC
    nErr = aFat.Mark(
        rIo.aHdr.GetTOCStart(), -1, -2 );
    return nErr;
}

sal_uLong Validator::FindUnrefedChains()
{
    if( aSmallFat.HasUnrefChains() ||
        aFat.HasUnrefChains() )
        return FAT_UNREFCHAIN;
    else
        return FAT_OK;
}

namespace { struct ErrorLink : public rtl::Static<Link, ErrorLink > {}; }

void StgIo::SetErrorLink( const Link& rLink )
{
    ErrorLink::get() = rLink;
}

const Link& StgIo::GetErrorLink()
{
    return ErrorLink::get();
}

sal_uLong StgIo::ValidateFATs()
{
    if( bFile )
    {
        Validator *pV = new Validator( *this );
        bool bRet1 = !pV->IsError(), bRet2 = true ;
        delete pV;

        SvFileStream *pFileStrm = ( SvFileStream *) GetStrm();
        if ( !pFileStrm )
            return FAT_INMEMORYERROR;

        StgIo aIo;
        if( aIo.Open( pFileStrm->GetFileName(),
                      STREAM_READ  | STREAM_SHARE_DENYNONE) &&
            aIo.Load() )
        {
            pV = new Validator( aIo );
            bRet2 = !pV->IsError();
            delete pV;
        }

        sal_uLong nErr;
        if( bRet1 != bRet2 )
            nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR;
        else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR;
        if( nErr != FAT_OK && !bCopied )
        {
            StgLinkArg aArg;
            aArg.aFile = pFileStrm->GetFileName();
            aArg.nErr = nErr;
            ErrorLink::get().Call( &aArg );
            bCopied = true;
        }
//      DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt");
        return nErr;
    }
//  OSL_FAIL("Validiere nicht (kein FileStorage)");
    return FAT_OK;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Bolloré telecom
 *
 * Author:
 *	Jeremy Lainé
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 */

#include "QXmppConstants.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppUtils.h"

#include <QDomElement>

QList<QXmppElement> QXmppDiscoveryIq::getItems() const
{
    return m_items;
}

void QXmppDiscoveryIq::setItems(const QList<QXmppElement> &items)
{
    m_items = items;
}

enum QXmppDiscoveryIq::QueryType QXmppDiscoveryIq::getQueryType() const
{
    return m_queryType;
}

void QXmppDiscoveryIq::setQueryType(enum QXmppDiscoveryIq::QueryType type)
{
    m_queryType = type;
}

bool QXmppDiscoveryIq::isDiscoveryIq( QDomElement &element )
{
    QDomElement queryElement = element.firstChildElement("query");
    return (queryElement.namespaceURI() == ns_disco_info ||
            queryElement.namespaceURI() == ns_disco_items);
}

void QXmppDiscoveryIq::parse( QDomElement &element )
{
    setFrom(element.attribute("from"));
    setTo(element.attribute("to"));
    setTypeFromStr(element.attribute("type"));
    QDomElement queryElement = element.firstChildElement("query");
    if (queryElement.namespaceURI() == ns_disco_items)
        m_queryType = ItemsQuery;
    else
        m_queryType = InfoQuery;

    QDomElement itemElement = queryElement.firstChildElement();
    while (!itemElement.isNull())
    {
        m_items.append(QXmppElement(element));
        itemElement = itemElement.nextSiblingElement();
    }
}

void QXmppDiscoveryIq::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
    writer->writeStartElement("query");
    helperToXmlAddAttribute(writer, "xmlns",
        m_queryType == InfoQuery ? ns_disco_info : ns_disco_items);
    foreach (const QXmppElement &item, m_items)
        item.toXml(writer);
    writer->writeEndElement();
}

<commit_msg>fix parsing of discovery items<commit_after>/*
 * Copyright (C) 2010 Bolloré telecom
 *
 * Author:
 *	Jeremy Lainé
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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.
 *
 */

#include "QXmppConstants.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppUtils.h"

#include <QDomElement>

QList<QXmppElement> QXmppDiscoveryIq::getItems() const
{
    return m_items;
}

void QXmppDiscoveryIq::setItems(const QList<QXmppElement> &items)
{
    m_items = items;
}

enum QXmppDiscoveryIq::QueryType QXmppDiscoveryIq::getQueryType() const
{
    return m_queryType;
}

void QXmppDiscoveryIq::setQueryType(enum QXmppDiscoveryIq::QueryType type)
{
    m_queryType = type;
}

bool QXmppDiscoveryIq::isDiscoveryIq( QDomElement &element )
{
    QDomElement queryElement = element.firstChildElement("query");
    return (queryElement.namespaceURI() == ns_disco_info ||
            queryElement.namespaceURI() == ns_disco_items);
}

void QXmppDiscoveryIq::parse( QDomElement &element )
{
    setFrom(element.attribute("from"));
    setTo(element.attribute("to"));
    setTypeFromStr(element.attribute("type"));
    QDomElement queryElement = element.firstChildElement("query");
    if (queryElement.namespaceURI() == ns_disco_items)
        m_queryType = ItemsQuery;
    else
        m_queryType = InfoQuery;

    QDomElement itemElement = queryElement.firstChildElement();
    while (!itemElement.isNull())
    {
        m_items.append(QXmppElement(itemElement));
        itemElement = itemElement.nextSiblingElement();
    }
}

void QXmppDiscoveryIq::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
    writer->writeStartElement("query");
    helperToXmlAddAttribute(writer, "xmlns",
        m_queryType == InfoQuery ? ns_disco_info : ns_disco_items);
    foreach (const QXmppElement &item, m_items)
        item.toXml(writer);
    writer->writeEndElement();
}

<|endoftext|>


<commit_before>#pragma once
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <vector>

#include "stiffness_matrix.hpp"

//! Sparse Matrix type. Makes using this type easier.
typedef Eigen::SparseMatrix<double> SparseMatrix;

//! Used for filling the sparse matrix.
typedef Eigen::Triplet<double> Triplet;

//----------------AssembleMatrixBegin----------------
//! Assemble the stiffness matrix
//! for the linear system
//!
//! @param[out] A will at the end contain the Galerkin matrix
//! @param[in] vertices a list of triangle vertices
//! @param[in] dofs a list of the dofs' indices in each triangle
template <class Matrix>
void assembleStiffnessMatrix(Matrix &A, const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &dofs, const int &N) {
	const int numberOfElements = dofs.rows();
	A.resize(N, N);

	std::vector<Triplet> triplets;

	triplets.reserve(numberOfElements * 6 * 10);
	// (write your solution here)
	A.setFromTriplets(triplets.begin(), triplets.end());
}
//----------------AssembleMatrixEnd----------------
<commit_msg>Solved series 3 problem 1f<commit_after>#pragma once
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <vector>

#include "stiffness_matrix.hpp"

//! Sparse Matrix type. Makes using this type easier.
typedef Eigen::SparseMatrix<double> SparseMatrix;

//! Used for filling the sparse matrix.
typedef Eigen::Triplet<double> Triplet;

//----------------AssembleMatrixBegin----------------
//! Assemble the stiffness matrix
//! for the linear system
//!
//! @param[out] A will at the end contain the Galerkin matrix
//! @param[in] vertices a list of triangle vertices
//! @param[in] dofs a list of the dofs' indices in each triangle
template <class Matrix>
void assembleStiffnessMatrix(Matrix &A, const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &dofs, const int &N) {
	const int numberOfElements = dofs.rows();
	A.resize(N, N);

	std::vector<Triplet> triplets;

	triplets.reserve(numberOfElements * 6 * 10);
	// (write your solution here)
	for (int i = 0; i < numberOfElements; ++i) {
		auto &indexSet = dofs.row(i);

		const auto &a = vertices.row(indexSet(0));
		const auto &b = vertices.row(indexSet(1));
		const auto &c = vertices.row(indexSet(2));

		Eigen::MatrixXd stiffnessMatrix;
		computeStiffnessMatrix(stiffnessMatrix, a, b, c);

		for (int n = 0; n < 6; ++n) {
			for (int m = 0; m < 6; ++m) {
				auto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));
				triplets.push_back(triplet);
			}
		}
	}
	A.setFromTriplets(triplets.begin(), triplets.end());
}
//----------------AssembleMatrixEnd----------------
<|endoftext|>


<commit_before>/** @file gsBoundaryConditions_test.cpp

 @brief test gsPde/gsBoundaryConditions

 This file is part of the G+Smo library.

 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 Author(s): A. Mantzaflaris,  H. Weiner
 **/

#include "gismo_unittest.h"
#include <typeinfo>
#include <memory>

std::string getBoxSideExpectedString(std::string string, int index)
{
    std::ostringstream stream;
    std::string result;
    stream << string << " (" << index << ")";
    result = stream.str();
    return result;
}

std::string getBoxSideActualString(gismo::boxSide boxSide)
{
    std::ostringstream stream;
    std::string result;
    stream << boxSide;
    result = stream.str();
    return result;
}

std::string getFunctionExprExpectedString(std::string string)
{
    std::ostringstream stream;
    std::string result;
    stream << "[ " << string << " ]";
    result = stream.str();
    return result;
}

std::string getFunctionExprActualString(gsFunctionExpr<real_t> func)
{
    std::ostringstream stream;
    std::string result;
    func.print(stream);
    result = stream.str();
    return result;
}

gsBoundaryConditions<real_t> gsBoundaryConditions_loadFromFile(std::string path)
{
    gsBoundaryConditions<real_t> result;
    gsReadFile<>(path, result);
    return result;
}

void gsBoundaryConditions_saveToFile(std::string path,
        gsBoundaryConditions<real_t> &sut)
{
    // clean-up before using file
    remove(path.c_str());
    // now save...
    gsFileData<> write;
    write << sut;
    write.dump(path);
}

// create the same gsBoundary condition as in test-data file "bc.xml"
gsBoundaryConditions<real_t> createBcGsBoundaryConditiions()
{
    // set-up
    gsBoundaryConditions<real_t> result;
    return result;
}

gsBoundaryConditions<real_t> createSimpleGsBoundaryConditiions()
{
    gsBoundaryConditions<real_t> result;
    return result;
}

gsFunctionExpr<real_t> getFunctionExpr(boundary_condition<real_t> bc)
{
    bool funcTypeSame1 = (typeid(*bc.m_function)
            == typeid(gsFunctionExpr<real_t> ));
    CHECK(funcTypeSame1);
    gsFunction<real_t>::Ptr ptr = bc.m_function;
    gsFunctionExpr<real_t> * ptr2 =
            dynamic_cast<gsFunctionExpr<real_t> *>(ptr.get());
    gsFunctionExpr<real_t> result = *ptr2;
    return result;
}

void checkBoundaryCondition(boundary_condition<real_t> bc, bool parametric,
        std::string label, gismo::condition_type::type conditionType, int patch,
        int index, int unknown, int unkcomp, int domainDim,
        std::string funcName)
{
    // check boundary condition itself
    CHECK_EQUAL(parametric, bc.m_parametric);
    CHECK_EQUAL(label, bc.m_label);
    CHECK_EQUAL(conditionType, bc.m_type);
    CHECK_EQUAL(patch, bc.ps.patch);
    CHECK_EQUAL(index, bc.ps.m_index);
    CHECK_EQUAL(unknown, bc.m_unknown);
    CHECK_EQUAL(unkcomp, bc.m_unkcomp);
    // check functionExpr
    gismo::gsFunctionExpr<real_t> func = getFunctionExpr(bc);
    CHECK_EQUAL(domainDim, func.domainDim());
    std::string expectedName = getFunctionExprExpectedString(funcName);
    std::string actualName = getFunctionExprActualString(func);
    CHECK_EQUAL(expectedName, actualName);
}

void checkGsBoundaryCondition(const gsBoundaryConditions<real_t> & sut)
{
    // check corner value(s)
    gismo::gsBoundaryConditions<real_t>::cornerContainer c1 =
            sut.cornerValues();
    unsigned elems1 = 1;
    CHECK_EQUAL(elems1, c1.size());
    gismo::corner_value<real_t> cv1 = c1[0];
    CHECK_EQUAL(0, cv1.corner);
    CHECK_EQUAL(0, cv1.corner.m_index);
    CHECK_EQUAL(0, cv1.patch);
    CHECK_EQUAL(0.0, cv1.value);
    CHECK_EQUAL(0, cv1.unknown);

    // check dirichlet conditions
    std::string label1 = "Dirichlet";
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc0 = sut.container(
            label1);
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc1 =
            sut.dirichletSides();
    unsigned elems2 = 6;
    CHECK_EQUAL(elems2, bcc0.size());
    CHECK_EQUAL(elems2, bcc1.size());
    // check boundary conditions themselves
    std::string funcName0 = "0";
    int patches[4] =
    { 0, 0, 1, 1 };
    int indizes[4] =
    { 1, 3, 1, 2 };
    int unknown = 0;
    int unkcomp = 0;
    int domainDim = 2;
    for (int i = 0; i < 4; i++)
    {
        checkBoundaryCondition(bcc0[i], false, label1,
                gismo::condition_type::dirichlet, patches[i], indizes[i],
                unknown, unkcomp, domainDim, funcName0);
    }

    std::string funcName1 = "sin(pi*x)*sin(pi*y)";
    int patch4 = 0;
    int index4 = 2;
    int patch5 = 0;
    int index5 = 4;
    checkBoundaryCondition(bcc0[4], false, label1,
            gismo::condition_type::dirichlet, patch4, index4, unknown, unkcomp,
            domainDim, funcName1);
    checkBoundaryCondition(bcc0[5], false, label1,
            gismo::condition_type::dirichlet, patch5, index5, unknown, unkcomp,
            domainDim, funcName1);

    // check neumann conditions
    std::string label2 = "Neumann";
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc2 = sut.container(
            label2);
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc3 = sut.neumannSides();
    unsigned elems3 = 2;
    CHECK_EQUAL(elems3, bcc2.size());
    CHECK_EQUAL(elems3, bcc3.size());
    int patch6 = 1;
    int index6 = 3;
    int patch7 = 1;
    int index7 = 4;
    checkBoundaryCondition(bcc2[0], false, label2,
            gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
            domainDim, funcName0);
    checkBoundaryCondition(bcc3[0], false, label2,
            gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
            domainDim, funcName0);
    checkBoundaryCondition(bcc2[1], false, label2,
            gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
            domainDim, funcName0);
    checkBoundaryCondition(bcc3[1], false, label2,
            gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
            domainDim, funcName0);

    // check robin conditions
    std::string label3 = "Robin";
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc4 = sut.container(
            label3);
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc5 = sut.robinSides();
    unsigned elems4 = 0;
    CHECK_EQUAL(elems4, bcc4.size());
    CHECK_EQUAL(elems4, bcc5.size());
    // check bctype_iterator
    typedef typename gismo::gsBoundaryConditions<real_t>::const_bciterator bctype_it;
    int c = 0;
    for (bctype_it it = sut.beginAll(); it != sut.endAll(); ++it)
    {
        c++;
    }
    CHECK_EQUAL(3, c);
}

SUITE(gsBoundaryConditions_test)
{
    TEST(gsBoundaryConditions_test_condition_type)
    {
        gismo::condition_type::type myType = gismo::condition_type::neumann;
        CHECK_EQUAL(gismo::condition_type::neumann, myType);
        CHECK_EQUAL(1, myType);
    }

    TEST(gsBoundaryConditions_test_function_expr)
    {
        int dim1 = 1;
        std::string funcName1 = "tan(x)";
        gsFunctionExpr<real_t> func1 = gsFunctionExpr<real_t>(funcName1, dim1);
        int domainDim1 = func1.domainDim();
        CHECK_EQUAL(dim1, domainDim1);
        std::string expectedName1 = getFunctionExprExpectedString(funcName1);
        std::string actualName1 = getFunctionExprActualString(func1);
        CHECK_EQUAL(expectedName1, actualName1);
        int dim2 = 2;
        std::string funcName2 = "sin(x)*sin(y)";
        gsFunctionExpr<real_t> func2 = gsFunctionExpr<real_t>(funcName2, dim2);
        int domainDim2 = func2.domainDim();
        CHECK_EQUAL(dim2, domainDim2);
        std::string expectedName2 = getFunctionExprExpectedString(funcName2);
        std::string actualName2 = getFunctionExprActualString(func2);
        CHECK_EQUAL(expectedName2, actualName2);
    }

    TEST(gsBoundaryConditions_test_box_side)
    {
        int index1 = 1;
        gismo::boxSide boxSide1 = gismo::boxSide(index1);
        CHECK_EQUAL(index1, boxSide1.m_index);
        std::string expect1 = getBoxSideExpectedString("west", index1);
        std::string actual1 = getBoxSideActualString(boxSide1);
        CHECK_EQUAL(expect1, actual1);
        int index2 = 7;
        gismo::boxSide boxSide2 = gismo::boxSide(index2);
        CHECK_EQUAL(index2, boxSide2.m_index);
        std::string expect2 = getBoxSideExpectedString("side", index2);
        std::string actual2 = getBoxSideActualString(boxSide2);
        CHECK_EQUAL(expect2, actual2);
    }

    TEST(gsBoundaryConditions_test_boundary_condition)
    {
        int dim1 = 1;
        std::string funcName1 = "tan(x)";
        int index1 = 1;
        int index2 = 2;
        gismo::boxSide boxSide1 = gismo::boxSide(index1);
        gismo::boundary_condition<real_t>::function_ptr funcPtr1 =
                gismo::memory::make_shared(
                        new gsFunctionExpr<real_t>(funcName1, dim1));
        std::string label1 = "Dirichlet";
        bool parametric1 = true;
        int unknown1 = 1;
        int unkcomp1 = 2;
        gismo::boundary_condition<real_t> bound = gismo::boundary_condition<real_t>(
                index2, boxSide1, funcPtr1, label1, unknown1, unkcomp1,
                parametric1);
        CHECK_EQUAL(parametric1, bound.m_parametric);
        CHECK_EQUAL(label1, bound.m_label);
        CHECK_EQUAL(gismo::condition_type::dirichlet, bound.m_type);
        CHECK_EQUAL(index2, bound.ps.patch);
        CHECK_EQUAL(index2, bound.patch());
        CHECK_EQUAL(index1, bound.ps.m_index);
        CHECK_EQUAL(funcPtr1, bound.m_function);
        CHECK_EQUAL(unknown1, bound.m_unknown);
        CHECK_EQUAL(unkcomp1, bound.m_unkcomp);
    }

    TEST(gsBoundaryConditions_test_box_corner)
    {
        int index1 = 3;
        gismo::boxCorner c1 = gismo::boxCorner(index1);
        CHECK_EQUAL(index1, c1.m_index);
    }

    TEST(gsBoundaryConditions_test_corner_value)
    {
        int index1 = 3;
        gismo::boxCorner c1 = gismo::boxCorner(index1);
        int p1 = 2;
        real_t v1 = 3.0;
        int u1 = 4;
        gismo::corner_value<real_t> cornerVal1 = gismo::corner_value<real_t>(p1, c1,
                v1, u1);
        CHECK_EQUAL(c1, cornerVal1.corner);
        CHECK_EQUAL(index1, cornerVal1.corner.m_index);
        CHECK_EQUAL(p1, cornerVal1.patch);
        CHECK_EQUAL(v1, cornerVal1.value);
        CHECK_EQUAL(u1, cornerVal1.unknown);
    }

    /***
     * test loading from bc.xml
     */
    TEST(gsBoundaryConditions_load_from_bc_xml)
    {
        std::string path = GISMO_DATA_DIR;
        path += "gsBoundaryConditions/bc.xml";
        gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path);
        checkGsBoundaryCondition(sut);
    }

    /***
     * test loading from bc.xml and
     * saving to bc2.xml
     * and ensure that bc.xml and bc2.xml have
     * the same content
     */
    TEST(gsBoundaryConditions_save_load_bc_xml)
    {
        std::string path1 = GISMO_DATA_DIR;
        path1 += "/gsBoundaryConditions/bc.xml";
        std::string path2 = gismo::util::getTempPath();
        path2 += "/bc2.xml";

        gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path1);
        gsBoundaryConditions_saveToFile(path2, sut);
        gsBoundaryConditions<real_t> sut2 = gsBoundaryConditions_loadFromFile(path2);
        checkGsBoundaryCondition(sut2);
    }

}
<commit_msg>warn fix<commit_after>/** @file gsBoundaryConditions_test.cpp

 @brief test gsPde/gsBoundaryConditions

 This file is part of the G+Smo library.

 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 Author(s): A. Mantzaflaris,  H. Weiner
 **/

#include "gismo_unittest.h"
#include <typeinfo>
#include <memory>

std::string getBoxSideExpectedString(std::string string, int index)
{
    std::ostringstream stream;
    std::string result;
    stream << string << " (" << index << ")";
    result = stream.str();
    return result;
}

std::string getBoxSideActualString(gismo::boxSide boxSide)
{
    std::ostringstream stream;
    std::string result;
    stream << boxSide;
    result = stream.str();
    return result;
}

std::string getFunctionExprExpectedString(std::string string)
{
    std::ostringstream stream;
    std::string result;
    stream << "[ " << string << " ]";
    result = stream.str();
    return result;
}

std::string getFunctionExprActualString(gsFunctionExpr<real_t> func)
{
    std::ostringstream stream;
    std::string result;
    func.print(stream);
    result = stream.str();
    return result;
}

gsBoundaryConditions<real_t> gsBoundaryConditions_loadFromFile(std::string path)
{
    gsBoundaryConditions<real_t> result;
    gsReadFile<>(path, result);
    return result;
}

void gsBoundaryConditions_saveToFile(std::string path,
        gsBoundaryConditions<real_t> &sut)
{
    // clean-up before using file
    remove(path.c_str());
    // now save...
    gsFileData<> write;
    write << sut;
    write.dump(path);
}

// create the same gsBoundary condition as in test-data file "bc.xml"
gsBoundaryConditions<real_t> createBcGsBoundaryConditiions()
{
    // set-up
    gsBoundaryConditions<real_t> result;
    return result;
}

gsBoundaryConditions<real_t> createSimpleGsBoundaryConditiions()
{
    gsBoundaryConditions<real_t> result;
    return result;
}

gsFunctionExpr<real_t> getFunctionExpr(boundary_condition<real_t> bc)
{
    bool funcTypeSame1 =
        dynamic_cast<gsFunctionExpr<real_t>*>(bc.m_function.get());
    CHECK(funcTypeSame1);
    gsFunction<real_t>::Ptr ptr = bc.m_function;
    gsFunctionExpr<real_t> * ptr2 =
            dynamic_cast<gsFunctionExpr<real_t> *>(ptr.get());
    gsFunctionExpr<real_t> result = *ptr2;
    return result;
}

void checkBoundaryCondition(boundary_condition<real_t> bc, bool parametric,
        std::string label, gismo::condition_type::type conditionType, int patch,
        int index, int unknown, int unkcomp, int domainDim,
        std::string funcName)
{
    // check boundary condition itself
    CHECK_EQUAL(parametric, bc.m_parametric);
    CHECK_EQUAL(label, bc.m_label);
    CHECK_EQUAL(conditionType, bc.m_type);
    CHECK_EQUAL(patch, bc.ps.patch);
    CHECK_EQUAL(index, bc.ps.m_index);
    CHECK_EQUAL(unknown, bc.m_unknown);
    CHECK_EQUAL(unkcomp, bc.m_unkcomp);
    // check functionExpr
    gismo::gsFunctionExpr<real_t> func = getFunctionExpr(bc);
    CHECK_EQUAL(domainDim, func.domainDim());
    std::string expectedName = getFunctionExprExpectedString(funcName);
    std::string actualName = getFunctionExprActualString(func);
    CHECK_EQUAL(expectedName, actualName);
}

void checkGsBoundaryCondition(const gsBoundaryConditions<real_t> & sut)
{
    // check corner value(s)
    gismo::gsBoundaryConditions<real_t>::cornerContainer c1 =
            sut.cornerValues();
    unsigned elems1 = 1;
    CHECK_EQUAL(elems1, c1.size());
    gismo::corner_value<real_t> cv1 = c1[0];
    CHECK_EQUAL(0, cv1.corner);
    CHECK_EQUAL(0, cv1.corner.m_index);
    CHECK_EQUAL(0, cv1.patch);
    CHECK_EQUAL(0.0, cv1.value);
    CHECK_EQUAL(0, cv1.unknown);

    // check dirichlet conditions
    std::string label1 = "Dirichlet";
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc0 = sut.container(
            label1);
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc1 =
            sut.dirichletSides();
    unsigned elems2 = 6;
    CHECK_EQUAL(elems2, bcc0.size());
    CHECK_EQUAL(elems2, bcc1.size());
    // check boundary conditions themselves
    std::string funcName0 = "0";
    int patches[4] =
    { 0, 0, 1, 1 };
    int indizes[4] =
    { 1, 3, 1, 2 };
    int unknown = 0;
    int unkcomp = 0;
    int domainDim = 2;
    for (int i = 0; i < 4; i++)
    {
        checkBoundaryCondition(bcc0[i], false, label1,
                gismo::condition_type::dirichlet, patches[i], indizes[i],
                unknown, unkcomp, domainDim, funcName0);
    }

    std::string funcName1 = "sin(pi*x)*sin(pi*y)";
    int patch4 = 0;
    int index4 = 2;
    int patch5 = 0;
    int index5 = 4;
    checkBoundaryCondition(bcc0[4], false, label1,
            gismo::condition_type::dirichlet, patch4, index4, unknown, unkcomp,
            domainDim, funcName1);
    checkBoundaryCondition(bcc0[5], false, label1,
            gismo::condition_type::dirichlet, patch5, index5, unknown, unkcomp,
            domainDim, funcName1);

    // check neumann conditions
    std::string label2 = "Neumann";
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc2 = sut.container(
            label2);
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc3 = sut.neumannSides();
    unsigned elems3 = 2;
    CHECK_EQUAL(elems3, bcc2.size());
    CHECK_EQUAL(elems3, bcc3.size());
    int patch6 = 1;
    int index6 = 3;
    int patch7 = 1;
    int index7 = 4;
    checkBoundaryCondition(bcc2[0], false, label2,
            gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
            domainDim, funcName0);
    checkBoundaryCondition(bcc3[0], false, label2,
            gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
            domainDim, funcName0);
    checkBoundaryCondition(bcc2[1], false, label2,
            gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
            domainDim, funcName0);
    checkBoundaryCondition(bcc3[1], false, label2,
            gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
            domainDim, funcName0);

    // check robin conditions
    std::string label3 = "Robin";
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc4 = sut.container(
            label3);
    gismo::gsBoundaryConditions<real_t>::bcContainer bcc5 = sut.robinSides();
    unsigned elems4 = 0;
    CHECK_EQUAL(elems4, bcc4.size());
    CHECK_EQUAL(elems4, bcc5.size());
    // check bctype_iterator
    typedef typename gismo::gsBoundaryConditions<real_t>::const_bciterator bctype_it;
    int c = 0;
    for (bctype_it it = sut.beginAll(); it != sut.endAll(); ++it)
    {
        c++;
    }
    CHECK_EQUAL(3, c);
}

SUITE(gsBoundaryConditions_test)
{
    TEST(gsBoundaryConditions_test_condition_type)
    {
        gismo::condition_type::type myType = gismo::condition_type::neumann;
        CHECK_EQUAL(gismo::condition_type::neumann, myType);
        CHECK_EQUAL(1, myType);
    }

    TEST(gsBoundaryConditions_test_function_expr)
    {
        int dim1 = 1;
        std::string funcName1 = "tan(x)";
        gsFunctionExpr<real_t> func1 = gsFunctionExpr<real_t>(funcName1, dim1);
        int domainDim1 = func1.domainDim();
        CHECK_EQUAL(dim1, domainDim1);
        std::string expectedName1 = getFunctionExprExpectedString(funcName1);
        std::string actualName1 = getFunctionExprActualString(func1);
        CHECK_EQUAL(expectedName1, actualName1);
        int dim2 = 2;
        std::string funcName2 = "sin(x)*sin(y)";
        gsFunctionExpr<real_t> func2 = gsFunctionExpr<real_t>(funcName2, dim2);
        int domainDim2 = func2.domainDim();
        CHECK_EQUAL(dim2, domainDim2);
        std::string expectedName2 = getFunctionExprExpectedString(funcName2);
        std::string actualName2 = getFunctionExprActualString(func2);
        CHECK_EQUAL(expectedName2, actualName2);
    }

    TEST(gsBoundaryConditions_test_box_side)
    {
        int index1 = 1;
        gismo::boxSide boxSide1 = gismo::boxSide(index1);
        CHECK_EQUAL(index1, boxSide1.m_index);
        std::string expect1 = getBoxSideExpectedString("west", index1);
        std::string actual1 = getBoxSideActualString(boxSide1);
        CHECK_EQUAL(expect1, actual1);
        int index2 = 7;
        gismo::boxSide boxSide2 = gismo::boxSide(index2);
        CHECK_EQUAL(index2, boxSide2.m_index);
        std::string expect2 = getBoxSideExpectedString("side", index2);
        std::string actual2 = getBoxSideActualString(boxSide2);
        CHECK_EQUAL(expect2, actual2);
    }

    TEST(gsBoundaryConditions_test_boundary_condition)
    {
        int dim1 = 1;
        std::string funcName1 = "tan(x)";
        int index1 = 1;
        int index2 = 2;
        gismo::boxSide boxSide1 = gismo::boxSide(index1);
        gismo::boundary_condition<real_t>::function_ptr funcPtr1 =
                gismo::memory::make_shared(
                        new gsFunctionExpr<real_t>(funcName1, dim1));
        std::string label1 = "Dirichlet";
        bool parametric1 = true;
        int unknown1 = 1;
        int unkcomp1 = 2;
        gismo::boundary_condition<real_t> bound = gismo::boundary_condition<real_t>(
                index2, boxSide1, funcPtr1, label1, unknown1, unkcomp1,
                parametric1);
        CHECK_EQUAL(parametric1, bound.m_parametric);
        CHECK_EQUAL(label1, bound.m_label);
        CHECK_EQUAL(gismo::condition_type::dirichlet, bound.m_type);
        CHECK_EQUAL(index2, bound.ps.patch);
        CHECK_EQUAL(index2, bound.patch());
        CHECK_EQUAL(index1, bound.ps.m_index);
        CHECK_EQUAL(funcPtr1, bound.m_function);
        CHECK_EQUAL(unknown1, bound.m_unknown);
        CHECK_EQUAL(unkcomp1, bound.m_unkcomp);
    }

    TEST(gsBoundaryConditions_test_box_corner)
    {
        int index1 = 3;
        gismo::boxCorner c1 = gismo::boxCorner(index1);
        CHECK_EQUAL(index1, c1.m_index);
    }

    TEST(gsBoundaryConditions_test_corner_value)
    {
        int index1 = 3;
        gismo::boxCorner c1 = gismo::boxCorner(index1);
        int p1 = 2;
        real_t v1 = 3.0;
        int u1 = 4;
        gismo::corner_value<real_t> cornerVal1 = gismo::corner_value<real_t>(p1, c1,
                v1, u1);
        CHECK_EQUAL(c1, cornerVal1.corner);
        CHECK_EQUAL(index1, cornerVal1.corner.m_index);
        CHECK_EQUAL(p1, cornerVal1.patch);
        CHECK_EQUAL(v1, cornerVal1.value);
        CHECK_EQUAL(u1, cornerVal1.unknown);
    }

    /***
     * test loading from bc.xml
     */
    TEST(gsBoundaryConditions_load_from_bc_xml)
    {
        std::string path = GISMO_DATA_DIR;
        path += "gsBoundaryConditions/bc.xml";
        gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path);
        checkGsBoundaryCondition(sut);
    }

    /***
     * test loading from bc.xml and
     * saving to bc2.xml
     * and ensure that bc.xml and bc2.xml have
     * the same content
     */
    TEST(gsBoundaryConditions_save_load_bc_xml)
    {
        std::string path1 = GISMO_DATA_DIR;
        path1 += "/gsBoundaryConditions/bc.xml";
        std::string path2 = gismo::util::getTempPath();
        path2 += "/bc2.xml";

        gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path1);
        gsBoundaryConditions_saveToFile(path2, sut);
        gsBoundaryConditions<real_t> sut2 = gsBoundaryConditions_loadFromFile(path2);
        checkGsBoundaryCondition(sut2);
    }

}
<|endoftext|>


<commit_before>/**
 * PUC-Rio 2015.2
 * INF1339 - Computação Gráfica Tridimensional
 * Professor: Waldemar Celes
 * Gabriel de Quadros Ligneul 1212560
 * Trabalho - Projeto de Grafo de Cena
 */

#include <algorithm>
#include <cmath>

#include <GL/gl.h>
#include <GL/glut.h>

#include "Manipulator.h"
#include "invertMatrix.h"
#include "vec3.h"

Manipulator::Manipulator() :
    reference_{0, 0, 0},
    matrix_{1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1},
    inv_{1, 0, 0, 0,
         0, 1, 0, 0,
         0, 0, 1, 0,
         0, 0, 0, 1},
    operation_{Operation::kNone},
    x_{0},
    y_{0},
    v_{0, 0, 0},
    invertX_{false},
    invertY_{false} {
}

void Manipulator::Apply() {
    glTranslatef(reference_[0], reference_[1], reference_[2]);
    glMultMatrixf(matrix_.data());
    glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
}

void Manipulator::ApplyInv() {
    glTranslatef(reference_[0], reference_[1], reference_[2]);
    glMultMatrixf(inv_.data());
    glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
}

void Manipulator::SetReferencePoint(float x, float y, float z) {
    reference_ = {x, y, z};
}

void Manipulator::GlutMouse(int button, int state, int x, int y) {
    SetOperation<GLUT_LEFT_BUTTON, Operation::kRotation>(button, state, x, y);
    SetOperation<GLUT_RIGHT_BUTTON, Operation::kZoom>(button, state, x, y);
}

void Manipulator::SetInvertAxis(bool invertX, bool invertY) {
    invertX_ = invertX;
    invertY_ = invertY;
}

void Manipulator::GlutMotion(int x, int y) {
    if (operation_ == Operation::kNone)
        return;

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    if (operation_ == Operation::kRotation) {
        vec3::Vf v = computeSphereCoordinates(x, y);
        vec3::Vf w = vec3::cross(v_, v);
        float theta = asin(vec3::norm(w)) * 180 / M_PI;
        glRotatef(theta, w[0], w[1], w[2]);
        v_ = v;
    } else if (operation_ == Operation::kZoom) {
        int vp[4];
        glGetIntegerv(GL_VIEWPORT, vp);
        float dy = y - y_;
        float f = dy / vp[3];
        float scale = 1 + kZoomScale * f;
        glScalef(scale, scale, scale);
    }

    glMultMatrixf(matrix_.data());
    glGetFloatv(GL_MODELVIEW_MATRIX, matrix_.data());
    gluInvertMatrix(matrix_.data(), inv_.data());
    glPopMatrix();

    x_ = x;
    y_ = y;
}

template<int k_button, Manipulator::Operation k_operation>
void Manipulator::SetOperation(int button, int state, int x, int y) {
    if (button == k_button) {
        if (state == GLUT_DOWN && operation_ == Operation::kNone) {
            operation_ = k_operation;
            x_ = x;
            y_ = y;
            v_ = computeSphereCoordinates(x, y);
        } else if (state == GLUT_UP && operation_ == k_operation) {
            operation_ = Operation::kNone;
        }
    }
}

std::array<float, 3> Manipulator::computeSphereCoordinates(int x, int y) {
    int vp[4];
    glGetIntegerv(GL_VIEWPORT, vp);
    const float w = vp[2];
    const float h = vp[3];

    if (invertX_) x = w - x;
    if (invertY_) y = h - y;

    const float radius = std::min(w / 2.0f, h / 2.0f);
    std::array<float, 3> v = {
        (x - w / 2.0f) / radius,
        (h - y - h / 2.0f) / radius,
    };

    const float dist = hypot(v[0], v[1]);
    if (dist > 1.0f) {
        v[0] /= dist;
        v[1] /= dist;
        v[2] = 0;
    } else {
        v[2] = sqrt(1 - v[0] * v[0] - v[1] * v[1]);
    }

    return v;
}

<commit_msg>Fixed the accumulation of the manipulator\'s inverse<commit_after>/**
 * PUC-Rio 2015.2
 * INF1339 - Computação Gráfica Tridimensional
 * Professor: Waldemar Celes
 * Gabriel de Quadros Ligneul 1212560
 * Trabalho - Projeto de Grafo de Cena
 */

#include <algorithm>
#include <cmath>

#include <GL/gl.h>
#include <GL/glut.h>

#include "Manipulator.h"
#include "invertMatrix.h"
#include "vec3.h"

Manipulator::Manipulator() :
    reference_{0, 0, 0},
    matrix_{1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1},
    inv_{1, 0, 0, 0,
         0, 1, 0, 0,
         0, 0, 1, 0,
         0, 0, 0, 1},
    operation_{Operation::kNone},
    x_{0},
    y_{0},
    v_{0, 0, 0},
    invertX_{false},
    invertY_{false} {
}

void Manipulator::Apply() {
    glTranslatef(reference_[0], reference_[1], reference_[2]);
    glMultMatrixf(matrix_.data());
    glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
}

void Manipulator::ApplyInv() {
    glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
    glMultMatrixf(inv_.data());
    glTranslatef(reference_[0], reference_[1], reference_[2]);
}

void Manipulator::SetReferencePoint(float x, float y, float z) {
    reference_ = {x, y, z};
}

void Manipulator::GlutMouse(int button, int state, int x, int y) {
    SetOperation<GLUT_LEFT_BUTTON, Operation::kRotation>(button, state, x, y);
    SetOperation<GLUT_RIGHT_BUTTON, Operation::kZoom>(button, state, x, y);
}

void Manipulator::SetInvertAxis(bool invertX, bool invertY) {
    invertX_ = invertX;
    invertY_ = invertY;
}

void Manipulator::GlutMotion(int x, int y) {
    if (operation_ == Operation::kNone)
        return;

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    if (operation_ == Operation::kRotation) {
        vec3::Vf v = computeSphereCoordinates(x, y);
        vec3::Vf w = vec3::cross(v_, v);
        float theta = asin(vec3::norm(w)) * 180 / M_PI;
        glRotatef(theta, w[0], w[1], w[2]);
        v_ = v;
    } else if (operation_ == Operation::kZoom) {
        int vp[4];
        glGetIntegerv(GL_VIEWPORT, vp);
        float dy = y - y_;
        float f = dy / vp[3];
        float scale = 1 + kZoomScale * f;
        glScalef(scale, scale, scale);
    }

    glMultMatrixf(matrix_.data());
    glGetFloatv(GL_MODELVIEW_MATRIX, matrix_.data());
    gluInvertMatrix(matrix_.data(), inv_.data());
    glPopMatrix();

    x_ = x;
    y_ = y;
}

template<int k_button, Manipulator::Operation k_operation>
void Manipulator::SetOperation(int button, int state, int x, int y) {
    if (button == k_button) {
        if (state == GLUT_DOWN && operation_ == Operation::kNone) {
            operation_ = k_operation;
            x_ = x;
            y_ = y;
            v_ = computeSphereCoordinates(x, y);
        } else if (state == GLUT_UP && operation_ == k_operation) {
            operation_ = Operation::kNone;
        }
    }
}

std::array<float, 3> Manipulator::computeSphereCoordinates(int x, int y) {
    int vp[4];
    glGetIntegerv(GL_VIEWPORT, vp);
    const float w = vp[2];
    const float h = vp[3];

    if (invertX_) x = w - x;
    if (invertY_) y = h - y;

    const float radius = std::min(w / 2.0f, h / 2.0f);
    std::array<float, 3> v = {
        (x - w / 2.0f) / radius,
        (h - y - h / 2.0f) / radius,
    };

    const float dist = hypot(v[0], v[1]);
    if (dist > 1.0f) {
        v[0] /= dist;
        v[1] /= dist;
        v[2] = 0;
    } else {
        v[2] = sqrt(1 - v[0] * v[0] - v[1] * v[1]);
    }

    return v;
}

<|endoftext|>


<commit_before>#include <cmath>
#include <cstdio>

int main() {
    float h, s;
    scanf("%f", &h);
    scanf("%f", &s);
    printf("%.3f\n", h * s / 12.0);
}
<commit_msg>Format code<commit_after>#include <cmath>
#include <cstdio>

int main() {
    float h, s;

    scanf("%f", &h);
    scanf("%f", &s);

    printf("%.3f\n", h * s / 12.0);
}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    int integer, number_of_digits, multiplier, current_digit;
    std::map<int, std::string> int_roman_base;
    std::string roman;
    std::vector<int> splitted_integer;

    int_roman_base[0] = "";
    int_roman_base[1] = "I";
    int_roman_base[2] = "II";
    int_roman_base[3] = "III";
    int_roman_base[4] = "IV";
    int_roman_base[5] = "V";
    int_roman_base[6] = "VI";
    int_roman_base[7] = "VII";
    int_roman_base[8] = "VIII";
    int_roman_base[9] = "IX";
    int_roman_base[10] = "X";
    int_roman_base[20] = "XX";
    int_roman_base[30] = "XXX";
    int_roman_base[40] = "XL";
    int_roman_base[50] = "L";
    int_roman_base[60] = "LX";
    int_roman_base[70] = "LXX";
    int_roman_base[80] = "LXXX";
    int_roman_base[90] = "XC";
    int_roman_base[100] = "C";
    int_roman_base[200] = "CC";
    int_roman_base[300] = "CCC";
    int_roman_base[400] = "CD";
    int_roman_base[500] = "D";
    int_roman_base[600] = "DC";
    int_roman_base[700] = "DCC";
    int_roman_base[800] = "DCCC";
    int_roman_base[900] = "CM";
    int_roman_base[1000] = "M";

    while (std::cin >> integer) {
        multiplier = 1;
        roman = "";

        while (integer > 0) {
            current_digit = integer % 10;
            integer /= 10;

            roman = int_roman_base[current_digit * multiplier] + roman;
            multiplier *= 10;
        }

        std::cout << roman << std::endl;
    }

    return 0;
}
<commit_msg>Remove unused code<commit_after>#include <cmath>
#include <iostream>
#include <map>
#include <string>

int main() {
    int integer, multiplier, current_digit;
    std::map<int, std::string> int_roman_base;
    std::string roman;

    int_roman_base[0] = "";
    int_roman_base[1] = "I";
    int_roman_base[2] = "II";
    int_roman_base[3] = "III";
    int_roman_base[4] = "IV";
    int_roman_base[5] = "V";
    int_roman_base[6] = "VI";
    int_roman_base[7] = "VII";
    int_roman_base[8] = "VIII";
    int_roman_base[9] = "IX";
    int_roman_base[10] = "X";
    int_roman_base[20] = "XX";
    int_roman_base[30] = "XXX";
    int_roman_base[40] = "XL";
    int_roman_base[50] = "L";
    int_roman_base[60] = "LX";
    int_roman_base[70] = "LXX";
    int_roman_base[80] = "LXXX";
    int_roman_base[90] = "XC";
    int_roman_base[100] = "C";
    int_roman_base[200] = "CC";
    int_roman_base[300] = "CCC";
    int_roman_base[400] = "CD";
    int_roman_base[500] = "D";
    int_roman_base[600] = "DC";
    int_roman_base[700] = "DCC";
    int_roman_base[800] = "DCCC";
    int_roman_base[900] = "CM";
    int_roman_base[1000] = "M";

    while (std::cin >> integer) {
        multiplier = 1;
        roman = "";

        while (integer > 0) {
            current_digit = integer % 10;
            integer /= 10;

            roman = int_roman_base[current_digit * multiplier] + roman;
            multiplier *= 10;
        }

        std::cout << roman << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "bench_framework.hpp"
#include "compare_images.hpp"

class test : public benchmark::test_case
{
    std::shared_ptr<image_rgba8> im_;
public:
    test(mapnik::parameters const& params)
     : test_case(params) {
        std::string filename("./benchmark/data/multicolor.png");
        std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename,"png"));
        if (!reader.get())
        {
            throw mapnik::image_reader_exception("Failed to load: " + filename);
        }
        im_ = std::make_shared<image_rgba8>(reader->width(),reader->height());
        reader->read(0,0,*im_);
    }
    bool validate() const
    {
        std::string expected("./benchmark/data/multicolor-hextree-expected.png");
        std::string actual("./benchmark/data/multicolor-hextree-actual.png");
        mapnik::save_to_file(*im_,actual, "png8:m=h:z=1");
        return benchmark::compare_images(actual,expected);
    }
    bool operator()() const
    {
        std::string out;
        for (std::size_t i=0;i<iterations_;++i) {
            out.clear();
            out = mapnik::save_to_string(*im_,"png8:m=h:z=1");
        }
        return true;
    }
};

BENCHMARK(test,"encoding multicolor png")
<commit_msg>fix - add missing namespace qualifier.<commit_after>#include "bench_framework.hpp"
#include "compare_images.hpp"

class test : public benchmark::test_case
{
    std::shared_ptr<mapnik::image_rgba8> im_;
public:
    test(mapnik::parameters const& params)
     : test_case(params) {
        std::string filename("./benchmark/data/multicolor.png");
        std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename,"png"));
        if (!reader.get())
        {
            throw mapnik::image_reader_exception("Failed to load: " + filename);
        }
        im_ = std::make_shared<mapnik::image_rgba8>(reader->width(),reader->height());
        reader->read(0,0,*im_);
    }
    bool validate() const
    {
        std::string expected("./benchmark/data/multicolor-hextree-expected.png");
        std::string actual("./benchmark/data/multicolor-hextree-actual.png");
        mapnik::save_to_file(*im_,actual, "png8:m=h:z=1");
        return benchmark::compare_images(actual,expected);
    }
    bool operator()() const
    {
        std::string out;
        for (std::size_t i=0;i<iterations_;++i) {
            out.clear();
            out = mapnik::save_to_string(*im_,"png8:m=h:z=1");
        }
        return true;
    }
};

BENCHMARK(test,"encoding multicolor png")
<|endoftext|>


<commit_before>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>

#include <dariadb.h>
#include <compression.h>
#include <compression/delta.h>
#include <compression/xor.h>
#include <compression/flag.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>

int main(int argc, char *argv[]) {
	(void)argc;
	(void)argv;

    auto test_buffer_size=1024*1024*100;
    uint8_t *buffer=new uint8_t[test_buffer_size];
    dariadb::utils::Range rng{buffer,buffer+test_buffer_size};
    //delta compression
    std::fill(buffer,buffer+test_buffer_size,0);

    {
        const size_t count=1000000;

        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);

        dariadb::compression::DeltaCompressor dc(bw);

        std::vector<dariadb::Time> deltas{50,255,1024,2050};
        dariadb::Time t=0;
        auto start=clock();
        for(size_t i=0;i<count;i++){
            dc.append(t);
            t+=deltas[i%deltas.size()];
            if (t > std::numeric_limits<dariadb::Time>::max()){
                t=0;
            }
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"delta compressor : "<<elapsed<<std::endl;

        auto w=dc.used_space();
        auto sz=sizeof(dariadb::Time)*count;
        std::cout<<"used space:  "
               <<(w*100.0)/(sz)<<"%"
               <<std::endl;
    }
    {
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
        dariadb::compression::DeltaDeCompressor dc(bw,0);

        auto start=clock();
        for(size_t i=1;i<1000000;i++){
            dc.read();
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"delta decompressor : "<<elapsed<<std::endl;
    }
    //xor compression
    std::fill(buffer,buffer+test_buffer_size,0);
    {
        const size_t count=1000000;
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
        dariadb::compression::XorCompressor dc(bw);

        dariadb::Value t=3.14;
        auto start=clock();
        for(size_t i=0;i<count;i++){
            dc.append(t);
            t*=1.5;
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"\nxor compressor : "<<elapsed<<std::endl;
        auto w=dc.used_space();
        auto sz=sizeof(dariadb::Time)*count;
        std::cout<<"used space: "
               <<(w*100.0)/(sz)<<"%"
               <<std::endl;
    }
    {
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
        dariadb::compression::XorDeCompressor dc(bw,0);

        auto start=clock();
        for(size_t i=1;i<1000000;i++){
            dc.read();
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"xor decompressor : "<<elapsed<<std::endl;
    }

    {
        const size_t count = 1000000;
        auto start = clock();
        for (size_t i = 0; i<count; i++) {
            dariadb::compression::inner::flat_double_to_int(3.14);
        }
        auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "\nflat_double_to_int: " << elapsed << std::endl;

        start = clock();
        for (size_t i = 0; i<count; i++) {
            dariadb::compression::inner::flat_int_to_double(0xfff);
        }
        elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "flat_int_to_double: " << elapsed << std::endl;
    }

    {
        const size_t count=1000000;
        uint8_t* buf_begin=new uint8_t[test_buffer_size];

        std::fill(buf_begin, buf_begin+test_buffer_size, 0);
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);

        dariadb::compression::CopmressedWriter cwr{bw};
        auto start = clock();
        for (size_t i = 0; i < count; i++) {
            auto m = dariadb::Meas::empty();
            m.time = static_cast<dariadb::Time>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count());
			m.flag = dariadb::Flag(i);
			m.value = dariadb::Value(i);
            cwr.append(m);
        }

        auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "\ncompress writer : " << elapsed << std::endl;
        auto w=cwr.used_space();
        auto sz=sizeof(dariadb::Meas)*count;
        std::cout<<"used space: "
               <<(w*100.0)/(sz)<<"%"
               <<std::endl;

        auto m = dariadb::Meas::empty();
        bw->reset_pos();
        dariadb::compression::CopmressedReader crr{bw,m};

        start = clock();
        for (int i = 1; i < 1000000; i++) {
            crr.read();
        }
        elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "compress reader : " << elapsed << std::endl;

        delete[] buf_begin;
    }
    delete[]buffer;
}
<commit_msg>compression bench refact.<commit_after>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>

#include <dariadb.h>
#include <compression.h>
#include <compression/delta.h>
#include <compression/xor.h>
#include <compression/flag.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>

int main(int argc, char *argv[]) {
	(void)argc;
	(void)argv;

    auto test_buffer_size=1024*1024*100;
    uint8_t *buffer=new uint8_t[test_buffer_size];
    dariadb::utils::Range rng{buffer,buffer+test_buffer_size};
    //delta compression
    std::fill(buffer,buffer+test_buffer_size,0);

    {
        const size_t count=1000000;

        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);

        dariadb::compression::DeltaCompressor dc(bw);

        std::vector<dariadb::Time> deltas{50,255,1024,2050};
        dariadb::Time t=0;
        auto start=clock();
        for(size_t i=0;i<count;i++){
            dc.append(t);
            t+=deltas[i%deltas.size()];
            if (t > std::numeric_limits<dariadb::Time>::max()){
                t=0;
            }
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"delta compressor : "<<elapsed<<std::endl;

        auto w=dc.used_space();
        auto sz=sizeof(dariadb::Time)*count;
        std::cout<<"used space:  "
               <<(w*100.0)/(sz)<<"%"
               <<std::endl;
    }
    {
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
        dariadb::compression::DeltaDeCompressor dc(bw,0);

        auto start=clock();
        for(size_t i=1;i<1000000;i++){
            dc.read();
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"delta decompressor : "<<elapsed<<std::endl;
    }
    //xor compression
    std::fill(buffer,buffer+test_buffer_size,0);
    {
        const size_t count=1000000;
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
        dariadb::compression::XorCompressor dc(bw);

        dariadb::Value t=3.14;
        auto start=clock();
        for(size_t i=0;i<count;i++){
            dc.append(t);
            t*=1.5;
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"\nxor compressor : "<<elapsed<<std::endl;
        auto w=dc.used_space();
        auto sz=sizeof(dariadb::Time)*count;
        std::cout<<"used space: "
               <<(w*100.0)/(sz)<<"%"
               <<std::endl;
    }
    {
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
        dariadb::compression::XorDeCompressor dc(bw,0);

        auto start=clock();
        for(size_t i=1;i<1000000;i++){
            dc.read();
        }
        auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
        std::cout<<"xor decompressor : "<<elapsed<<std::endl;
    }

    {
        const size_t count = 1000000;
        auto start = clock();
        for (size_t i = 0; i<count; i++) {
            dariadb::compression::inner::flat_double_to_int(3.14);
        }
        auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "\nflat_double_to_int: " << elapsed << std::endl;

        start = clock();
        for (size_t i = 0; i<count; i++) {
            dariadb::compression::inner::flat_int_to_double(0xfff);
        }
        elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "flat_int_to_double: " << elapsed << std::endl;
    }

    {
        const size_t count=1000000;
        uint8_t* buf_begin=new uint8_t[test_buffer_size];

        std::fill(buf_begin, buf_begin+test_buffer_size, 0);
        auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);

        dariadb::compression::CopmressedWriter cwr{bw};
        auto start = clock();
        for (size_t i = 0; i < count; i++) {
            auto m = dariadb::Meas::empty();
            m.time = static_cast<dariadb::Time>(dariadb::timeutil::current_time());
			m.flag = dariadb::Flag(i);
			m.value = dariadb::Value(i);
            cwr.append(m);
        }

        auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "\ncompress writer : " << elapsed << std::endl;
        auto w=cwr.used_space();
        auto sz=sizeof(dariadb::Meas)*count;
        std::cout<<"used space: "
               <<(w*100.0)/(sz)<<"%"
               <<std::endl;

        auto m = dariadb::Meas::empty();
        bw->reset_pos();
        dariadb::compression::CopmressedReader crr{bw,m};

        start = clock();
        for (int i = 1; i < 1000000; i++) {
            crr.read();
        }
        elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
        std::cout << "compress reader : " << elapsed << std::endl;

        delete[] buf_begin;
    }
    delete[]buffer;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_cache.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/placement_finder.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/font_set.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/text_path.hpp>

// agg
#define AGG_RENDERING_BUFFER row_ptr_cache<int8u>
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_path_storage.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_image_accessors.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_conv_contour.h"
#include "agg_conv_clip_polyline.h"
#include "agg_vcgen_stroke.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_smooth_poly1.h"
#include "agg_conv_marker.h"
#include "agg_vcgen_markers_term.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_rasterizer_outline.h"
#include "agg_renderer_outline_image.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_renderer_scanline.h"
#include "agg_pattern_filters_rgba.h"
#include "agg_renderer_outline_image.h"
#include "agg_vpgen_clip_polyline.h"
#include "agg_arrowhead.h"

// boost
#include <boost/utility.hpp>

// stl
#ifdef MAPNIK_DEBUG
#include <iostream>
#endif

#include <cmath>

namespace mapnik
{
class pattern_source : private boost::noncopyable
{
public:
    pattern_source(image_data_32 const& pattern)
        : pattern_(pattern) {}

    unsigned int width() const
    {
        return pattern_.width();
    }
    unsigned int height() const
    {
        return pattern_.height();
    }
    agg::rgba8 pixel(int x, int y) const
    {
        unsigned c = pattern_(x,y);
        return agg::rgba8(c & 0xff,
                          (c >> 8) & 0xff,
                          (c >> 16) & 0xff,
                          (c >> 24) & 0xff);
    }
private:
    image_data_32 const& pattern_;
};

template <typename T>
agg_renderer<T>::agg_renderer(Map const& m, T & pixmap, double scale_factor, unsigned offset_x, unsigned offset_y)
    : feature_style_processor<agg_renderer>(m, scale_factor),
      pixmap_(pixmap),
      width_(pixmap_.width()),
      height_(pixmap_.height()),
      scale_factor_(scale_factor),
      t_(m.width(),m.height(),m.get_current_extent(),offset_x,offset_y),
      font_engine_(),
      font_manager_(font_engine_),
      detector_(box2d<double>(-m.buffer_size(), -m.buffer_size(), m.width() + m.buffer_size() ,m.height() + m.buffer_size())),
      ras_ptr(new rasterizer)
{
    boost::optional<color> const& bg = m.background();
    if (bg) pixmap_.set_background(*bg);

    boost::optional<std::string> const& image_filename = m.background_image();
    if (image_filename)
    {
        boost::optional<mapnik::image_ptr> bg_image = mapnik::image_cache::instance()->find(*image_filename,true);
        if (bg_image)
        {
            int w = (*bg_image)->width();
            int h = (*bg_image)->height();
            if ( w > 0 && h > 0)
            {
                // repeat background-image in both x,y
                unsigned x_steps = unsigned(std::ceil(width_/double(w)));
                unsigned y_steps = unsigned(std::ceil(height_/double(h)));
                for (unsigned x=0;x<x_steps;++x)
                {
                    for (unsigned y=0;y<y_steps;++y)
                    {
                        pixmap_.set_rectangle_alpha2(*(*bg_image), x*w, y*h, 1.0f);
                    }
                }
            }
        }
    }
#ifdef MAPNIK_DEBUG
    std::clog << "scale=" << m.scale() << "\n";
#endif
}

template <typename T>
agg_renderer<T>::~agg_renderer() {}

template <typename T>
void agg_renderer<T>::start_map_processing(Map const& map)
{
#ifdef MAPNIK_DEBUG
    std::clog << "start map processing bbox="
              << map.get_current_extent() << "\n";
#endif
    ras_ptr->clip_box(0,0,width_,height_);
}

template <typename T>
void agg_renderer<T>::end_map_processing(Map const& )
{
#ifdef MAPNIK_DEBUG
    std::clog << "end map processing\n";
#endif
}

template <typename T>
void agg_renderer<T>::start_layer_processing(layer const& lay)
{
#ifdef MAPNIK_DEBUG
    std::clog << "start layer processing : " << lay.name()  << "\n";
    std::clog << "datasource = " << lay.datasource().get() << "\n";
#endif
    if (lay.clear_label_cache())
    {
        detector_.clear();
    }
}

template <typename T>
void agg_renderer<T>::end_layer_processing(layer const&)
{
#ifdef MAPNIK_DEBUG
    std::clog << "end layer processing\n";
#endif
}

template class agg_renderer<image_32>;
}
<commit_msg>+ fix comment<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_cache.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/placement_finder.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/font_set.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/text_path.hpp>

// agg
#define AGG_RENDERING_BUFFER row_ptr_cache<int8u>
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_path_storage.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_image_accessors.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_conv_contour.h"
#include "agg_conv_clip_polyline.h"
#include "agg_vcgen_stroke.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_smooth_poly1.h"
#include "agg_conv_marker.h"
#include "agg_vcgen_markers_term.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_rasterizer_outline.h"
#include "agg_renderer_outline_image.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_renderer_scanline.h"
#include "agg_pattern_filters_rgba.h"
#include "agg_renderer_outline_image.h"
#include "agg_vpgen_clip_polyline.h"
#include "agg_arrowhead.h"

// boost
#include <boost/utility.hpp>

// stl
#ifdef MAPNIK_DEBUG
#include <iostream>
#endif

#include <cmath>

namespace mapnik
{
class pattern_source : private boost::noncopyable
{
public:
    pattern_source(image_data_32 const& pattern)
        : pattern_(pattern) {}

    unsigned int width() const
    {
        return pattern_.width();
    }
    unsigned int height() const
    {
        return pattern_.height();
    }
    agg::rgba8 pixel(int x, int y) const
    {
        unsigned c = pattern_(x,y);
        return agg::rgba8(c & 0xff,
                          (c >> 8) & 0xff,
                          (c >> 16) & 0xff,
                          (c >> 24) & 0xff);
    }
private:
    image_data_32 const& pattern_;
};

template <typename T>
agg_renderer<T>::agg_renderer(Map const& m, T & pixmap, double scale_factor, unsigned offset_x, unsigned offset_y)
    : feature_style_processor<agg_renderer>(m, scale_factor),
      pixmap_(pixmap),
      width_(pixmap_.width()),
      height_(pixmap_.height()),
      scale_factor_(scale_factor),
      t_(m.width(),m.height(),m.get_current_extent(),offset_x,offset_y),
      font_engine_(),
      font_manager_(font_engine_),
      detector_(box2d<double>(-m.buffer_size(), -m.buffer_size(), m.width() + m.buffer_size() ,m.height() + m.buffer_size())),
      ras_ptr(new rasterizer)
{
    boost::optional<color> const& bg = m.background();
    if (bg) pixmap_.set_background(*bg);

    boost::optional<std::string> const& image_filename = m.background_image();
    if (image_filename)
    {
        boost::optional<mapnik::image_ptr> bg_image = mapnik::image_cache::instance()->find(*image_filename,true);
        if (bg_image)
        {
            int w = (*bg_image)->width();
            int h = (*bg_image)->height();
            if ( w > 0 && h > 0)
            {
                // repeat background-image both vertically and horizontally
                unsigned x_steps = unsigned(std::ceil(width_/double(w)));
                unsigned y_steps = unsigned(std::ceil(height_/double(h)));
                for (unsigned x=0;x<x_steps;++x)
                {
                    for (unsigned y=0;y<y_steps;++y)
                    {
                        pixmap_.set_rectangle_alpha2(*(*bg_image), x*w, y*h, 1.0f);
                    }
                }
            }
        }
    }
#ifdef MAPNIK_DEBUG
    std::clog << "scale=" << m.scale() << "\n";
#endif
}

template <typename T>
agg_renderer<T>::~agg_renderer() {}

template <typename T>
void agg_renderer<T>::start_map_processing(Map const& map)
{
#ifdef MAPNIK_DEBUG
    std::clog << "start map processing bbox="
              << map.get_current_extent() << "\n";
#endif
    ras_ptr->clip_box(0,0,width_,height_);
}

template <typename T>
void agg_renderer<T>::end_map_processing(Map const& )
{
#ifdef MAPNIK_DEBUG
    std::clog << "end map processing\n";
#endif
}

template <typename T>
void agg_renderer<T>::start_layer_processing(layer const& lay)
{
#ifdef MAPNIK_DEBUG
    std::clog << "start layer processing : " << lay.name()  << "\n";
    std::clog << "datasource = " << lay.datasource().get() << "\n";
#endif
    if (lay.clear_label_cache())
    {
        detector_.clear();
    }
}

template <typename T>
void agg_renderer<T>::end_layer_processing(layer const&)
{
#ifdef MAPNIK_DEBUG
    std::clog << "end layer processing\n";
#endif
}

template class agg_renderer<image_32>;
}
<|endoftext|>