<commit_before>#include "test_slitherlink_field.h"
#include "test.h"

#include <cassert>
#include <vector>

#include "../slitherlink/sl_field.h"
#include "../slitherlink/sl_database.h"

namespace
{
// Place clues and check edges
void DoAddClueTest(penciloid::Y height, penciloid::X width, std::vector<const char*> test_target, penciloid::slitherlink::Database *db)
{
	using namespace penciloid;
	using namespace penciloid::slitherlink;

	Field field(height, width);
	field.SetDatabase(db);

	for (Y y = 0; y < height; ++y) {
		for (X x = 0; x < width; ++x) {
			if ('0' <= test_target[y * 2 + 1][x * 2 + 1] && test_target[y * 2 + 1][x * 2 + 1] <= '3') {
				field.AddClue(Position(y, x), test_target[y * 2 + 1][x * 2 + 1] - '0');
			}
		}
	}

	for (Y y = 0; y <= 2 * height; ++y) {
		for (X x = 0; x <= 2 * width; ++x) {
			if (y % 2 != x % 2) {
				Field::EdgeState expected;
				if (test_target[y][x] == 'x') expected = Field::EDGE_BLANK;
				else if (test_target[y][x] == ' ') expected = Field::EDGE_UNDECIDED;
				else expected = Field::EDGE_LINE;

				if (field.GetEdge(Position(y, x)) != expected) {
					y = y;
				}
				assert(field.GetEdge(Position(y, x)) == expected);
			}
		}
	}
}
}

namespace penciloid
{
namespace test
{
void RunAllSlitherlinkFieldTest()
{
	SlitherlinkFieldAddClue();
	SlitherlinkFieldTheorem();
}
void SlitherlinkFieldAddClue()
{
	using namespace slitherlink;

	Database db;
	db.CreateDefault();

	DoAddClueTest(3, 3, {
		"+ + + +",
		"       ",
		"+ +x+ +",
		"  x0x  ",
		"+ +x+ +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+x+ + +",
		"x1     ",
		"+ + + +",
		"       ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+ +-+ +",
		" 2     ",
		"+ + + +",
		"|      ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+ + +",
		"|3     ",
		"+ + + +",
		"       ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+x+x+-+",
		"x0x2| |",
		"+x+-+x+",
		"x | x |",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+-+-+",
		"|2x1x |",
		"+x+x+ +",
		"| x    ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+-+-+",
		"|2x1x |",
		"+x+x+-+",
		"| x2| x",
		"+ +-+x+",
		"    x x",
		"+ +x+x+",
	}, &db);
}
void SlitherlinkFieldTheorem()
{
	using namespace slitherlink;

	Database db;
	db.CreateDefault();

	DoAddClueTest(3, 3, {
		"+ + + +",
		"  x    ",
		"+ + + +",
		"|3|3|  ",
		"+ + + +",
		"  x    ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 4, {
		"+ + +-+x+",
		"     3| x",
		"+ + + + +",
		"  |3     ",
		"+x+-+ + +",
		"  x      ",
		"+ + + + +",
	}, &db);
}
}
}
<commit_msg>Slitherlink: add a test case<commit_after>#include "test_slitherlink_field.h"
#include "test.h"

#include <cassert>
#include <vector>

#include "../slitherlink/sl_field.h"
#include "../slitherlink/sl_database.h"

namespace
{
// Place clues and check edges
void DoAddClueTest(penciloid::Y height, penciloid::X width, std::vector<const char*> test_target, penciloid::slitherlink::Database *db)
{
	using namespace penciloid;
	using namespace penciloid::slitherlink;

	Field field(height, width);
	field.SetDatabase(db);

	for (Y y = 0; y < height; ++y) {
		for (X x = 0; x < width; ++x) {
			if ('0' <= test_target[y * 2 + 1][x * 2 + 1] && test_target[y * 2 + 1][x * 2 + 1] <= '3') {
				field.AddClue(Position(y, x), test_target[y * 2 + 1][x * 2 + 1] - '0');
			}
		}
	}

	for (Y y = 0; y <= 2 * height; ++y) {
		for (X x = 0; x <= 2 * width; ++x) {
			if (y % 2 != x % 2) {
				Field::EdgeState expected;
				if (test_target[y][x] == 'x') expected = Field::EDGE_BLANK;
				else if (test_target[y][x] == ' ') expected = Field::EDGE_UNDECIDED;
				else expected = Field::EDGE_LINE;

				if (field.GetEdge(Position(y, x)) != expected) {
					y = y;
				}
				assert(field.GetEdge(Position(y, x)) == expected);
			}
		}
	}
}
}

namespace penciloid
{
namespace test
{
void RunAllSlitherlinkFieldTest()
{
	SlitherlinkFieldAddClue();
	SlitherlinkFieldTheorem();
}
void SlitherlinkFieldAddClue()
{
	using namespace slitherlink;

	Database db;
	db.CreateDefault();

	DoAddClueTest(3, 3, {
		"+ + + +",
		"       ",
		"+ +x+ +",
		"  x0x  ",
		"+ +x+ +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+x+ + +",
		"x1     ",
		"+ + + +",
		"       ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+ +-+ +",
		" 2     ",
		"+ + + +",
		"|      ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+ + +",
		"|3     ",
		"+ + + +",
		"       ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+x+x+-+",
		"x0x2| |",
		"+x+-+x+",
		"x | x |",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+-+-+",
		"|2x1x |",
		"+x+x+ +",
		"| x    ",
		"+ + + +",
		"       ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+-+-+",
		"|2x1x |",
		"+x+x+-+",
		"| x2| x",
		"+ +-+x+",
		"    x x",
		"+ +x+x+",
	}, &db);
}
void SlitherlinkFieldTheorem()
{
	using namespace slitherlink;

	Database db;
	db.CreateDefault();

	DoAddClueTest(3, 3, {
		"+ + + +",
		"  x    ",
		"+ + + +",
		"|3|3|  ",
		"+ + + +",
		"  x    ",
		"+ + + +",
	}, &db);
	DoAddClueTest(3, 4, {
		"+ + +-+x+",
		"     3| x",
		"+ + + + +",
		"  |3     ",
		"+x+-+ + +",
		"  x      ",
		"+ + + + +",
	}, &db);
	DoAddClueTest(3, 3, {
		"+-+-+-+",
		"| x x |",
		"+x+-+x+",
		"|3|3| |",
		"+-+x+ +",
		"x1x    ",
		"+x+x+ +",
	}, &db);
}
}
}
<|endoftext|>


<commit_before>/* Finds the distance between the origin and a polytope (defined by its vertices) using bullet's low level functions. Uses GJK and EPA algorithms.

Author: Anirudha Majumdar
Date: Nov 8 2013
*/

///We need internal access to bullet
// #include "GL_Simplex1to4.h"
#include "LinearMath/btTransform.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"

#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionShapes/btConvexHullShape.h"
// #include <iostream>
// #include <chrono>
// #include <ctime>
// #include <time.h>

#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPointCollector.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "LinearMath/btTransformUtil.h"

#include <mex.h>
#include <drakeMexUtil.h>

using namespace std;

// Set solvers
static btVoronoiSimplexSolver sGjkSimplexSolver;
static btGjkEpaPenetrationDepthSolver epaSolver;

/*Sphere of radius r representing the point.
We could probably make the radius 0 and be ok, but I'm not sure if bullet expects things to be non-degenrate.
*/
static const double radius = 0.5;
static btSphereShape* point = new btSphereShape(radius);

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	 // Check for proper number of arguments.
 	 if(nrhs!=1) {
	   mexErrMsgIdAndTxt( "MATLAB:ptToPolyDist:invalidNumInputs",
  	  "One input required.");
	 } else if(nlhs>1) {
 	  mexErrMsgIdAndTxt( "MATLAB:ptToPolyDist:maxlhs",
 	          "Too many output arguments.");
	 }

	// Get inputs
	  double *vertsPr;
	  vertsPr = mxGetPrSafe(prhs[0]);
	  const int nRows = mxGetM(prhs[0]); // number of rows
	  const int nCols = mxGetN(prhs[0]); // number of columns

	  // Check to see if number of rows of vertices is 3
	  if(nRows != 3){
	    mexErrMsgIdAndTxt( "MATLAB:ptToPolyDist:invalidInputs",
		    "Input should be 3 x N");
	  }

	// Initialize polytope object with single point
	btConvexHullShape polytope(btVector3(vertsPr[0],vertsPr[1],vertsPr[2]), 1);

	// Add rest of the points (note the indexing starts from 1 on the loop)
	for(int i=1;i<nCols;i++){
			polytope.addPoint(btVector3(vertsPr[i*nRows],vertsPr[i*nRows+1],vertsPr[i*nRows+2]));

	/*
	mexPrintf("i: %d\n", i);
	mexPrintf("x: %f", vertsPr[i*nRows]);
	mexPrintf("y: %f", vertsPr[i*nRows+1]);
	mexPrintf("z: %f\n", vertsPr[i*nRows+2]);*/

	}

	// btConvexHullShape polytope(&points0[0].getX(),6);

	 // Assign elements of verts (input) to polytope
	btTransform tr;
	btGjkPairDetector::ClosestPointInput input;
	tr.setIdentity();
	input.m_transformA = tr;
	input.m_transformB = tr;

	btGjkPairDetector convexConvex(point,&polytope,&sGjkSimplexSolver,&epaSolver);

	// Output
	btPointCollector gjkOutput;

	convexConvex.getClosestPoints(input, gjkOutput, 0);

	// mexPrintf("Hello!\n");

	plhs[0] = mxCreateDoubleScalar(gjkOutput.m_distance + radius + CONVEX_DISTANCE_MARGIN);

        // cout << gjkOutput.m_distance + radius + CONVEX_DISTANCE_MARGIN << endl;

}

<commit_msg>mex errors are now Drake errors instead of MATLAB errors<commit_after>/* Finds the distance between the origin and a polytope (defined by its vertices) using bullet's low level functions. Uses GJK and EPA algorithms.

Author: Anirudha Majumdar
Date: Nov 8 2013
*/

///We need internal access to bullet
// #include "GL_Simplex1to4.h"
#include "LinearMath/btTransform.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"

#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionShapes/btConvexHullShape.h"
// #include <iostream>
// #include <chrono>
// #include <ctime>
// #include <time.h>

#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPointCollector.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
#include "LinearMath/btTransformUtil.h"

#include <mex.h>
#include <drakeMexUtil.h>

using namespace std;

// Set solvers
static btVoronoiSimplexSolver sGjkSimplexSolver;
static btGjkEpaPenetrationDepthSolver epaSolver;

/*Sphere of radius r representing the point.
We could probably make the radius 0 and be ok, but I'm not sure if bullet expects things to be non-degenrate.
*/
static const double radius = 0.5;
static btSphereShape* point = new btSphereShape(radius);

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	 // Check for proper number of arguments.
 	 if(nrhs!=1) {
	   mexErrMsgIdAndTxt( "Drake:ptToPolyDist:invalidNumInputs",
  	  "One input required.");
	 } else if(nlhs>1) {
 	  mexErrMsgIdAndTxt( "Drake:ptToPolyDist:maxlhs",
 	          "Too many output arguments.");
	 }

	// Get inputs
	  double *vertsPr;
	  vertsPr = mxGetPrSafe(prhs[0]);
	  const int nRows = mxGetM(prhs[0]); // number of rows
	  const int nCols = mxGetN(prhs[0]); // number of columns

	  // Check to see if number of rows of vertices is 3
	  if(nRows != 3){
	    mexErrMsgIdAndTxt( "Drake:ptToPolyDist:invalidInputs",
		    "Input should be 3 x N");
	  }

	// Initialize polytope object with single point
	btConvexHullShape polytope(btVector3(vertsPr[0],vertsPr[1],vertsPr[2]), 1);

	// Add rest of the points (note the indexing starts from 1 on the loop)
	for(int i=1;i<nCols;i++){
			polytope.addPoint(btVector3(vertsPr[i*nRows],vertsPr[i*nRows+1],vertsPr[i*nRows+2]));

	/*
	mexPrintf("i: %d\n", i);
	mexPrintf("x: %f", vertsPr[i*nRows]);
	mexPrintf("y: %f", vertsPr[i*nRows+1]);
	mexPrintf("z: %f\n", vertsPr[i*nRows+2]);*/

	}

	// btConvexHullShape polytope(&points0[0].getX(),6);

	 // Assign elements of verts (input) to polytope
	btTransform tr;
	btGjkPairDetector::ClosestPointInput input;
	tr.setIdentity();
	input.m_transformA = tr;
	input.m_transformB = tr;

	btGjkPairDetector convexConvex(point,&polytope,&sGjkSimplexSolver,&epaSolver);

	// Output
	btPointCollector gjkOutput;

	convexConvex.getClosestPoints(input, gjkOutput, 0);

	// mexPrintf("Hello!\n");

	plhs[0] = mxCreateDoubleScalar(gjkOutput.m_distance + radius + CONVEX_DISTANCE_MARGIN);

        // cout << gjkOutput.m_distance + radius + CONVEX_DISTANCE_MARGIN << endl;

}

<|endoftext|>


<commit_before>#include "BBNodeManagerAIG.h"

namespace BEEV
{

  void
  BBNodeManagerAIG::toCNF(const BBNodeAIG& top, Cnf_Dat_t*& cnfData, ToSATBase::ASTNodeToSATVar& nodeToVar, const UserDefinedFlags& uf)
  {
    assert(cnfData == NULL);

    Aig_ObjCreatePo(aigMgr, top.n);
    Aig_ManCleanup(aigMgr); // remove nodes not connected to the PO.
    Aig_ManCheck(aigMgr); // check that AIG looks ok.

    assert(Aig_ManPoNum(aigMgr) == 1);

    // UseZeroes gives assertion errors.
    // Rewriting is sometimes very slow. Can it be configured to be faster?
    // What about refactoring???

    int nodeCount = aigMgr->nObjs[AIG_OBJ_AND];
    if (uf.stats_flag)
      cerr << "Nodes before AIG rewrite:" << nodeCount <<endl;

    if (uf.enable_AIG_rewrites_flag && aigMgr->nObjs[AIG_OBJ_AND] < 5000)
      {
          Dar_LibStart();
          Aig_Man_t * pTemp;
          Dar_RwrPar_t Pars, * pPars = &Pars;
          Dar_ManDefaultRwrParams( pPars );

          // Assertion errors occur with this enabled.
          // pPars->fUseZeros = 1;

          // For mul63bit.smt2 with iterations =3 & nCutsMax = 8
          // CNF generation was taking 139 seconds, solving 10 seconds.

          // With nCutsMax =2, CNF generation takes 16 seconds, solving 10 seconds.
          // The rewriting doesn't remove as many nodes of course..
          int iterations = 3;

          for (int i=0; i < iterations;i++)
          {
            aigMgr = Aig_ManDup( pTemp = aigMgr, 0 );
            Aig_ManStop( pTemp );
            Dar_ManRewrite( aigMgr, pPars );

            aigMgr = Aig_ManDup( pTemp = aigMgr, 0 );
            Aig_ManStop( pTemp );

            if (uf.stats_flag)
              cerr << "After rewrite [" << i << "]  nodes:" << aigMgr->nObjs[AIG_OBJ_AND] << endl;

            if (nodeCount == aigMgr->nObjs[AIG_OBJ_AND])
              break;
          }
      }
    cnfData = Cnf_Derive(aigMgr, 0);

    BBNodeManagerAIG::SymbolToBBNode::const_iterator it;

    assert(nodeToVar.size() ==0);

    // Each symbol maps to a vector of CNF variables.
    for (it = symbolToBBNode.begin(); it != symbolToBBNode.end(); it++)
      {
        const ASTNode& n = it->first;
        const vector<BBNodeAIG> &b = it->second;
        assert (nodeToVar.find(n) == nodeToVar.end());

        const int width = (n.GetType() == BOOLEAN_TYPE) ? 1: n.GetValueWidth();

        // INT_MAX for parts of symbols that didn't get encoded.
        vector<unsigned> v(width, ~((unsigned) 0));

        for (unsigned i = 0; i < b.size(); i++)
          {
            if (!b[i].IsNull())
              {
                Aig_Obj_t * pObj;
                pObj = (Aig_Obj_t*)Vec_PtrEntry( aigMgr->vPis, b[i].symbol_index );
                v[i] = cnfData->pVarNums[pObj->Id];
              }
          }

        nodeToVar.insert(make_pair(n, v));
      }
    assert(cnfData != NULL);
  }
}

<commit_msg>When encoding to CNF via ABC, use the simple mapping if there are more than 10M nodes. This is because currently ABC seems to have a 4GB memory limit internally. So any more than about 10M nodes maxes out the memory.<commit_after>#include "BBNodeManagerAIG.h"

namespace BEEV
{

  void
  BBNodeManagerAIG::toCNF(const BBNodeAIG& top, Cnf_Dat_t*& cnfData, ToSATBase::ASTNodeToSATVar& nodeToVar, const UserDefinedFlags& uf)
  {
    assert(cnfData == NULL);

    Aig_ObjCreatePo(aigMgr, top.n);
    Aig_ManCleanup(aigMgr); // remove nodes not connected to the PO.
    Aig_ManCheck(aigMgr); // check that AIG looks ok.

    assert(Aig_ManPoNum(aigMgr) == 1);

    // UseZeroes gives assertion errors.
    // Rewriting is sometimes very slow. Can it be configured to be faster?
    // What about refactoring???

    int nodeCount = aigMgr->nObjs[AIG_OBJ_AND];
    if (uf.stats_flag)
      cerr << "Nodes before AIG rewrite:" << nodeCount <<endl;

    if (uf.enable_AIG_rewrites_flag && aigMgr->nObjs[AIG_OBJ_AND] < 5000)
      {
          Dar_LibStart();
          Aig_Man_t * pTemp;
          Dar_RwrPar_t Pars, * pPars = &Pars;
          Dar_ManDefaultRwrParams( pPars );

          // Assertion errors occur with this enabled.
          // pPars->fUseZeros = 1;

          // For mul63bit.smt2 with iterations =3 & nCutsMax = 8
          // CNF generation was taking 139 seconds, solving 10 seconds.

          // With nCutsMax =2, CNF generation takes 16 seconds, solving 10 seconds.
          // The rewriting doesn't remove as many nodes of course..
          int iterations = 3;

          for (int i=0; i < iterations;i++)
          {
            aigMgr = Aig_ManDup( pTemp = aigMgr, 0 );
            Aig_ManStop( pTemp );
            Dar_ManRewrite( aigMgr, pPars );

            aigMgr = Aig_ManDup( pTemp = aigMgr, 0 );
            Aig_ManStop( pTemp );

            if (uf.stats_flag)
              cerr << "After rewrite [" << i << "]  nodes:" << aigMgr->nObjs[AIG_OBJ_AND] << endl;

            if (nodeCount == aigMgr->nObjs[AIG_OBJ_AND])
              break;
          }
      }
    if (aigMgr->nObjs[AIG_OBJ_AND] < 10000000)
      cnfData = Cnf_Derive(aigMgr, 0);
    else
      cnfData = Cnf_DeriveSimple(aigMgr, 0);

    BBNodeManagerAIG::SymbolToBBNode::const_iterator it;

    assert(nodeToVar.size() ==0);

    // Each symbol maps to a vector of CNF variables.
    for (it = symbolToBBNode.begin(); it != symbolToBBNode.end(); it++)
      {
        const ASTNode& n = it->first;
        const vector<BBNodeAIG> &b = it->second;
        assert (nodeToVar.find(n) == nodeToVar.end());

        const int width = (n.GetType() == BOOLEAN_TYPE) ? 1: n.GetValueWidth();

        // INT_MAX for parts of symbols that didn't get encoded.
        vector<unsigned> v(width, ~((unsigned) 0));

        for (unsigned i = 0; i < b.size(); i++)
          {
            if (!b[i].IsNull())
              {
                Aig_Obj_t * pObj;
                pObj = (Aig_Obj_t*)Vec_PtrEntry( aigMgr->vPis, b[i].symbol_index );
                v[i] = cnfData->pVarNums[pObj->Id];
              }
          }

        nodeToVar.insert(make_pair(n, v));
      }
    assert(cnfData != NULL);
  }
}

<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2016 dune-gdt developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// Authors:
//   Felix Schindler (2016)

#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_IPDG_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_IPDG_HH

#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/grid/boundaryinfo.hh>
#include <dune/xt/grid/layers.hh>
#include <dune/xt/grid/gridprovider.hh>
#include <dune/xt/la/container.hh>

#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/discretizations/default.hh>
#include <dune/gdt/functionals/elliptic-ipdg.hh>
#include <dune/gdt/operators/elliptic-ipdg.hh>
#include <dune/gdt/spaces/dg.hh>

#include "../problems/interface.hh"
#include "base.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

/**
 * \brief Discretizes a linear elliptic PDE using an interior penalty discontinuous Galerkin Finite Element method.
 */
template <class GridType,
          XT::Grid::Layers layer = XT::Grid::Layers::leaf,
          ChooseSpaceBackend spacebackend = default_dg_backend,
          XT::LA::Backends la = XT::LA::default_sparse_backend,
          int pol = 1,
          class RangeFieldType = double,
          size_t dimRange = 1,
          LocalEllipticIpdgIntegrands::Method method = LocalEllipticIpdgIntegrands::default_method>
class IpdgDiscretizer
{
public:
  typedef ProblemInterface<typename GridType::template Codim<0>::Entity,
                           typename GridType::ctype,
                           GridType::dimension,
                           RangeFieldType,
                           dimRange>
      ProblemType;
  typedef DgSpaceProvider<GridType, layer, spacebackend, pol, RangeFieldType, dimRange> SpaceProvider;
  typedef typename SpaceProvider::Type SpaceType;
  typedef typename XT::LA::Container<RangeFieldType, la>::MatrixType MatrixType;
  typedef typename XT::LA::Container<RangeFieldType, la>::VectorType VectorType;
  typedef StationaryContainerBasedDefaultDiscretization<ProblemType, SpaceType, MatrixType, VectorType, SpaceType>
      DiscretizationType;
  static const constexpr ChooseDiscretizer type = ChooseDiscretizer::swipdg;
  static const constexpr XT::LA::Backends la_backend = la;
  static const int polOrder = pol;

  static std::string static_id() //                                                        int() needed, otherwise we
  { //                                                                                get a linker error
    return std::string("gdt.linearelliptic.discretization.swipdg.order_") + Dune::XT::Common::to_string(int(polOrder));
  }

  static DiscretizationType
  discretize(XT::Grid::GridProvider<GridType>& grid_provider, const ProblemType& problem, const int level = 0)
  {
    auto logger = XT::Common::TimedLogger().get(static_id());
    logger.info() << "Creating space... " << std::endl;
    auto space = SpaceProvider::create(grid_provider, level);
    logger.debug() << "grid has " << space.grid_view().indexSet().size(0) << " elements" << std::endl;
    typedef typename SpaceType::GridViewType GridViewType;
    typedef typename GridViewType::Intersection IntersectionType;
    auto boundary_info = XT::Grid::BoundaryInfoFactory<IntersectionType>::create(problem.boundary_info_cfg());
    logger.info() << "Assembling... " << std::endl;
    VectorType rhs_vector(space.mapper().size(), 0.0);
    auto ipdg_operator = make_elliptic_ipdg_matrix_operator<MatrixType, method>(
        problem.diffusion_factor(), problem.diffusion_tensor(), *boundary_info, space);
    auto ipdg_boundary_functional = make_elliptic_ipdg_dirichlet_vector_functional<method>(
        problem.dirichlet(), problem.diffusion_factor(), problem.diffusion_tensor(), *boundary_info, rhs_vector, space);
    auto l2_force_functional = make_l2_volume_vector_functional(problem.force(), rhs_vector, space);
    auto l2_neumann_functional =
        make_l2_face_vector_functional(problem.neumann(),
                                       rhs_vector,
                                       space,
                                       new XT::Grid::ApplyOn::NeumannIntersections<GridViewType>(*boundary_info));
    // register everything for assembly in one grid walk
    SystemAssembler<SpaceType> assembler(space);
    assembler.add(*ipdg_operator);
    assembler.add(*ipdg_boundary_functional);
    assembler.add(*l2_force_functional);
    assembler.add(*l2_neumann_functional);
    assembler.assemble();
    // create the discretization (no copy of the containers done here, bc. of cow)
    return DiscretizationType(problem, space, ipdg_operator->matrix(), rhs_vector);
  } // ... discretize(...)
}; // class IpdgDiscretizer

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_IPDG_HH
<commit_msg>[test...linearelliptic.ipdg] add missing include<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2016 dune-gdt developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// Authors:
//   Felix Schindler (2016)

#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_IPDG_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_IPDG_HH

#include <dune/xt/common/timedlogging.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/grid/boundaryinfo.hh>
#include <dune/xt/grid/layers.hh>
#include <dune/xt/grid/gridprovider.hh>
#include <dune/xt/la/container.hh>

#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/discretizations/default.hh>
#include <dune/gdt/functionals/elliptic-ipdg.hh>
#include <dune/gdt/functionals/l2.hh>
#include <dune/gdt/operators/elliptic-ipdg.hh>
#include <dune/gdt/spaces/dg.hh>

#include "../problems/interface.hh"
#include "base.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

/**
 * \brief Discretizes a linear elliptic PDE using an interior penalty discontinuous Galerkin Finite Element method.
 */
template <class GridType,
          XT::Grid::Layers layer = XT::Grid::Layers::leaf,
          ChooseSpaceBackend spacebackend = default_dg_backend,
          XT::LA::Backends la = XT::LA::default_sparse_backend,
          int pol = 1,
          class RangeFieldType = double,
          size_t dimRange = 1,
          LocalEllipticIpdgIntegrands::Method method = LocalEllipticIpdgIntegrands::default_method>
class IpdgDiscretizer
{
public:
  typedef ProblemInterface<typename GridType::template Codim<0>::Entity,
                           typename GridType::ctype,
                           GridType::dimension,
                           RangeFieldType,
                           dimRange>
      ProblemType;
  typedef DgSpaceProvider<GridType, layer, spacebackend, pol, RangeFieldType, dimRange> SpaceProvider;
  typedef typename SpaceProvider::Type SpaceType;
  typedef typename XT::LA::Container<RangeFieldType, la>::MatrixType MatrixType;
  typedef typename XT::LA::Container<RangeFieldType, la>::VectorType VectorType;
  typedef StationaryContainerBasedDefaultDiscretization<ProblemType, SpaceType, MatrixType, VectorType, SpaceType>
      DiscretizationType;
  static const constexpr ChooseDiscretizer type = ChooseDiscretizer::swipdg;
  static const constexpr XT::LA::Backends la_backend = la;
  static const int polOrder = pol;

  static std::string static_id() //                                                        int() needed, otherwise we
  { //                                                                                get a linker error
    return std::string("gdt.linearelliptic.discretization.swipdg.order_") + Dune::XT::Common::to_string(int(polOrder));
  }

  static DiscretizationType
  discretize(XT::Grid::GridProvider<GridType>& grid_provider, const ProblemType& problem, const int level = 0)
  {
    auto logger = XT::Common::TimedLogger().get(static_id());
    logger.info() << "Creating space... " << std::endl;
    auto space = SpaceProvider::create(grid_provider, level);
    logger.debug() << "grid has " << space.grid_view().indexSet().size(0) << " elements" << std::endl;
    typedef typename SpaceType::GridViewType GridViewType;
    typedef typename GridViewType::Intersection IntersectionType;
    auto boundary_info = XT::Grid::BoundaryInfoFactory<IntersectionType>::create(problem.boundary_info_cfg());
    logger.info() << "Assembling... " << std::endl;
    VectorType rhs_vector(space.mapper().size(), 0.0);
    auto ipdg_operator = make_elliptic_ipdg_matrix_operator<MatrixType, method>(
        problem.diffusion_factor(), problem.diffusion_tensor(), *boundary_info, space);
    auto ipdg_boundary_functional = make_elliptic_ipdg_dirichlet_vector_functional<method>(
        problem.dirichlet(), problem.diffusion_factor(), problem.diffusion_tensor(), *boundary_info, rhs_vector, space);
    auto l2_force_functional = make_l2_volume_vector_functional(problem.force(), rhs_vector, space);
    auto l2_neumann_functional =
        make_l2_face_vector_functional(problem.neumann(),
                                       rhs_vector,
                                       space,
                                       new XT::Grid::ApplyOn::NeumannIntersections<GridViewType>(*boundary_info));
    // register everything for assembly in one grid walk
    SystemAssembler<SpaceType> assembler(space);
    assembler.add(*ipdg_operator);
    assembler.add(*ipdg_boundary_functional);
    assembler.add(*l2_force_functional);
    assembler.add(*l2_neumann_functional);
    assembler.assemble();
    // create the discretization (no copy of the containers done here, bc. of cow)
    return DiscretizationType(problem, space, ipdg_operator->matrix(), rhs_vector);
  } // ... discretize(...)
}; // class IpdgDiscretizer

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_DISCRETIZERS_IPDG_HH
<|endoftext|>


<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/

#include "SinkMapUserObject.h"
#include "MooseMesh.h"
#include "GaussianUserObject.h"

// libmesh includes
#include "libmesh/quadrature.h"

template<>
InputParameters validParams<SinkMapUserObject>()
{
  MooseEnum sink_placement("corner inside", "corner");
  MooseEnum sink_shape_3d("spheres lines", "lines");

  InputParameters params = validParams<ElementUserObject>();
  params.addRequiredParam<Real>("spacing", "Distance to space sink centers");
  params.addRequiredParam<Real>("strength", "Average strength of the overall sink map.");
  params.addRequiredParam<UserObjectName>("gaussian_user_object", "Name of the GaussianUserObject to use for sink shapes.");
  params.addParam<MooseEnum>("sink_placement", sink_placement, "How to place sinks on domain, choices are 'corner' to place them in the corners (and wrap around), and 'inside' to keep them away from edges.");
  params.addParam<MooseEnum>("sink_shape_3d", sink_shape_3d, "Shape to use for sinks in 3D, choices are 'spheres' or 'lines'.");
  params.addCoupledVar("periodic_variable", "Use the periodicity settings of this variable to populate the grain map");

  MultiMooseEnum setup_options(SetupInterface::getExecuteOptions());
  // the mapping needs to run at timestep begin, which is after the adaptivity
  // run of the previous timestep.
  setup_options = "timestep_begin";
  params.set<MultiMooseEnum>("execute_on") = setup_options;
  return params;
}

SinkMapUserObject::SinkMapUserObject(const InputParameters & parameters) :
    ElementUserObject(parameters),
    _spacing(getParam<Real>("spacing")),
    _strength(getParam<Real>("strength")),
    _gaussian_user_object_ptr(NULL),
    _sink_placement(getParam<MooseEnum>("sink_placement")),
    _sink_shape_3d(getParam<MooseEnum>("sink_shape_3d")),
    _periodic_var(isCoupled("periodic_variable") ? coupled("periodic_variable") : -1),
    _dim(_mesh.dimension()),
    _mesh_changed(true)
{
  _zero_map.assign(_fe_problem.getMaxQps(), 0.0);
}

void
SinkMapUserObject::initialSetup()
{
  // get sink sigma
  _gaussian_user_object_ptr = &getUserObject<GaussianUserObject>("gaussian_user_object");
  _sigma = _gaussian_user_object_ptr->getSigma();

  // calculate sink locations
  if (_sink_placement == "corner")
  {
    // yes this is dumb, but it works
    for (Real x_center = _mesh.getMinInDimension(0); x_center <= _mesh.getMinInDimension(0) + _mesh.dimensionWidth(0); x_center += _spacing)
      for (Real y_center = _mesh.getMinInDimension(1); y_center <= _mesh.getMinInDimension(1) + _mesh.dimensionWidth(1); y_center += _spacing)
        if ((_dim == 3) && (_sink_shape_3d == "spheres"))
          for (Real z_center = _mesh.getMinInDimension(2); z_center <= _mesh.getMinInDimension(2) + _mesh.dimensionWidth(2); z_center += _spacing)
            _sink_location_list.push_back(Point(x_center, y_center, z_center));
        else
          _sink_location_list.push_back(Point(x_center, y_center, 0.0));
  }
  else  // centered sink placement
  {
    if (_dim == 1)
      for (Real x_center = _mesh.getMinInDimension(0) + _spacing/2.0; x_center <= _mesh.getMinInDimension(0) + _mesh.dimensionWidth(0) - _spacing/2.0; x_center += _spacing)
        _sink_location_list.push_back(Point(x_center, 0.0, 0.0));
    else
      for (Real x_center = _mesh.getMinInDimension(0) + _spacing/2.0; x_center <= _mesh.getMinInDimension(0) + _mesh.dimensionWidth(0) - _spacing/2.0; x_center += _spacing)
        for (Real y_center = _mesh.getMinInDimension(1) + _spacing/2.0; y_center <= _mesh.getMinInDimension(1) + _mesh.dimensionWidth(1) - _spacing/2.0; y_center += _spacing)
          if ((_dim == 3) && (_sink_shape_3d == "spheres"))
            for (Real z_center = _mesh.getMinInDimension(2) + _spacing/2.0; z_center <= _mesh.getMinInDimension(2) + _mesh.dimensionWidth(2) - _spacing/2.0; z_center += _spacing)
              _sink_location_list.push_back(Point(x_center, y_center, z_center));
          else
            _sink_location_list.push_back(Point(x_center, y_center, 0.0));
  }

  // compute normalization constant
  _norm = _strength*std::pow(_spacing, (double) _dim);

  // normalization constant from GaussianUserObject has an additional 1/(sigma*sqrt(2*pi)) since mesh is in 3D but lines are in 2D
  if ((_dim == 3) && (_sink_shape_3d == "lines"))
    _norm *= _sigma*std::sqrt(2.0*libMesh::pi);

  // print sink centers
  for (unsigned int i=0; i<_sink_location_list.size(); i++)
    _console << _sink_location_list[i] << std::endl;
}

void
SinkMapUserObject::initialize()
{
  if (_mesh_changed)
  {
    _rebuild_map = true;
    _sink_strength_map.clear();
  }
  else
    _rebuild_map = false;

  _mesh_changed = false;
}

void
SinkMapUserObject::execute()
{
  if (_rebuild_map)
  {
    // reserve space for each quadrature point in the element
    _elem_map.assign(_qrule->n_points(), 0);

    // loop over quadrature points in this element
    for (unsigned int qp = 0; qp < _qrule->n_points(); ++qp)
    {
      // find distance to nearest sink from this point
      Real rmin = getDistanceToNearestSink(_q_point[qp]);

      // compute sink strength at this location
      _elem_map[qp] = _norm*_gaussian_user_object_ptr->value(rmin);
    }

    // insert vector into map
    _sink_strength_map.insert(std::pair<dof_id_type, std::vector<Real> >(_current_elem->id(), _elem_map));
  }
}

void
SinkMapUserObject::threadJoin(const UserObject &y)
{
  // if the map needs to be updated we merge the maps from all threads
  if (_rebuild_map)
  {
    const SinkMapUserObject & uo = static_cast<const SinkMapUserObject &>(y);
    _sink_strength_map.insert(uo._sink_strength_map.begin(), uo._sink_strength_map.end());
  }
}

void
SinkMapUserObject::meshChanged()
{
  _mesh_changed = true;
}

const std::vector<Real> &
SinkMapUserObject::getLocalSinkMap(const Elem * elem) const
{
  SinkMap::const_iterator i = _sink_strength_map.find(elem->id());

  // if no entry in the map was found then something went wrong
  if (i == _sink_strength_map.end())
    mooseError("no sinks found in element " << elem->id());

  return i->second;
}

Real
SinkMapUserObject::getDistanceToNearestSink(const Point & p) const
{
  Real r, rmin = std::numeric_limits<Real>::max();

  // to do 3D lines, need to change z-component of point to that of a sink
  // so the distance to the line is based on the xy-plane distance
  Point new_p;
  if ((_dim == 3) && (_sink_shape_3d == "lines"))
    new_p = Point(p(0), p(1), 0.0);
  else
    new_p = p;

  // find the distance to the closest sink location
  for (unsigned i = 0; i < _sink_location_list.size(); ++i)
  {
    // use a non-periodic or periodic distance
    r = _periodic_var < 0 ?
          (new_p - _sink_location_list[i]).norm() :
          _mesh.minPeriodicDistance(_periodic_var, new_p, _sink_location_list[i]);
    if (r < rmin)
      rmin = r;
  }
  return rmin;
}
<commit_msg>typo in SinkMapUserObject.C, closes #42<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/

#include "SinkMapUserObject.h"
#include "MooseMesh.h"
#include "GaussianUserObject.h"

// libmesh includes
#include "libmesh/quadrature.h"

template<>
InputParameters validParams<SinkMapUserObject>()
{
  MooseEnum sink_placement("corner inside", "corner");
  MooseEnum sink_shape_3d("spheres lines", "lines");

  InputParameters params = validParams<ElementUserObject>();
  params.addRequiredParam<Real>("spacing", "Distance to space sink centers");
  params.addRequiredParam<Real>("strength", "Average strength of the overall sink map.");
  params.addRequiredParam<UserObjectName>("gaussian_user_object", "Name of the GaussianUserObject to use for sink shapes.");
  params.addParam<MooseEnum>("sink_placement", sink_placement, "How to place sinks on domain, choices are 'corner' to place them in the corners (and wrap around), and 'inside' to keep them away from edges.");
  params.addParam<MooseEnum>("sink_shape_3d", sink_shape_3d, "Shape to use for sinks in 3D, choices are 'spheres' or 'lines'.");
  params.addCoupledVar("periodic_variable", "Use the periodicity settings of this variable to populate the sink map");

  MultiMooseEnum setup_options(SetupInterface::getExecuteOptions());
  // the mapping needs to run at timestep begin, which is after the adaptivity
  // run of the previous timestep.
  setup_options = "timestep_begin";
  params.set<MultiMooseEnum>("execute_on") = setup_options;
  return params;
}

SinkMapUserObject::SinkMapUserObject(const InputParameters & parameters) :
    ElementUserObject(parameters),
    _spacing(getParam<Real>("spacing")),
    _strength(getParam<Real>("strength")),
    _gaussian_user_object_ptr(NULL),
    _sink_placement(getParam<MooseEnum>("sink_placement")),
    _sink_shape_3d(getParam<MooseEnum>("sink_shape_3d")),
    _periodic_var(isCoupled("periodic_variable") ? coupled("periodic_variable") : -1),
    _dim(_mesh.dimension()),
    _mesh_changed(true)
{
  _zero_map.assign(_fe_problem.getMaxQps(), 0.0);
}

void
SinkMapUserObject::initialSetup()
{
  // get sink sigma
  _gaussian_user_object_ptr = &getUserObject<GaussianUserObject>("gaussian_user_object");
  _sigma = _gaussian_user_object_ptr->getSigma();

  // calculate sink locations
  if (_sink_placement == "corner")
  {
    // yes this is dumb, but it works
    for (Real x_center = _mesh.getMinInDimension(0); x_center <= _mesh.getMinInDimension(0) + _mesh.dimensionWidth(0); x_center += _spacing)
      for (Real y_center = _mesh.getMinInDimension(1); y_center <= _mesh.getMinInDimension(1) + _mesh.dimensionWidth(1); y_center += _spacing)
        if ((_dim == 3) && (_sink_shape_3d == "spheres"))
          for (Real z_center = _mesh.getMinInDimension(2); z_center <= _mesh.getMinInDimension(2) + _mesh.dimensionWidth(2); z_center += _spacing)
            _sink_location_list.push_back(Point(x_center, y_center, z_center));
        else
          _sink_location_list.push_back(Point(x_center, y_center, 0.0));
  }
  else  // centered sink placement
  {
    if (_dim == 1)
      for (Real x_center = _mesh.getMinInDimension(0) + _spacing/2.0; x_center <= _mesh.getMinInDimension(0) + _mesh.dimensionWidth(0) - _spacing/2.0; x_center += _spacing)
        _sink_location_list.push_back(Point(x_center, 0.0, 0.0));
    else
      for (Real x_center = _mesh.getMinInDimension(0) + _spacing/2.0; x_center <= _mesh.getMinInDimension(0) + _mesh.dimensionWidth(0) - _spacing/2.0; x_center += _spacing)
        for (Real y_center = _mesh.getMinInDimension(1) + _spacing/2.0; y_center <= _mesh.getMinInDimension(1) + _mesh.dimensionWidth(1) - _spacing/2.0; y_center += _spacing)
          if ((_dim == 3) && (_sink_shape_3d == "spheres"))
            for (Real z_center = _mesh.getMinInDimension(2) + _spacing/2.0; z_center <= _mesh.getMinInDimension(2) + _mesh.dimensionWidth(2) - _spacing/2.0; z_center += _spacing)
              _sink_location_list.push_back(Point(x_center, y_center, z_center));
          else
            _sink_location_list.push_back(Point(x_center, y_center, 0.0));
  }

  // compute normalization constant
  _norm = _strength*std::pow(_spacing, (double) _dim);

  // normalization constant from GaussianUserObject has an additional 1/(sigma*sqrt(2*pi)) since mesh is in 3D but lines are in 2D
  if ((_dim == 3) && (_sink_shape_3d == "lines"))
    _norm *= _sigma*std::sqrt(2.0*libMesh::pi);

  // print sink centers
  for (unsigned int i=0; i<_sink_location_list.size(); i++)
    _console << _sink_location_list[i] << std::endl;
}

void
SinkMapUserObject::initialize()
{
  if (_mesh_changed)
  {
    _rebuild_map = true;
    _sink_strength_map.clear();
  }
  else
    _rebuild_map = false;

  _mesh_changed = false;
}

void
SinkMapUserObject::execute()
{
  if (_rebuild_map)
  {
    // reserve space for each quadrature point in the element
    _elem_map.assign(_qrule->n_points(), 0);

    // loop over quadrature points in this element
    for (unsigned int qp = 0; qp < _qrule->n_points(); ++qp)
    {
      // find distance to nearest sink from this point
      Real rmin = getDistanceToNearestSink(_q_point[qp]);

      // compute sink strength at this location
      _elem_map[qp] = _norm*_gaussian_user_object_ptr->value(rmin);
    }

    // insert vector into map
    _sink_strength_map.insert(std::pair<dof_id_type, std::vector<Real> >(_current_elem->id(), _elem_map));
  }
}

void
SinkMapUserObject::threadJoin(const UserObject &y)
{
  // if the map needs to be updated we merge the maps from all threads
  if (_rebuild_map)
  {
    const SinkMapUserObject & uo = static_cast<const SinkMapUserObject &>(y);
    _sink_strength_map.insert(uo._sink_strength_map.begin(), uo._sink_strength_map.end());
  }
}

void
SinkMapUserObject::meshChanged()
{
  _mesh_changed = true;
}

const std::vector<Real> &
SinkMapUserObject::getLocalSinkMap(const Elem * elem) const
{
  SinkMap::const_iterator i = _sink_strength_map.find(elem->id());

  // if no entry in the map was found then something went wrong
  if (i == _sink_strength_map.end())
    mooseError("no sinks found in element " << elem->id());

  return i->second;
}

Real
SinkMapUserObject::getDistanceToNearestSink(const Point & p) const
{
  Real r, rmin = std::numeric_limits<Real>::max();

  // to do 3D lines, need to change z-component of point to that of a sink
  // so the distance to the line is based on the xy-plane distance
  Point new_p;
  if ((_dim == 3) && (_sink_shape_3d == "lines"))
    new_p = Point(p(0), p(1), 0.0);
  else
    new_p = p;

  // find the distance to the closest sink location
  for (unsigned i = 0; i < _sink_location_list.size(); ++i)
  {
    // use a non-periodic or periodic distance
    r = _periodic_var < 0 ?
          (new_p - _sink_location_list[i]).norm() :
          _mesh.minPeriodicDistance(_periodic_var, new_p, _sink_location_list[i]);
    if (r < rmin)
      rmin = r;
  }
  return rmin;
}
<|endoftext|>


<commit_before>#ifndef DOMNamedNodeMap_HEADER_GUARD_
#define DOMNamedNodeMap_HEADER_GUARD_

/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#include <xercesc/util/XercesDefs.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class DOMNode;

/**
 *  DOMNamedNodeMaps  are used to
 * represent collections of nodes that can be accessed by name.
 *
 * Note that DOMNamedNodeMap does not inherit from DOMNodeList;
 * DOMNamedNodeMaps are not maintained in any particular order.
 * Nodes contained in a DOMNamedNodeMap may
 * also be accessed by an ordinal index, but this is simply to allow
 * convenient enumeration of the contents, and
 * does not imply that the DOM specifies an order to these Nodes.
 *
 * @since DOM Level 1
 */
class CDOM_EXPORT DOMNamedNodeMap {
protected:
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    /** @name Hidden constructors */
    //@{
    DOMNamedNodeMap() {};
    DOMNamedNodeMap(const DOMNamedNodeMap &) {};
    DOMNamedNodeMap & operator = (const DOMNamedNodeMap &) {return *this;};
    //@}

public:
    // -----------------------------------------------------------------------
    //  All constructors are hidden, just the destructor is available
    // -----------------------------------------------------------------------
    /** @name Destructor */
    //@{
    /**
     * Destructor
     *
     */
    virtual ~DOMNamedNodeMap() {};
    //@}

    // -----------------------------------------------------------------------
    //  Virtual DOMNamedNodeMap interface
    // -----------------------------------------------------------------------
    /** @name Functions introduced in DOM Level 1 */
    //@{
    // -----------------------------------------------------------------------
    //  Setter methods
    // -----------------------------------------------------------------------
    /**
     * Adds a node using its nodeName attribute.
     *
     *
As the nodeName attribute is used to derive the name
     * which the node must be stored under, multiple nodes of certain types
     * (those that have a "special" string value) cannot be stored as the names
     * would clash. This is seen as preferable to allowing nodes to be aliased.
     * @param arg A node to store in a named node map. The node will later be
     *   accessible using the value of the nodeName attribute of
     *   the node. If a node with that name is already present in the map, it
     *   is replaced by the new one.
     * @return If the new DOMNode replaces an existing node the
     *   replaced DOMNode is returned,
     *   otherwise null is returned.
     * @exception DOMException
     *   WRONG_DOCUMENT_ERR: Raised if arg was created from a
     *   different document than the one that created the
     *   DOMNamedNodeMap.
     *
NO_MODIFICATION_ALLOWED_ERR: Raised if this
     *   DOMNamedNodeMap is readonly.
     *
INUSE_ATTRIBUTE_ERR: Raised if arg is an
     *   DOMAttr that is already an attribute of another
     *   DOMElement object. The DOM user must explicitly clone
     *   DOMAttr nodes to re-use them in other elements.
     * @since DOM Level 1
     */
    virtual DOMNode   *setNamedItem(DOMNode *arg) = 0;

    // -----------------------------------------------------------------------
    //  Getter methods
    // -----------------------------------------------------------------------
    /**
     * Returns the indexth item in the map.
     *
     * If index
     * is greater than or equal to the number of nodes in the map, this returns
     * null.
     * @param index Index into the map.
     * @return The node at the indexth position in the
     *   DOMNamedNodeMap, or null if that is not a valid
     *   index.
     * @since DOM Level 1
     */
    virtual DOMNode     *item(XMLSize_t index) const = 0;

    /**
     * Retrieves a node specified by name.
     *
     * @param name The nodeName of a node to retrieve.
     * @return A DOMNode (of any type) with the specified nodeName, or
     *   null if it does not identify any node in
     *   the map.
     * @since DOM Level 1
     */
    virtual DOMNode   *getNamedItem(const XMLCh *name) const = 0;

    /**
     * The number of nodes in the map.
     *
     * The range of valid child node indices is
     * 0 to length-1 inclusive.
     * @since DOM Level 1
     */
    virtual XMLSize_t   getLength() const = 0;

    // -----------------------------------------------------------------------
    //  Node methods
    // -----------------------------------------------------------------------
    /**
     * Removes a node specified by name.
     *
     * If the removed node is an
     * DOMAttr with a default value it is immediately replaced.
     * @param name The nodeName of a node to remove.
     * @return The node removed from the map or null if no node
     *   with such a name exists.
     * @exception DOMException
     *   NOT_FOUND_ERR: Raised if there is no node named name in
     *   the map.
     *

     *   NO_MODIFICATION_ALLOWED_ERR: Raised if this DOMNamedNodeMap
     *   is readonly.
     * @since DOM Level 1
     */
    virtual DOMNode    *removeNamedItem(const XMLCh *name) = 0;
    //@}

    /** @name Functions introduced in DOM Level 1 */
    //@{
    /**
     * Retrieves a node specified by local name and namespace URI.
     *
     * @param namespaceURI The namespace URI of
     *    the node to retrieve.
     * @param localName The local name of the node to retrieve.
     * @return A DOMNode (of any type) with the specified
     *    local name and namespace URI, or null if they do not
     *    identify any node in the map.
     * @since DOM Level 2
     */
    virtual DOMNode   *getNamedItemNS(const XMLCh *namespaceURI,
	                                        const XMLCh *localName) const = 0;

    /**
     * Adds a node using its namespaceURI and localName.
     *
     * @param arg A node to store in a named node map. The node will later be
     *       accessible using the value of the namespaceURI and
     *       localName attribute of the node. If a node with those
     *       namespace URI and local name is already present in the map, it is
     *       replaced by the new one.
     * @return If the new DOMNode replaces an existing node the
     *   replaced DOMNode is returned,
     *   otherwise null is returned.
     * @exception DOMException
     *   WRONG_DOCUMENT_ERR: Raised if arg was created from a
     *   different document than the one that created the
     *   DOMNamedNodeMap.
     *
NO_MODIFICATION_ALLOWED_ERR: Raised if this
     *   DOMNamedNodeMap is readonly.
     *
INUSE_ATTRIBUTE_ERR: Raised if arg is an
     *   DOMAttr that is already an attribute of another
     *   DOMElement object. The DOM user must explicitly clone
     *   DOMAttr nodes to re-use them in other elements.
     * @since DOM Level 2
     */
    virtual DOMNode   *setNamedItemNS(DOMNode *arg) = 0;

    /**
     * Removes a node specified by local name and namespace URI.
     *
     * @param namespaceURI The namespace URI of
     *    the node to remove.
     * @param localName The local name of the
     *    node to remove. When this DOMNamedNodeMap contains the
     *    attributes attached to an element, as returned by the attributes
     *    attribute of the DOMNode interface, if the removed
     *    attribute is known to have a default value, an attribute
     *    immediately appears containing the default value
     *    as well as the corresponding namespace URI, local name, and prefix.
     * @return The node removed from the map if a node with such a local name
     *    and namespace URI exists.
     * @exception DOMException
     *   NOT_FOUND_ERR: Raised if there is no node named name in
     *   the map.
     *

     *   NO_MODIFICATION_ALLOWED_ERR: Raised if this DOMNamedNodeMap
     *   is readonly.
     * @since DOM Level 2
     */
    virtual DOMNode     *removeNamedItemNS(const XMLCh *namespaceURI,
	                                          const XMLCh *localName) = 0;
    //@}

};

XERCES_CPP_NAMESPACE_END

#endif

<commit_msg>[Bug 13751] Documentation for DOMNamedNodeMap incorrect.<commit_after>#ifndef DOMNamedNodeMap_HEADER_GUARD_
#define DOMNamedNodeMap_HEADER_GUARD_

/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#include <xercesc/util/XercesDefs.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class DOMNode;

/**
 *  DOMNamedNodeMaps  are used to
 * represent collections of nodes that can be accessed by name.
 *
 * Note that DOMNamedNodeMap does not inherit from DOMNodeList;
 * DOMNamedNodeMaps are not maintained in any particular order.
 * Nodes contained in a DOMNamedNodeMap may
 * also be accessed by an ordinal index, but this is simply to allow
 * convenient enumeration of the contents, and
 * does not imply that the DOM specifies an order to these Nodes.
 *
 * @since DOM Level 1
 */
class CDOM_EXPORT DOMNamedNodeMap {
protected:
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    /** @name Hidden constructors */
    //@{
    DOMNamedNodeMap() {};
    DOMNamedNodeMap(const DOMNamedNodeMap &) {};
    DOMNamedNodeMap & operator = (const DOMNamedNodeMap &) {return *this;};
    //@}

public:
    // -----------------------------------------------------------------------
    //  All constructors are hidden, just the destructor is available
    // -----------------------------------------------------------------------
    /** @name Destructor */
    //@{
    /**
     * Destructor
     *
     */
    virtual ~DOMNamedNodeMap() {};
    //@}

    // -----------------------------------------------------------------------
    //  Virtual DOMNamedNodeMap interface
    // -----------------------------------------------------------------------
    /** @name Functions introduced in DOM Level 1 */
    //@{
    // -----------------------------------------------------------------------
    //  Setter methods
    // -----------------------------------------------------------------------
    /**
     * Adds a node using its nodeName attribute.
     *
     *
As the nodeName attribute is used to derive the name
     * which the node must be stored under, multiple nodes of certain types
     * (those that have a "special" string value) cannot be stored as the names
     * would clash. This is seen as preferable to allowing nodes to be aliased.
     * @param arg A node to store in a named node map. The node will later be
     *   accessible using the value of the nodeName attribute of
     *   the node. If a node with that name is already present in the map, it
     *   is replaced by the new one.
     * @return If the new DOMNode replaces an existing node the
     *   replaced DOMNode is returned,
     *   otherwise null is returned.
     * @exception DOMException
     *   WRONG_DOCUMENT_ERR: Raised if arg was created from a
     *   different document than the one that created the
     *   DOMNamedNodeMap.
     *
NO_MODIFICATION_ALLOWED_ERR: Raised if this
     *   DOMNamedNodeMap is readonly.
     *
INUSE_ATTRIBUTE_ERR: Raised if arg is an
     *   DOMAttr that is already an attribute of another
     *   DOMElement object. The DOM user must explicitly clone
     *   DOMAttr nodes to re-use them in other elements.
     * @since DOM Level 1
     */
    virtual DOMNode   *setNamedItem(DOMNode *arg) = 0;

    // -----------------------------------------------------------------------
    //  Getter methods
    // -----------------------------------------------------------------------
    /**
     * Returns the indexth item in the map.
     *
     * If index
     * is greater than or equal to the number of nodes in the map, this returns
     * null.
     * @param index Index into the map.
     * @return The node at the indexth position in the
     *   DOMNamedNodeMap, or null if that is not a valid
     *   index.
     * @since DOM Level 1
     */
    virtual DOMNode     *item(XMLSize_t index) const = 0;

    /**
     * Retrieves a node specified by name.
     *
     * @param name The nodeName of a node to retrieve.
     * @return A DOMNode (of any type) with the specified nodeName, or
     *   null if it does not identify any node in
     *   the map.
     * @since DOM Level 1
     */
    virtual DOMNode   *getNamedItem(const XMLCh *name) const = 0;

    /**
     * The number of nodes in the map.
     *
     * The range of valid child node indices is
     * 0 to length-1 inclusive.
     * @since DOM Level 1
     */
    virtual XMLSize_t   getLength() const = 0;

    // -----------------------------------------------------------------------
    //  Node methods
    // -----------------------------------------------------------------------
    /**
     * Removes a node specified by name.
     *
     * If the removed node is an
     * DOMAttr with a default value it is immediately replaced.
     * @param name The nodeName of a node to remove.
     * @return The node removed from the map if a node with such a name exists.
     * @exception DOMException
     *   NOT_FOUND_ERR: Raised if there is no node named name in
     *   the map.
     *

     *   NO_MODIFICATION_ALLOWED_ERR: Raised if this DOMNamedNodeMap
     *   is readonly.
     * @since DOM Level 1
     */
    virtual DOMNode    *removeNamedItem(const XMLCh *name) = 0;
    //@}

    /** @name Functions introduced in DOM Level 2 */
    //@{
    /**
     * Retrieves a node specified by local name and namespace URI.
     *
     * @param namespaceURI The namespace URI of
     *    the node to retrieve.
     * @param localName The local name of the node to retrieve.
     * @return A DOMNode (of any type) with the specified
     *    local name and namespace URI, or null if they do not
     *    identify any node in the map.
     * @since DOM Level 2
     */
    virtual DOMNode   *getNamedItemNS(const XMLCh *namespaceURI,
	                                        const XMLCh *localName) const = 0;

    /**
     * Adds a node using its namespaceURI and localName.
     *
     * @param arg A node to store in a named node map. The node will later be
     *       accessible using the value of the namespaceURI and
     *       localName attribute of the node. If a node with those
     *       namespace URI and local name is already present in the map, it is
     *       replaced by the new one.
     * @return If the new DOMNode replaces an existing node the
     *   replaced DOMNode is returned,
     *   otherwise null is returned.
     * @exception DOMException
     *   WRONG_DOCUMENT_ERR: Raised if arg was created from a
     *   different document than the one that created the
     *   DOMNamedNodeMap.
     *
NO_MODIFICATION_ALLOWED_ERR: Raised if this
     *   DOMNamedNodeMap is readonly.
     *
INUSE_ATTRIBUTE_ERR: Raised if arg is an
     *   DOMAttr that is already an attribute of another
     *   DOMElement object. The DOM user must explicitly clone
     *   DOMAttr nodes to re-use them in other elements.
     * @since DOM Level 2
     */
    virtual DOMNode   *setNamedItemNS(DOMNode *arg) = 0;

    /**
     * Removes a node specified by local name and namespace URI.
     *
     * @param namespaceURI The namespace URI of
     *    the node to remove.
     * @param localName The local name of the
     *    node to remove. When this DOMNamedNodeMap contains the
     *    attributes attached to an element, as returned by the attributes
     *    attribute of the DOMNode interface, if the removed
     *    attribute is known to have a default value, an attribute
     *    immediately appears containing the default value
     *    as well as the corresponding namespace URI, local name, and prefix.
     * @return The node removed from the map if a node with such a local name
     *    and namespace URI exists.
     * @exception DOMException
     *   NOT_FOUND_ERR: Raised if there is no node named name in
     *   the map.
     *

     *   NO_MODIFICATION_ALLOWED_ERR: Raised if this DOMNamedNodeMap
     *   is readonly.
     * @since DOM Level 2
     */
    virtual DOMNode     *removeNamedItemNS(const XMLCh *namespaceURI,
	                                          const XMLCh *localName) = 0;
    //@}

};

XERCES_CPP_NAMESPACE_END

#endif

<|endoftext|>


<commit_before>/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2006 Sam Lantinga

    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

    Sam Lantinga
    slouken@libsdl.org
*/
#include "SDL_config.h"

/* Qtopia based framebuffer implementation */

#include <unistd.h>

#include <qapplication.h>
#include <qpe/qpeapplication.h>

#include "SDL_timer.h"

#include "SDL_QWin.h"

extern "C"
{

#include "../SDL_sysvideo.h"
#include "../../events/SDL_events_c.h"
#include "SDL_sysevents_c.h"
#include "SDL_sysmouse_c.h"
#include "SDL_syswm_c.h"
#include "SDL_lowvideo.h"

    //#define QTOPIA_DEBUG
#define QT_HIDDEN_SIZE	32      /* starting hidden window size */

    /* Name of the environment variable used to invert the screen rotation or not:
       Possible values:
       !=0 : Screen is 270 rotated
       0: Screen is 90 rotated */
#define SDL_QT_ROTATION_ENV_NAME "SDL_QT_INVERT_ROTATION"

    /* Initialization/Query functions */
    static int QT_VideoInit(_THIS, SDL_PixelFormat * vformat);
    static SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat * format,
                                   Uint32 flags);
    static SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface * current,
                                        int width, int height, int bpp,
                                        Uint32 flags);
    static void QT_UpdateMouse(_THIS);
    static int QT_SetColors(_THIS, int firstcolor, int ncolors,
                            SDL_Color * colors);
    static void QT_VideoQuit(_THIS);

    /* Hardware surface functions */
    static int QT_AllocHWSurface(_THIS, SDL_Surface * surface);
    static int QT_LockHWSurface(_THIS, SDL_Surface * surface);
    static void QT_UnlockHWSurface(_THIS, SDL_Surface * surface);
    static void QT_FreeHWSurface(_THIS, SDL_Surface * surface);

    static int QT_ToggleFullScreen(_THIS, int fullscreen);

    static int QT_IconifyWindow(_THIS);
    static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode);

    /* FB driver bootstrap functions */

    static int QT_Available(void)
    {
        return (1);
    }

    static void QT_DeleteDevice(SDL_VideoDevice * device)
    {
        SDL_free(device->hidden);
        SDL_free(device);
    }

    static SDL_VideoDevice *QT_CreateDevice(int devindex)
    {
        SDL_VideoDevice *device;

        /* Initialize all variables that we clean on shutdown */
        device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice));
        if (device) {
            SDL_memset(device, 0, (sizeof *device));
            device->hidden = (struct SDL_PrivateVideoData *)
                SDL_malloc((sizeof *device->hidden));
        }
        if ((device == NULL) || (device->hidden == NULL)) {
            SDL_OutOfMemory();
            if (device) {
                SDL_free(device);
            }
            return (0);
        }
        SDL_memset(device->hidden, 0, (sizeof *device->hidden));

        /* Set the function pointers */
        device->VideoInit = QT_VideoInit;
        device->ListModes = QT_ListModes;
        device->SetVideoMode = QT_SetVideoMode;
        device->UpdateMouse = QT_UpdateMouse;
        device->SetColors = QT_SetColors;
        device->UpdateRects = NULL;
        device->VideoQuit = QT_VideoQuit;
        device->AllocHWSurface = QT_AllocHWSurface;
        device->CheckHWBlit = NULL;
        device->FillHWRect = NULL;
        device->SetHWColorKey = NULL;
        device->SetHWAlpha = NULL;
        device->LockHWSurface = QT_LockHWSurface;
        device->UnlockHWSurface = QT_UnlockHWSurface;
        device->FlipHWSurface = NULL;
        device->FreeHWSurface = QT_FreeHWSurface;
        device->SetIcon = NULL;
        device->SetCaption = QT_SetWMCaption;
        device->IconifyWindow = QT_IconifyWindow;
        device->GrabInput = QT_GrabInput;
        device->GetWMInfo = NULL;
        device->FreeWMCursor = QT_FreeWMCursor;
        device->CreateWMCursor = QT_CreateWMCursor;
        device->ShowWMCursor = QT_ShowWMCursor;
        device->WarpWMCursor = QT_WarpWMCursor;
        device->InitOSKeymap = QT_InitOSKeymap;
        device->PumpEvents = QT_PumpEvents;

        device->free = QT_DeleteDevice;
        device->ToggleFullScreen = QT_ToggleFullScreen;

        /* Set the driver flags */
        device->handles_any_size = 0;

        return device;
    }

    VideoBootStrap Qtopia_bootstrap = {
        "qtopia", "Qtopia / QPE graphics",
        QT_Available, QT_CreateDevice
    };

    /* Function to sort the display_list */
    static int CompareModes(const void *A, const void *B)
    {
#if 0
        const display_mode *a = (display_mode *) A;
        const display_mode *b = (display_mode *) B;

        if (a->space == b->space) {
            return ((b->virtual_width * b->virtual_height) -
                    (a->virtual_width * a->virtual_height));
        } else {
            return (ColorSpaceToBitsPerPixel(b->space) -
                    ColorSpaceToBitsPerPixel(a->space));
        }
#endif
        return 0;
    }

    /* Yes, this isn't the fastest it could be, but it works nicely */
    static int QT_AddMode(_THIS, int index, unsigned int w, unsigned int h)
    {
        SDL_Rect *mode;
        int i;
        int next_mode;

        /* Check to see if we already have this mode */
        if (SDL_nummodes[index] > 0) {
            for (i = SDL_nummodes[index] - 1; i >= 0; --i) {
                mode = SDL_modelist[index][i];
                if ((mode->w == w) && (mode->h == h)) {
                    return (0);
                }
            }
        }

        /* Set up the new video mode rectangle */
        mode = (SDL_Rect *) SDL_malloc(sizeof *mode);
        if (mode == NULL) {
            SDL_OutOfMemory();
            return (-1);
        }
        mode->x = 0;
        mode->y = 0;
        mode->w = w;
        mode->h = h;
#ifdef QTOPIA_DEBUG
        fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h,
                index + 1);
#endif

        /* Allocate the new list of modes, and fill in the new mode */
        next_mode = SDL_nummodes[index];
        SDL_modelist[index] = (SDL_Rect **)
            SDL_realloc(SDL_modelist[index],
                        (1 + next_mode + 1) * sizeof(SDL_Rect *));
        if (SDL_modelist[index] == NULL) {
            SDL_OutOfMemory();
            SDL_nummodes[index] = 0;
            SDL_free(mode);
            return (-1);
        }
        SDL_modelist[index][next_mode] = mode;
        SDL_modelist[index][next_mode + 1] = NULL;
        SDL_nummodes[index]++;

        return (0);
    }

    int QT_VideoInit(_THIS, SDL_PixelFormat * vformat)
    {
        /* Initialize the QPE Application  */
        /* Determine the screen depth */
        vformat->BitsPerPixel = QPixmap::defaultDepth();

        // For now we hardcode the current depth because anything else
        // might as well be emulated by SDL rather than by Qtopia.

        QSize desktop_size = qApp->desktop()->size();
        QT_AddMode(_this, ((vformat->BitsPerPixel + 7) / 8) - 1,
                   desktop_size.width(), desktop_size.height());
        QT_AddMode(_this, ((vformat->BitsPerPixel + 7) / 8) - 1,
                   desktop_size.height(), desktop_size.width());

        /* Determine the current screen size */
        this->info.current_w = desktop_size.width();
        this->info.current_h = desktop_size.height();

        /* Create the window / widget */
        SDL_Win = new SDL_QWin(QSize(QT_HIDDEN_SIZE, QT_HIDDEN_SIZE));
        ((QPEApplication *) qApp)->showMainWidget(SDL_Win);
        /* Fill in some window manager capabilities */
        _this->info.wm_available = 0;

        /* We're done! */
        return (0);
    }

    /* We support any dimension at our bit-depth */
    SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags)
    {
        SDL_Rect **modes;

        modes = ((SDL_Rect **) 0);
        if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) {
            modes = SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1];
        } else {
            if (format->BitsPerPixel == _this->screen->format->BitsPerPixel) {
                modes = ((SDL_Rect **) - 1);
            }
        }
        return (modes);
    }

    /* Various screen update functions available */
    static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect * rects);

    static int QT_SetFullScreen(_THIS, SDL_Surface * screen, int fullscreen)
    {
        return -1;
    }

    static int QT_ToggleFullScreen(_THIS, int fullscreen)
    {
        return -1;
    }

    /* FIXME: check return values and cleanup here */
    SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface * current,
                                 int width, int height, int bpp, Uint32 flags)
    {

        QImage *qimage;
        QSize desktop_size = qApp->desktop()->size();

        current->flags = 0;     //SDL_FULLSCREEN; // We always run fullscreen.

        if (width <= desktop_size.width()
            && height <= desktop_size.height()) {
            current->w = desktop_size.width();
            current->h = desktop_size.height();
        } else if (width <= desktop_size.height()
                   && height <= desktop_size.width()) {
            // Landscape mode
            char *envString = SDL_getenv(SDL_QT_ROTATION_ENV_NAME);
            int envValue = envString ? atoi(envString) : 0;
            screenRotation =
                envValue ? SDL_QT_ROTATION_270 : SDL_QT_ROTATION_90;
            current->h = desktop_size.width();
            current->w = desktop_size.height();
        } else {
            SDL_SetError("Unsupported resolution, %dx%d\n", width, height);
        }
        if (flags & SDL_INTERNALOPENGL) {
            SDL_SetError("OpenGL not supported");
            return (NULL);
        }
        /* Create the QImage framebuffer */
        qimage = new QImage(current->w, current->h, bpp);
        if (qimage->isNull()) {
            SDL_SetError("Couldn't create screen bitmap");
            delete qimage;
            return (NULL);
        }
        current->pitch = qimage->bytesPerLine();
        current->pixels = (void *) qimage->bits();
        SDL_Win->setImage(qimage);
        _this->UpdateRects = QT_NormalUpdate;
        SDL_Win->setFullscreen(true);
        /* We're done */
        return (current);
    }

    /* Update the current mouse state and position */
    void QT_UpdateMouse(_THIS)
    {
        QPoint point(-1, -1);
        if (SDL_Win->isActiveWindow()) {
            point = SDL_Win->mousePos();
        }

        if ((point.x() >= 0) && (point.x() < SDL_VideoSurface->w) &&
            (point.y() >= 0) && (point.y() < SDL_VideoSurface->h)) {
            SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
            SDL_PrivateMouseMotion(0, 0,
                                   (Sint16) point.x(), (Sint16) point.y());
        } else {
            SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
        }
    }

    /* We don't actually allow hardware surfaces other than the main one */
    static int QT_AllocHWSurface(_THIS, SDL_Surface * surface)
    {
        return (-1);
    }
    static void QT_FreeHWSurface(_THIS, SDL_Surface * surface)
    {
        return;
    }
    static int QT_LockHWSurface(_THIS, SDL_Surface * surface)
    {
        return (0);
    }
    static void QT_UnlockHWSurface(_THIS, SDL_Surface * surface)
    {
        return;
    }

    static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect * rects)
    {
        if (SDL_Win->lockScreen()) {
            for (int i = 0; i < numrects; ++i) {
                QRect rect(rects[i].x, rects[i].y, rects[i].w, rects[i].h);
                SDL_Win->repaintRect(rect);
            }
            SDL_Win->unlockScreen();
        }
    }
    /* Is the system palette settable? */
    int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors)
    {
        return -1;
    }

    void QT_VideoQuit(_THIS)
    {
        // This is dumb, but if I free this, the app doesn't exit correctly.
        // Of course, this will leak memory if init video is done more than once.
        // Sucks but such is life.

        //    -- David Hedbor
        //    delete SDL_Win;
        //    SDL_Win = 0;
        _this->screen->pixels = NULL;
        QT_GrabInput(_this, SDL_GRAB_OFF);
    }

    static int QT_IconifyWindow(_THIS)
    {
        SDL_Win->hide();

        return true;
    }

    static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode)
    {
        if (mode == SDL_GRAB_OFF) {
            QPEApplication::grabKeyboard();
            qApp->processEvents();
            QPEApplication::ungrabKeyboard();
        } else {
            QPEApplication::grabKeyboard();
        }
        qApp->processEvents();
        return mode;
    }

};                              /* Extern C */

/* vi: set ts=4 sw=4 expandtab: */
<commit_msg>Patch from 1.2 branch...fix compilation on Qtopia video target (reference  Bugzilla #285).<commit_after>/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2006 Sam Lantinga

    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

    Sam Lantinga
    slouken@libsdl.org
*/
#include "SDL_config.h"

/* Qtopia based framebuffer implementation */

#include <unistd.h>

#include <qapplication.h>
#include <qpe/qpeapplication.h>

#include "SDL_timer.h"

#include "SDL_QWin.h"

extern "C"
{

#include "../SDL_sysvideo.h"
#include "../../events/SDL_events_c.h"
#include "SDL_sysevents_c.h"
#include "SDL_sysmouse_c.h"
#include "SDL_syswm_c.h"
#include "SDL_lowvideo.h"

    //#define QTOPIA_DEBUG
#define QT_HIDDEN_SIZE	32      /* starting hidden window size */

    /* Name of the environment variable used to invert the screen rotation or not:
       Possible values:
       !=0 : Screen is 270 rotated
       0: Screen is 90 rotated */
#define SDL_QT_ROTATION_ENV_NAME "SDL_QT_INVERT_ROTATION"

    /* Initialization/Query functions */
    static int QT_VideoInit(_THIS, SDL_PixelFormat * vformat);
    static SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat * format,
                                   Uint32 flags);
    static SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface * current,
                                        int width, int height, int bpp,
                                        Uint32 flags);
    static void QT_UpdateMouse(_THIS);
    static int QT_SetColors(_THIS, int firstcolor, int ncolors,
                            SDL_Color * colors);
    static void QT_VideoQuit(_THIS);

    /* Hardware surface functions */
    static int QT_AllocHWSurface(_THIS, SDL_Surface * surface);
    static int QT_LockHWSurface(_THIS, SDL_Surface * surface);
    static void QT_UnlockHWSurface(_THIS, SDL_Surface * surface);
    static void QT_FreeHWSurface(_THIS, SDL_Surface * surface);

    static int QT_ToggleFullScreen(_THIS, int fullscreen);

    static int QT_IconifyWindow(_THIS);
    static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode);

    /* FB driver bootstrap functions */

    static int QT_Available(void)
    {
        return (1);
    }

    static void QT_DeleteDevice(SDL_VideoDevice * device)
    {
        SDL_free(device->hidden);
        SDL_free(device);
    }

    static SDL_VideoDevice *QT_CreateDevice(int devindex)
    {
        SDL_VideoDevice *device;

        /* Initialize all variables that we clean on shutdown */
        device = (SDL_VideoDevice *) SDL_malloc(sizeof(SDL_VideoDevice));
        if (device) {
            SDL_memset(device, 0, (sizeof *device));
            device->hidden = (struct SDL_PrivateVideoData *)
                SDL_malloc((sizeof *device->hidden));
        }
        if ((device == NULL) || (device->hidden == NULL)) {
            SDL_OutOfMemory();
            if (device) {
                SDL_free(device);
            }
            return (0);
        }
        SDL_memset(device->hidden, 0, (sizeof *device->hidden));

        /* Set the function pointers */
        device->VideoInit = QT_VideoInit;
        device->ListModes = QT_ListModes;
        device->SetVideoMode = QT_SetVideoMode;
        device->UpdateMouse = QT_UpdateMouse;
        device->SetColors = QT_SetColors;
        device->UpdateRects = NULL;
        device->VideoQuit = QT_VideoQuit;
        device->AllocHWSurface = QT_AllocHWSurface;
        device->CheckHWBlit = NULL;
        device->FillHWRect = NULL;
        device->SetHWColorKey = NULL;
        device->SetHWAlpha = NULL;
        device->LockHWSurface = QT_LockHWSurface;
        device->UnlockHWSurface = QT_UnlockHWSurface;
        device->FlipHWSurface = NULL;
        device->FreeHWSurface = QT_FreeHWSurface;
        device->SetIcon = NULL;
        device->SetCaption = QT_SetWMCaption;
        device->IconifyWindow = QT_IconifyWindow;
        device->GrabInput = QT_GrabInput;
        device->GetWMInfo = NULL;
        device->FreeWMCursor = QT_FreeWMCursor;
        device->CreateWMCursor = QT_CreateWMCursor;
        device->ShowWMCursor = QT_ShowWMCursor;
        device->WarpWMCursor = QT_WarpWMCursor;
        device->InitOSKeymap = QT_InitOSKeymap;
        device->PumpEvents = QT_PumpEvents;

        device->free = QT_DeleteDevice;
        device->ToggleFullScreen = QT_ToggleFullScreen;

        /* Set the driver flags */
        device->handles_any_size = 0;

        return device;
    }

    VideoBootStrap Qtopia_bootstrap = {
        "qtopia", "Qtopia / QPE graphics",
        QT_Available, QT_CreateDevice
    };

    /* Function to sort the display_list */
    static int CompareModes(const void *A, const void *B)
    {
#if 0
        const display_mode *a = (display_mode *) A;
        const display_mode *b = (display_mode *) B;

        if (a->space == b->space) {
            return ((b->virtual_width * b->virtual_height) -
                    (a->virtual_width * a->virtual_height));
        } else {
            return (ColorSpaceToBitsPerPixel(b->space) -
                    ColorSpaceToBitsPerPixel(a->space));
        }
#endif
        return 0;
    }

    /* Yes, this isn't the fastest it could be, but it works nicely */
    static int QT_AddMode(_THIS, int index, unsigned int w, unsigned int h)
    {
        SDL_Rect *mode;
        int i;
        int next_mode;

        /* Check to see if we already have this mode */
        if (SDL_nummodes[index] > 0) {
            for (i = SDL_nummodes[index] - 1; i >= 0; --i) {
                mode = SDL_modelist[index][i];
                if ((mode->w == w) && (mode->h == h)) {
                    return (0);
                }
            }
        }

        /* Set up the new video mode rectangle */
        mode = (SDL_Rect *) SDL_malloc(sizeof *mode);
        if (mode == NULL) {
            SDL_OutOfMemory();
            return (-1);
        }
        mode->x = 0;
        mode->y = 0;
        mode->w = w;
        mode->h = h;
#ifdef QTOPIA_DEBUG
        fprintf(stderr, "Adding mode %dx%d at %d bytes per pixel\n", w, h,
                index + 1);
#endif

        /* Allocate the new list of modes, and fill in the new mode */
        next_mode = SDL_nummodes[index];
        SDL_modelist[index] = (SDL_Rect **)
            SDL_realloc(SDL_modelist[index],
                        (1 + next_mode + 1) * sizeof(SDL_Rect *));
        if (SDL_modelist[index] == NULL) {
            SDL_OutOfMemory();
            SDL_nummodes[index] = 0;
            SDL_free(mode);
            return (-1);
        }
        SDL_modelist[index][next_mode] = mode;
        SDL_modelist[index][next_mode + 1] = NULL;
        SDL_nummodes[index]++;

        return (0);
    }

    int QT_VideoInit(_THIS, SDL_PixelFormat * vformat)
    {
        /* Initialize the QPE Application  */
        /* Determine the screen depth */
        vformat->BitsPerPixel = QPixmap::defaultDepth();

        // For now we hardcode the current depth because anything else
        // might as well be emulated by SDL rather than by Qtopia.

        QSize desktop_size = qApp->desktop()->size();
        QT_AddMode(_this, ((vformat->BitsPerPixel + 7) / 8) - 1,
                   desktop_size.width(), desktop_size.height());
        QT_AddMode(_this, ((vformat->BitsPerPixel + 7) / 8) - 1,
                   desktop_size.height(), desktop_size.width());

        /* Determine the current screen size */
        _this->info.current_w = desktop_size.width();
        _this->info.current_h = desktop_size.height();

        /* Create the window / widget */
        SDL_Win = new SDL_QWin(QSize(QT_HIDDEN_SIZE, QT_HIDDEN_SIZE));
        ((QPEApplication *) qApp)->showMainWidget(SDL_Win);
        /* Fill in some window manager capabilities */
        _this->info.wm_available = 0;

        /* We're done! */
        return (0);
    }

    /* We support any dimension at our bit-depth */
    SDL_Rect **QT_ListModes(_THIS, SDL_PixelFormat * format, Uint32 flags)
    {
        SDL_Rect **modes;

        modes = ((SDL_Rect **) 0);
        if ((flags & SDL_FULLSCREEN) == SDL_FULLSCREEN) {
            modes = SDL_modelist[((format->BitsPerPixel + 7) / 8) - 1];
        } else {
            if (format->BitsPerPixel == _this->screen->format->BitsPerPixel) {
                modes = ((SDL_Rect **) - 1);
            }
        }
        return (modes);
    }

    /* Various screen update functions available */
    static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect * rects);

    static int QT_SetFullScreen(_THIS, SDL_Surface * screen, int fullscreen)
    {
        return -1;
    }

    static int QT_ToggleFullScreen(_THIS, int fullscreen)
    {
        return -1;
    }

    /* FIXME: check return values and cleanup here */
    SDL_Surface *QT_SetVideoMode(_THIS, SDL_Surface * current,
                                 int width, int height, int bpp, Uint32 flags)
    {

        QImage *qimage;
        QSize desktop_size = qApp->desktop()->size();

        current->flags = 0;     //SDL_FULLSCREEN; // We always run fullscreen.

        if (width <= desktop_size.width()
            && height <= desktop_size.height()) {
            current->w = desktop_size.width();
            current->h = desktop_size.height();
        } else if (width <= desktop_size.height()
                   && height <= desktop_size.width()) {
            // Landscape mode
            char *envString = SDL_getenv(SDL_QT_ROTATION_ENV_NAME);
            int envValue = envString ? atoi(envString) : 0;
            screenRotation =
                envValue ? SDL_QT_ROTATION_270 : SDL_QT_ROTATION_90;
            current->h = desktop_size.width();
            current->w = desktop_size.height();
        } else {
            SDL_SetError("Unsupported resolution, %dx%d\n", width, height);
        }
        if (flags & SDL_INTERNALOPENGL) {
            SDL_SetError("OpenGL not supported");
            return (NULL);
        }
        /* Create the QImage framebuffer */
        qimage = new QImage(current->w, current->h, bpp);
        if (qimage->isNull()) {
            SDL_SetError("Couldn't create screen bitmap");
            delete qimage;
            return (NULL);
        }
        current->pitch = qimage->bytesPerLine();
        current->pixels = (void *) qimage->bits();
        SDL_Win->setImage(qimage);
        _this->UpdateRects = QT_NormalUpdate;
        SDL_Win->setFullscreen(true);
        /* We're done */
        return (current);
    }

    /* Update the current mouse state and position */
    void QT_UpdateMouse(_THIS)
    {
        QPoint point(-1, -1);
        if (SDL_Win->isActiveWindow()) {
            point = SDL_Win->mousePos();
        }

        if ((point.x() >= 0) && (point.x() < SDL_VideoSurface->w) &&
            (point.y() >= 0) && (point.y() < SDL_VideoSurface->h)) {
            SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
            SDL_PrivateMouseMotion(0, 0,
                                   (Sint16) point.x(), (Sint16) point.y());
        } else {
            SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
        }
    }

    /* We don't actually allow hardware surfaces other than the main one */
    static int QT_AllocHWSurface(_THIS, SDL_Surface * surface)
    {
        return (-1);
    }
    static void QT_FreeHWSurface(_THIS, SDL_Surface * surface)
    {
        return;
    }
    static int QT_LockHWSurface(_THIS, SDL_Surface * surface)
    {
        return (0);
    }
    static void QT_UnlockHWSurface(_THIS, SDL_Surface * surface)
    {
        return;
    }

    static void QT_NormalUpdate(_THIS, int numrects, SDL_Rect * rects)
    {
        if (SDL_Win->lockScreen()) {
            for (int i = 0; i < numrects; ++i) {
                QRect rect(rects[i].x, rects[i].y, rects[i].w, rects[i].h);
                SDL_Win->repaintRect(rect);
            }
            SDL_Win->unlockScreen();
        }
    }
    /* Is the system palette settable? */
    int QT_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color * colors)
    {
        return -1;
    }

    void QT_VideoQuit(_THIS)
    {
        // This is dumb, but if I free this, the app doesn't exit correctly.
        // Of course, this will leak memory if init video is done more than once.
        // Sucks but such is life.

        //    -- David Hedbor
        //    delete SDL_Win;
        //    SDL_Win = 0;
        _this->screen->pixels = NULL;
        QT_GrabInput(_this, SDL_GRAB_OFF);
    }

    static int QT_IconifyWindow(_THIS)
    {
        SDL_Win->hide();

        return true;
    }

    static SDL_GrabMode QT_GrabInput(_THIS, SDL_GrabMode mode)
    {
        if (mode == SDL_GRAB_OFF) {
            QPEApplication::grabKeyboard();
            qApp->processEvents();
            QPEApplication::ungrabKeyboard();
        } else {
            QPEApplication::grabKeyboard();
        }
        qApp->processEvents();
        return mode;
    }

};                              /* Extern C */

/* vi: set ts=4 sw=4 expandtab: */
<|endoftext|>