<commit_before>// $Id$
// -*-C++-*-
// * BeginRiceCopyright *****************************************************
//
// Copyright ((c)) 2002, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express 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 RICE or 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.
//
// ******************************************************* EndRiceCopyright *

//***************************************************************************
//
// File:
//    BloopIRInterface.h
//
// Purpose:
//   A derivation of the IR interface for the ISA (disassembler) class
//   of bloop.
//
//   Note: many stubs still exist.
//
// Description:
//    [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************

#ifndef BloopIRInterface_h
#define BloopIRInterface_h

//************************* System Include Files ****************************

#include <list>
#include <set>

//*************************** User Include Files ****************************

// OpenAnalysis headers.
// Use OA_IRHANDLETYPE_SZ64: size of bfd_vma/Addr
#include <OpenAnalysis/Utils/DGraph.h>
#include <OpenAnalysis/Interface/IRInterface.h>

#include <lib/ISA/ISA.h>
#include <lib/binutils/Instruction.h>
#include <lib/binutils/Procedure.h>
#include <lib/support/String.h>
#include <lib/support/Assertion.h>

//*************************** Forward Declarations ***************************

class BloopIRStmtIterator: public IRStmtIterator {
public:
  BloopIRStmtIterator (Procedure &_p) : pii(_p) {  };
  ~BloopIRStmtIterator () {};

  StmtHandle Current () { return (StmtHandle)(pii.Current()); };
  bool IsValid () { return pii.IsValid(); };
  void operator++ () { ++pii; };
private:
  ProcedureInstructionIterator pii;
};

class BloopIRUseDefIterator: public IRUseDefIterator {
public:
  BloopIRUseDefIterator (Instruction *insn, int uses_or_defs);
  BloopIRUseDefIterator () { BriefAssertion (0); }
  ~BloopIRUseDefIterator () {};

  LeafHandle Current () { return 0; };
  bool IsValid () { return false; };
  void operator++ () {  };
private:
};

//*************************** Forward Declarations ***************************

class BloopIRInterface : public IRInterface {
public:
  BloopIRInterface (Procedure *_p);
  BloopIRInterface () { BriefAssertion(0); }
  ~BloopIRInterface () {}

  //------------------------------
  // General - all statement types
  //------------------------------
  IRStmtType GetStmtType (StmtHandle);
  StmtLabel GetLabel (StmtHandle);

  //------------------------------
  // For procedures, compound statements.
  //------------------------------
  IRStmtIterator *ProcBody(ProcHandle h)
    { BriefAssertion(false); return NULL; }
  IRStmtIterator *GetFirstInCompound (StmtHandle h);

  //------------------------------
  // Loops
  //------------------------------
  IRStmtIterator *LoopBody(StmtHandle h);
  StmtHandle LoopHeader (StmtHandle h);
  bool LoopIterationsDefinedAtEntry (StmtHandle h);
  ExprHandle GetLoopCondition (StmtHandle h);
  StmtHandle GetLoopIncrement (StmtHandle h);

  //------------------------------
  // invariant: a two-way conditional or a multi-way conditional MUST provide
  // provided either a target, or a target label
  //------------------------------

  //------------------------------
  // Structured two-way conditionals
  //------------------------------
  IRStmtIterator *TrueBody (StmtHandle h);
  IRStmtIterator *ElseBody (StmtHandle h);

  //------------------------------
  // Structured multiway conditionals
  //------------------------------
  int NumMultiCases (StmtHandle h);
  // condition for multi body
  ExprHandle GetSMultiCondition (StmtHandle h, int bodyIndex);
  // multi-way beginning expression
  ExprHandle GetMultiExpr (StmtHandle h);
  IRStmtIterator *MultiBody (StmtHandle h, int bodyIndex);
  bool IsBreakImplied (StmtHandle multicond);
  IRStmtIterator *GetMultiCatchall (StmtHandle h);

  //------------------------------
  // Unstructured two-way conditionals:
  //------------------------------
  // two-way branch, loop continue
  StmtLabel  GetTargetLabel (StmtHandle h, int n);
  ExprHandle GetCondition (StmtHandle h);

  //------------------------------
  // Unstructured multi-way conditionals
  //------------------------------
  int NumUMultiTargets (StmtHandle h);
  StmtLabel GetUMultiTargetLabel (StmtHandle h, int targetIndex);
  StmtLabel GetUMultiCatchallLabel (StmtHandle h);
  ExprHandle GetUMultiCondition (StmtHandle h, int targetIndex);

  //------------------------------
  // Special
  //------------------------------
  bool ParallelWithSuccessor(StmtHandle h) { return false; }

  // Given an unstructured branch/jump statement, return the number
  // of delay slots.
  int NumberOfDelaySlots(StmtHandle h);

  //------------------------------
  // Obtain uses and defs
  //------------------------------
  IRProcCallIterator *GetProcCalls(StmtHandle h)
    { BriefAssertion(false); return NULL; }
  IRUseDefIterator *GetUses (StmtHandle h);
  IRUseDefIterator *GetDefs (StmtHandle h);

  //------------------------------
  // Symbol Handles
  //------------------------------
  SymHandle GetProcSymHandle(ProcHandle h) { return (SymHandle)0; }
  SymHandle GetSymHandle (LeafHandle vh) { return (SymHandle)0; }
  const char *GetSymNameFromSymHandle (SymHandle sh) { return "<no-sym>"; }

  //------------------------------
  // Debugging
  //------------------------------
  void PrintLeaf (LeafHandle vh, ostream & os) { };
  void Dump (StmtHandle stmt, ostream& os);

private:
  Procedure *proc;
  std::set<Addr> branchTargetSet;
};

#endif // BloopIRInterface_h
<commit_msg>Coordinate with updates to IRInterface<commit_after>// $Id$
// -*-C++-*-
// * BeginRiceCopyright *****************************************************
//
// Copyright ((c)) 2002, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express 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 RICE or 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.
//
// ******************************************************* EndRiceCopyright *

//***************************************************************************
//
// File:
//    BloopIRInterface.h
//
// Purpose:
//   A derivation of the IR interface for the ISA (disassembler) class
//   of bloop.
//
//   Note: many stubs still exist.
//
// Description:
//    [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************

#ifndef BloopIRInterface_h
#define BloopIRInterface_h

//************************* System Include Files ****************************

#include <list>
#include <set>

//*************************** User Include Files ****************************

// OpenAnalysis headers.
// Use OA_IRHANDLETYPE_SZ64: size of bfd_vma/Addr
#include <OpenAnalysis/Utils/DGraph.h>
#include <OpenAnalysis/Interface/IRInterface.h>

#include <lib/ISA/ISA.h>
#include <lib/binutils/Instruction.h>
#include <lib/binutils/Procedure.h>
#include <lib/support/String.h>
#include <lib/support/Assertion.h>

//*************************** Forward Declarations ***************************

class BloopIRStmtIterator: public IRStmtIterator {
public:
  BloopIRStmtIterator (Procedure &_p) : pii(_p) { }
  ~BloopIRStmtIterator () { }

  StmtHandle Current () { return (StmtHandle)(pii.Current()); }
  bool IsValid () { return pii.IsValid(); }
  void operator++ () { ++pii; }

  void Reset() { pii.Reset(); }

private:
  ProcedureInstructionIterator pii;
};

class BloopIRUseDefIterator: public IRUseDefIterator {
public:
  BloopIRUseDefIterator (Instruction *insn, int uses_or_defs);
  BloopIRUseDefIterator () { BriefAssertion (0); }
  ~BloopIRUseDefIterator () { }

  LeafHandle Current () { return 0; }
  bool IsValid () { return false; }
  void operator++ () { }

  void Reset() { }

private:
};

//*************************** Forward Declarations ***************************

class BloopIRInterface : public IRInterface {
public:
  BloopIRInterface (Procedure *_p);
  BloopIRInterface () { BriefAssertion(0); }
  ~BloopIRInterface () { }

  //--------------------------------------------------------
  // Procedures and call sites
  //--------------------------------------------------------
  IRProcType GetProcType(ProcHandle h)
    { BriefAssertion(0); return ProcType_ILLEGAL; }
  IRStmtIterator *ProcBody(ProcHandle h)
    { BriefAssertion(0); return NULL; }
  IRCallsiteIterator *GetCallsites(StmtHandle h)
    { BriefAssertion(0); return NULL; }
  IRCallsiteParamIterator *GetCallsiteParams(ExprHandle h)
    { BriefAssertion(0); return NULL; }
  bool IsParamProcRef(ExprHandle h)
    { BriefAssertion(0); return false; }
  virtual bool IsCallThruProcParam(ExprHandle h)
    { BriefAssertion(0); return false; }

  //--------------------------------------------------------
  // Statements: General
  //--------------------------------------------------------
  IRStmtType GetStmtType (StmtHandle);
  StmtLabel GetLabel (StmtHandle);
  IRStmtIterator *GetFirstInCompound (StmtHandle h);

  //--------------------------------------------------------
  // Loops
  //--------------------------------------------------------
  IRStmtIterator *LoopBody(StmtHandle h);
  StmtHandle LoopHeader (StmtHandle h);
  bool LoopIterationsDefinedAtEntry (StmtHandle h);
  ExprHandle GetLoopCondition (StmtHandle h);
  StmtHandle GetLoopIncrement (StmtHandle h);

  //--------------------------------------------------------
  // invariant: a two-way conditional or a multi-way conditional MUST provide
  // provided either a target, or a target label
  //--------------------------------------------------------

  //--------------------------------------------------------
  // Structured two-way conditionals
  //--------------------------------------------------------
  IRStmtIterator *TrueBody (StmtHandle h);
  IRStmtIterator *ElseBody (StmtHandle h);

  //--------------------------------------------------------
  // Structured multiway conditionals
  //--------------------------------------------------------
  int NumMultiCases (StmtHandle h);
  // condition for multi body
  ExprHandle GetSMultiCondition (StmtHandle h, int bodyIndex);
  // multi-way beginning expression
  ExprHandle GetMultiExpr (StmtHandle h);
  IRStmtIterator *MultiBody (StmtHandle h, int bodyIndex);
  bool IsBreakImplied (StmtHandle multicond);
  IRStmtIterator *GetMultiCatchall (StmtHandle h);

  //--------------------------------------------------------
  // Unstructured two-way conditionals:
  //--------------------------------------------------------
  // two-way branch, loop continue
  StmtLabel  GetTargetLabel (StmtHandle h, int n);
  ExprHandle GetCondition (StmtHandle h);

  //--------------------------------------------------------
  // Unstructured multi-way conditionals
  //--------------------------------------------------------
  int NumUMultiTargets (StmtHandle h);
  StmtLabel GetUMultiTargetLabel (StmtHandle h, int targetIndex);
  StmtLabel GetUMultiCatchallLabel (StmtHandle h);
  ExprHandle GetUMultiCondition (StmtHandle h, int targetIndex);

  //--------------------------------------------------------
  // Special
  //--------------------------------------------------------
  bool ParallelWithSuccessor(StmtHandle h) { return false; }

  // Given an unstructured branch/jump statement, return the number
  // of delay slots.
  int NumberOfDelaySlots(StmtHandle h);

  //--------------------------------------------------------
  // Obtain uses and defs
  //--------------------------------------------------------
  IRUseDefIterator *GetUses (StmtHandle h);
  IRUseDefIterator *GetDefs (StmtHandle h);

  //--------------------------------------------------------
  // Symbol Handles
  //--------------------------------------------------------
  SymHandle GetProcSymHandle(ProcHandle h)
    { BriefAssertion(0); return (SymHandle)0; }
  SymHandle GetSymHandle (LeafHandle vh) { return (SymHandle)0; }
  const char *GetSymNameFromSymHandle (SymHandle sh) { return "<no-sym>"; }

  //--------------------------------------------------------
  // Debugging
  //--------------------------------------------------------
  void PrintLeaf (LeafHandle vh, ostream & os) { };
  void Dump (StmtHandle stmt, ostream& os);

private:
  Procedure *proc;
  std::set<Addr> branchTargetSet;
};

#endif // BloopIRInterface_h
<|endoftext|>


<commit_before>//========================================================
// Hazi feladat keret.
// A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// sorokon beluli reszben celszeru garazdalkodni, mert
// a tobbit ugyis toroljuk.
// A Hazi feladat csak ebben a fajlban lehet
// Tilos:
// - mast "beincludolni", illetve mas konyvtarat hasznalni
// - faljmuveleteket vegezni
//========================================================

#include <math.h>
#include <stdlib.h>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
// MsWindows-on ez is kell
#include <windows.h>
#else // g++ nem fordit a stanard include-ok nelkul :-/
#include <string.h>
#endif // Win32 platform

#include <GL/gl.h>
#include <GL/glu.h>
// A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/
#include <GL/glut.h>
#include <stdio.h>

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Innentol modosithatod...

//--------------------------------------------------------
// Nev:
// Neptun:
//--------------------------------------------------------

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

class Vector {
public:
	float x, y, z;

	Vector(float x0, float y0, float z0) {
		x = x0;
		y = y0;
		z = z0;
	}

	Vector operator+(const Vector& v) {
		return Vector(x + v.x, y + v.y, z + v.z);
	}

	Vector operator*(float f) {
		return Vector(x * f, y * f, z * f);
	}
};

class Matrix {
public:
	float m[4][4];

	void Clear() {
		memset(&m[0][0], 0, sizeof(m));
	}

	void LoadIdentify() {
		Clear();
		m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1;
	}

	Vector operator*(const Vector& v) {
		float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3];
		float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3];
		float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3];
		float  h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3];

		return Vector(Xh/h, Yh/h, Zh/h);
	}
};

enum {
	NOOP = 0,
	SCALE,
	ROTATE,
	SHIFT
};

int trans_state = NOOP;

// csak mert math.ht nemszabad ;-/
# define M_PI           3.14159265358979323846

const Vector* points[2][7];

Matrix* transs[4];

void onInitialization( ) {
	points[0][0] = new Vector(160, 20, 0);
	points[0][1] = new Vector(250, 80, 0);
	points[0][2] = new Vector(270, 20, 0);
	points[0][3] = new Vector(360, 80, 0);
	points[0][4] = new Vector(390, 20, 0);
	points[0][5] = new Vector(470, 80, 0);
	points[0][6] = new Vector(490, 20, 0);

	points[1][0] = new Vector(160, 120, 0);
	points[1][1] = new Vector(250, 180, 0);
	points[1][2] = new Vector(270, 120, 0);
	points[1][3] = new Vector(360, 180, 0);
	points[1][4] = new Vector(390, 120, 0);
	points[1][5] = new Vector(470, 180, 0);
	points[1][6] = new Vector(490, 120, 0);

	/*
	 * 1 0 0 0
	 * 0 1 0 0
	 * 0 0 1 0
	 * 0 0 0 1
	 */
	transs[NOOP] = new Matrix();
	transs[NOOP]->LoadIdentify();

	/*
	 * 0.5   0   0   0
	 *   0 0.5   0   0
	 *   0   0 0.5   0
	 *   0   0   0   1
	 */
	transs[SCALE] = new Matrix();
	transs[SCALE]->LoadIdentify();
	transs[SCALE]->m[0][0] = 0.5;
	transs[SCALE]->m[1][1] = 0.5;
	transs[SCALE]->m[2][2] = 0.5;

	/*
	 *  cos  sin    0    0
	 * -sin  cos    0    0
	 *    0    0    1    0
	 *    0    0    0    1
	 */
	float angle = M_PI/4;
	transs[ROTATE] = new Matrix();
	transs[ROTATE]->LoadIdentify();
	transs[ROTATE]->m[0][0] = cosf(angle);
	transs[ROTATE]->m[0][1] = -sinf(angle);
	transs[ROTATE]->m[1][0] = sinf(angle);
	transs[ROTATE]->m[1][1] = cosf(angle);

	/*
	 *  1  0  0  0
	 *  0  1  0  0
	 *  0  0  1  0
	 * px py pz  1
	 */
	transs[SHIFT] = new Matrix();
	transs[SHIFT]->LoadIdentify();
	transs[SHIFT]->m[1][3] = 100;
	gluOrtho2D(0., 500., 0., 500.);
}

void onDisplay( ) {
	glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glColor4d(0.9f, 0.8f, 0.7f, 1.0f);

	for (int i = 0; i < ARRAY_SIZE(points); i++) {
		glBegin(GL_LINE_STRIP);
		for (int j = 0; j < ARRAY_SIZE(points[i]); j++) {
			Vector v = *transs[trans_state] * *points[i][j];
			glVertex2d(v.x, v.y);
		}
		glEnd();
	}

	// Buffercsere: rajzolas vege
	glFinish();
	glutSwapBuffers();
}

void onMouse(int button, int state, int x, int y) {
	// A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON
	// ill. a GLUT_DOWN / GLUT_UP makrokat hasznald.
}

void onIdle( ) {
}

void onKeyboard(unsigned char key, int x, int y) {
	if (key == 's')
		trans_state = (trans_state + 1) % 4;
	onDisplay();
}

// ...Idaig modosithatod
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

int main(int argc, char **argv) {
	glutInit(&argc, argv);
	glutInitWindowSize(600, 600);
	glutInitWindowPosition(100, 100);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

	glutCreateWindow("Grafika hazi feladat");

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	onInitialization();

	glutDisplayFunc(onDisplay);
	glutMouseFunc(onMouse);
	glutIdleFunc(onIdle);
	glutKeyboardFunc(onKeyboard);

	glutMainLoop();

	return 0;
}
<commit_msg>nev neptunkod<commit_after>//========================================================
// Hazi feladat keret.
// A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// sorokon beluli reszben celszeru garazdalkodni, mert
// a tobbit ugyis toroljuk.
// A Hazi feladat csak ebben a fajlban lehet
// Tilos:
// - mast "beincludolni", illetve mas konyvtarat hasznalni
// - faljmuveleteket vegezni
//========================================================

#include <math.h>
#include <stdlib.h>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
// MsWindows-on ez is kell
#include <windows.h>
#else // g++ nem fordit a stanard include-ok nelkul :-/
#include <string.h>
#endif // Win32 platform

#include <GL/gl.h>
#include <GL/glu.h>
// A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/
#include <GL/glut.h>
#include <stdio.h>

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Innentol modosithatod...

//--------------------------------------------------------
// Nev: Vajna Miklos
// Neptun: AYU9RZ
//--------------------------------------------------------

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

class Vector {
public:
	float x, y, z;

	Vector(float x0, float y0, float z0) {
		x = x0;
		y = y0;
		z = z0;
	}

	Vector operator+(const Vector& v) {
		return Vector(x + v.x, y + v.y, z + v.z);
	}

	Vector operator*(float f) {
		return Vector(x * f, y * f, z * f);
	}
};

class Matrix {
public:
	float m[4][4];

	void Clear() {
		memset(&m[0][0], 0, sizeof(m));
	}

	void LoadIdentify() {
		Clear();
		m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1;
	}

	Vector operator*(const Vector& v) {
		float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3];
		float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3];
		float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3];
		float  h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3];

		return Vector(Xh/h, Yh/h, Zh/h);
	}
};

enum {
	NOOP = 0,
	SCALE,
	ROTATE,
	SHIFT
};

int trans_state = NOOP;

// csak mert math.ht nemszabad ;-/
# define M_PI           3.14159265358979323846

const Vector* points[2][7];

Matrix* transs[4];

void onInitialization( ) {
	points[0][0] = new Vector(160, 20, 0);
	points[0][1] = new Vector(250, 80, 0);
	points[0][2] = new Vector(270, 20, 0);
	points[0][3] = new Vector(360, 80, 0);
	points[0][4] = new Vector(390, 20, 0);
	points[0][5] = new Vector(470, 80, 0);
	points[0][6] = new Vector(490, 20, 0);

	points[1][0] = new Vector(160, 120, 0);
	points[1][1] = new Vector(250, 180, 0);
	points[1][2] = new Vector(270, 120, 0);
	points[1][3] = new Vector(360, 180, 0);
	points[1][4] = new Vector(390, 120, 0);
	points[1][5] = new Vector(470, 180, 0);
	points[1][6] = new Vector(490, 120, 0);

	/*
	 * 1 0 0 0
	 * 0 1 0 0
	 * 0 0 1 0
	 * 0 0 0 1
	 */
	transs[NOOP] = new Matrix();
	transs[NOOP]->LoadIdentify();

	/*
	 * 0.5   0   0   0
	 *   0 0.5   0   0
	 *   0   0 0.5   0
	 *   0   0   0   1
	 */
	transs[SCALE] = new Matrix();
	transs[SCALE]->LoadIdentify();
	transs[SCALE]->m[0][0] = 0.5;
	transs[SCALE]->m[1][1] = 0.5;
	transs[SCALE]->m[2][2] = 0.5;

	/*
	 *  cos  sin    0    0
	 * -sin  cos    0    0
	 *    0    0    1    0
	 *    0    0    0    1
	 */
	float angle = M_PI/4;
	transs[ROTATE] = new Matrix();
	transs[ROTATE]->LoadIdentify();
	transs[ROTATE]->m[0][0] = cosf(angle);
	transs[ROTATE]->m[0][1] = -sinf(angle);
	transs[ROTATE]->m[1][0] = sinf(angle);
	transs[ROTATE]->m[1][1] = cosf(angle);

	/*
	 *  1  0  0  0
	 *  0  1  0  0
	 *  0  0  1  0
	 * px py pz  1
	 */
	transs[SHIFT] = new Matrix();
	transs[SHIFT]->LoadIdentify();
	transs[SHIFT]->m[1][3] = 100;
	gluOrtho2D(0., 500., 0., 500.);
}

void onDisplay( ) {
	glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glColor4d(0.9f, 0.8f, 0.7f, 1.0f);

	for (int i = 0; i < ARRAY_SIZE(points); i++) {
		glBegin(GL_LINE_STRIP);
		for (int j = 0; j < ARRAY_SIZE(points[i]); j++) {
			Vector v = *transs[trans_state] * *points[i][j];
			glVertex2d(v.x, v.y);
		}
		glEnd();
	}

	// Buffercsere: rajzolas vege
	glFinish();
	glutSwapBuffers();
}

void onMouse(int button, int state, int x, int y) {
	// A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON
	// ill. a GLUT_DOWN / GLUT_UP makrokat hasznald.
}

void onIdle( ) {
}

void onKeyboard(unsigned char key, int x, int y) {
	if (key == 's')
		trans_state = (trans_state + 1) % 4;
	onDisplay();
}

// ...Idaig modosithatod
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

int main(int argc, char **argv) {
	glutInit(&argc, argv);
	glutInitWindowSize(600, 600);
	glutInitWindowPosition(100, 100);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

	glutCreateWindow("Grafika hazi feladat");

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	onInitialization();

	glutDisplayFunc(onDisplay);
	glutMouseFunc(onMouse);
	glutIdleFunc(onIdle);
	glutKeyboardFunc(onKeyboard);

	glutMainLoop();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * expand/include.cpp
 * - include!/include_str!/include_bytes! support
 */
#include <synext_macro.hpp>
#include <synext.hpp>   // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp>    // Lexer (new files)
#include <ast/expr.hpp>
#include <ast/crate.hpp>

namespace {

    ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
    {
        auto n = Parse_ExprVal(lex);
        ASSERT_BUG(sp, n, "No expression returned");
        Expand_BareExpr(crate, mod, n);

        auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
        if( !string_np ) {
            ERROR(sp, E0000, "include! requires a string literal - got " << *n);
        }
        return mv$( string_np->m_value );
    }

    ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
    {
        DEBUG(base_path << ", " << path);
        // Absolute
        if( path[0] == '/' || path[0] == '\\' ) {
            return path;
        }
        // Windows absolute
        else if( isalnum(path[0]) && path[1] == ':' && (path[2] == '/' || path[2] == '\\') ) {
            return path;
        }
        else if( base_path.size() == 0 ) {
            return path;
        }
        else if( base_path.back() == '/' || base_path.back() == '\\' ) {
            return base_path + path;
        }
        else {

            auto slash = ::std::min( base_path.find_last_of('/'), base_path.find_last_of('\\') );
            if( slash == ::std::string::npos )
            {
                return path;
            }
            else
            {
                slash += 1;
                ::std::string   rv;
                rv.reserve( slash + path.size() );
                rv.append( base_path.begin(), base_path.begin() + slash );
                rv.append( path.begin(), path.end() );
                return rv;
            }
        }
    }
};

class CIncludeExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;
        auto lex = TTStream(sp, ParseState(crate.m_edition), tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
        crate.m_extra_files.push_back(file_path);

        try {
            ParseState  ps(crate.m_edition);
            ps.module = &mod;
            return box$( Lexer(file_path, ps) );
        }
        catch(::std::runtime_error& e)
        {
            ERROR(sp, E0000, e.what());
        }
    }
};

class CIncludeBytesExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;
        auto lex = TTStream(sp, ParseState(crate.m_edition), tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
        crate.m_extra_files.push_back(file_path);

        ::std::ifstream is(file_path);
        if( !is.good() ) {
            ERROR(sp, E0000, "Cannot open file " << file_path << " for include_bytes!");
        }
        ::std::stringstream   ss;
        ss << is.rdbuf();

        ::std::vector<TokenTree>    toks;
        toks.push_back(Token(TOK_BYTESTRING, mv$(ss.str())));
        return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );
    }
};

class CIncludeStrExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;
        auto lex = TTStream(sp, ParseState(crate.m_edition), tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
        crate.m_extra_files.push_back(file_path);

        ::std::ifstream is(file_path);
        if( !is.good() ) {
            ERROR(sp, E0000, "Cannot open file " << file_path << " for include_str!");
        }
        ::std::stringstream   ss;
        ss << is.rdbuf();

        ::std::vector<TokenTree>    toks;
        toks.push_back(Token(TOK_STRING, mv$(ss.str())));
        return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );
    }
};

// TODO: include_str! and include_bytes!

STATIC_MACRO("include", CIncludeExpander);
STATIC_MACRO("include_bytes", CIncludeBytesExpander);
STATIC_MACRO("include_str", CIncludeStrExpander);

<commit_msg>Expand include - Relative path logic<commit_after>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * expand/include.cpp
 * - include!/include_str!/include_bytes! support
 */
#include <synext_macro.hpp>
#include <synext.hpp>   // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp>    // Lexer (new files)
#include <ast/expr.hpp>
#include <ast/crate.hpp>

namespace {

    ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
    {
        auto n = Parse_ExprVal(lex);
        ASSERT_BUG(sp, n, "No expression returned");
        Expand_BareExpr(crate, mod, n);

        auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
        if( !string_np ) {
            ERROR(sp, E0000, "include! requires a string literal - got " << *n);
        }
        return mv$( string_np->m_value );
    }

    ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
    {
        DEBUG(base_path << ", " << path);
        // Absolute
        if( path[0] == '/' || path[0] == '\\' ) {
            return path;
        }
        // Windows absolute
        else if( isalnum(path[0]) && path[1] == ':' && (path[2] == '/' || path[2] == '\\') ) {
            return path;
        }
        else if( base_path.size() == 0 ) {
            return path;
        }
        else if( base_path.back() == '/' || base_path.back() == '\\' ) {
            return base_path + path;
        }
        else {

            auto slash_fwd = base_path.find_last_of('/');
            auto slash_back = base_path.find_last_of('\\');
            auto slash =
                slash_fwd == std::string::npos ? slash_back
                : slash_back == std::string::npos ? slash_fwd
                : std::max(slash_fwd, slash_back)
                ;
            if( slash == ::std::string::npos )
            {
                return path;
            }
            else
            {
                DEBUG("> slash = " << slash);
                slash += 1;
                ::std::string   rv;
                rv.reserve( slash + path.size() );
                rv.append( base_path.begin(), base_path.begin() + slash );
                rv.append( path.begin(), path.end() );
                return rv;
            }
        }
    }
};

class CIncludeExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;
        auto lex = TTStream(sp, ParseState(crate.m_edition), tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
        crate.m_extra_files.push_back(file_path);

        try {
            ParseState  ps(crate.m_edition);
            ps.module = &mod;
            return box$( Lexer(file_path, ps) );
        }
        catch(::std::runtime_error& e)
        {
            ERROR(sp, E0000, e.what());
        }
    }
};

class CIncludeBytesExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;
        auto lex = TTStream(sp, ParseState(crate.m_edition), tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
        crate.m_extra_files.push_back(file_path);

        ::std::ifstream is(file_path);
        if( !is.good() ) {
            ERROR(sp, E0000, "Cannot open file " << file_path << " for include_bytes!");
        }
        ::std::stringstream   ss;
        ss << is.rdbuf();

        ::std::vector<TokenTree>    toks;
        toks.push_back(Token(TOK_BYTESTRING, mv$(ss.str())));
        return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );
    }
};

class CIncludeStrExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;
        auto lex = TTStream(sp, ParseState(crate.m_edition), tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));
        crate.m_extra_files.push_back(file_path);

        ::std::ifstream is(file_path);
        if( !is.good() ) {
            ERROR(sp, E0000, "Cannot open file " << file_path << " for include_str!");
        }
        ::std::stringstream   ss;
        ss << is.rdbuf();

        ::std::vector<TokenTree>    toks;
        toks.push_back(Token(TOK_STRING, mv$(ss.str())));
        return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) );
    }
};

// TODO: include_str! and include_bytes!

STATIC_MACRO("include", CIncludeExpander);
STATIC_MACRO("include_bytes", CIncludeBytesExpander);
STATIC_MACRO("include_str", CIncludeStrExpander);

<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * 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.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/

#include <fclaw2d_global.h>

#include <fclaw2d_regrid.h>
#include <fclaw2d_ghost_fill.h>
#include <fclaw_timer.h>

#include <fclaw2d_forestclaw.h>
#include <fclaw2d_partition.h>
#include <fclaw2d_exchange.h>
#include <fclaw2d_vtable.h>
#include <fclaw2d_clawpatch.h>

#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif

/* This is also called from fclaw2d_initialize, so is not made static */
void cb_fclaw2d_regrid_tag4refinement(fclaw2d_domain_t *domain,
                                      fclaw2d_patch_t *this_patch,
                                      int this_block_idx,
                                      int this_patch_idx,
                                      void *user)
{
    fclaw2d_vtable_t vt;
    int refine_patch, maxlevel, level;
    const amr_options_t* gparms;

    int domain_init = *((int*) user);

    vt = fclaw2d_get_vtable(domain);
    gparms = get_domain_parms(domain);

    maxlevel = gparms->maxlevel;
    level = this_patch->level;

    if (level < maxlevel)
    {
        refine_patch  =
            vt.regrid_tag4refinement(domain,this_patch,this_block_idx,
                                    this_patch_idx, domain_init);
        if (refine_patch == 1)
        {
            fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx);
        }
    }
}

/* Tag family for coarsening */
static
void cb_regrid_tag4coarsening(fclaw2d_domain_t *domain,
                              fclaw2d_patch_t *fine_patches,
                              int blockno, int fine0_patchno,
                              void *user)
{
    const amr_options_t *gparms = get_domain_parms(domain);
    fclaw2d_vtable_t vt;
    vt = fclaw2d_get_vtable(domain);

    int minlevel = gparms->minlevel;

    int level = fine_patches[0].level;

    if (level > minlevel)
    {
        int family_coarsened = 1;
        family_coarsened = vt.regrid_tag4coarsening(domain,&fine_patches[0],
                                                  blockno, fine0_patchno);
        if (family_coarsened == 1)
        {
            for (int igrid = 0; igrid < NumSiblings; igrid++)
            {
                int fine_patchno = fine0_patchno + igrid;
                fclaw2d_patch_mark_coarsen(domain,blockno, fine_patchno);
            }
        }
    }
}

/* ----------------------------------------------------------------
   Public interface
   -------------------------------------------------------------- */

void cb_fclaw2d_regrid_repopulate(fclaw2d_domain_t * old_domain,
                                  fclaw2d_patch_t * old_patch,
                                  fclaw2d_domain_t * new_domain,
                                  fclaw2d_patch_t * new_patch,
                                  fclaw2d_patch_relation_t newsize,
                                  int blockno,
                                  int old_patchno,
                                  int new_patchno,
                                  void *user)
{
    fclaw2d_vtable_t vt;
    vt = fclaw2d_get_vtable(new_domain);

    int domain_init = *((int*) user);

    fclaw2d_domain_data_t *ddata_old = fclaw2d_domain_get_data (old_domain);
    fclaw2d_domain_data_t *ddata_new = fclaw2d_domain_get_data (new_domain);
    fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;

    if (newsize == FCLAW2D_PATCH_SAMESIZE)
    {
        new_patch->user = old_patch->user;
        old_patch->user = NULL;
        ++ddata_old->count_delete_clawpatch;
        ++ddata_new->count_set_clawpatch;
#if 0
        fclaw2d_clawpatch_initialize_after_regrid(new_domain,
                                                  new_patch,
                                                  blockno,
                                                  new_patchno);
#endif
    }
    else if (newsize == FCLAW2D_PATCH_HALFSIZE)
    {
        fclaw2d_patch_t *fine_siblings = new_patch;
        fclaw2d_patch_t *coarse_patch = old_patch;

        for (int i = 0; i < NumSiblings; i++)
        {
            fclaw2d_patch_t *fine_patch = &fine_siblings[i];
            int fine_patchno = new_patchno + i;
            fclaw2d_patch_data_new(new_domain,fine_patch);
            fclaw2d_clawpatch_build(new_domain,fine_patch,blockno,
                                    fine_patchno,(void*) &build_mode);
            if (domain_init)
            {
                vt.patch_initialize(new_domain,fine_patch,blockno,fine_patchno);
            }
        }

        if (!domain_init)
        {
            int coarse_patchno = old_patchno;
            int fine_patchno = new_patchno;

            vt.regrid_interpolate2fine(new_domain,coarse_patch,fine_siblings,
                                      blockno,coarse_patchno,fine_patchno);
        }
        fclaw2d_patch_data_delete(old_domain,coarse_patch);
    }
    else if (newsize == FCLAW2D_PATCH_DOUBLESIZE)
    {
        if (domain_init)
        {
            fclaw_debugf("fclaw2d_regrid.cpp (repopulate): We shouldn't end up here\n");
            exit(0);
        }

        /* Old grids are the finer grids;  new grid is the coarsened grid */
        fclaw2d_patch_t *fine_siblings = old_patch;
        int fine_patchno = old_patchno;

        fclaw2d_patch_t *coarse_patch = new_patch;
        int coarse_patchno = new_patchno;
        fclaw2d_patch_data_new(new_domain,coarse_patch);

        /* Area (and possibly other things) should be averaged to coarse grid. */
        fclaw2d_clawpatch_build_from_fine(new_domain,fine_siblings,coarse_patch,
                                          blockno,coarse_patchno,fine_patchno,
                                          build_mode);

        /* Average the solution. Does this need to be customizable? */
        vt.regrid_average2coarse(new_domain,fine_siblings,coarse_patch,
                                blockno,coarse_patchno, fine_patchno);

        for(int i = 0; i < 4; i++)
        {
            fclaw2d_patch_t* fine_patch = &fine_siblings[i];
            fclaw2d_patch_data_delete(old_domain,fine_patch);
        }
    }
    else
    {
        fclaw_global_essentialf("cb_adapt_domain : newsize not recognized\n");
        exit(1);
    }
}

/* ----------------------------------------------------------------
   Public interface
   -------------------------------------------------------------- */
void fclaw2d_regrid(fclaw2d_domain_t **domain)
{
    fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain);
    fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]);

    fclaw_global_infof("Regridding domain\n");

    /* First determine which families should be coarsened. */
    fclaw2d_domain_iterate_families(*domain, cb_regrid_tag4coarsening,
                                    (void*) NULL);

    int domain_init = 0;
    fclaw2d_domain_iterate_patches(*domain, cb_fclaw2d_regrid_tag4refinement,
                                   (void *) &domain_init);

    /* Rebuild domain if necessary */
    /* Will return be NULL if no refining was done */
    fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);
    fclaw_bool have_new_refinement = new_domain != NULL;

    /* Domain data may go out of scope now. */
    ddata = NULL;

    if (have_new_refinement)
    {
        fclaw_global_infof(" -- Have new refinement\n");

        /* allocate memory for user patch data and user domain data in the new
           domain;  copy data from the old to new the domain. */
        fclaw2d_domain_setup(*domain, new_domain);
        ddata = fclaw2d_domain_get_data(new_domain);

        /* Average to new coarse grids and interpolate to new fine grids */
        fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);
        fclaw2d_domain_iterate_adapted(*domain, new_domain,
                                       cb_fclaw2d_regrid_repopulate,
                                       (void *) &domain_init);
        fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);

        /* free memory associated with old domain */
        fclaw2d_domain_reset(domain);
        *domain = new_domain;
        new_domain = NULL;

        /* Repartition for load balancing.  Second arg (mode) for vtk output */
        fclaw2d_partition_domain(domain, -1);

        /* Need a new timer */
        ddata = fclaw2d_domain_get_data(*domain);

        /* Set up ghost patches. No parallel communication is done here */
        fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);
        fclaw2d_exchange_setup(*domain);
        fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);

        /* Update ghost cells.  This is needed because we have new coarse or fine
           patches without valid ghost cells.   Time_interp = 0, since we only
           only regrid when all levels are time synchronized. */
        int minlevel = (*domain)->global_minlevel;
        int maxlevel = (*domain)->global_maxlevel;
        int time_interp = 0;
        double sync_time = fclaw2d_domain_get_time(*domain);
        fclaw2d_ghost_update(*domain,
                             minlevel,
                             maxlevel,
                             sync_time,
                             time_interp,
                             FCLAW2D_TIMER_REGRID);
    }
    else
    {
#if 0
        /* We updated all the ghost cells when leaving advance, so don't need to do
           it here */
        /* Set up ghost patches. No parallel communication is done here */
        fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);
        fclaw2d_exchange_setup(*domain);
        fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);
#endif
    }

    /* Stop timer */
    ddata = fclaw2d_domain_get_data(*domain);
    fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]);

    /* Count calls to this function */
    ++ddata->count_amr_regrid;
}

#ifdef __cplusplus
#if 0
{
#endif
}
#endif
<commit_msg>Adding timer around grid adaption<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * 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.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*/

#include <fclaw2d_global.h>

#include <fclaw2d_regrid.h>
#include <fclaw2d_ghost_fill.h>
#include <fclaw_timer.h>

#include <fclaw2d_forestclaw.h>
#include <fclaw2d_partition.h>
#include <fclaw2d_exchange.h>
#include <fclaw2d_vtable.h>
#include <fclaw2d_clawpatch.h>

#ifdef __cplusplus
extern "C"
{
#if 0
}
#endif
#endif

/* This is also called from fclaw2d_initialize, so is not made static */
void cb_fclaw2d_regrid_tag4refinement(fclaw2d_domain_t *domain,
                                      fclaw2d_patch_t *this_patch,
                                      int this_block_idx,
                                      int this_patch_idx,
                                      void *user)
{
    fclaw2d_vtable_t vt;
    int refine_patch, maxlevel, level;
    const amr_options_t* gparms;

    int domain_init = *((int*) user);

    vt = fclaw2d_get_vtable(domain);
    gparms = get_domain_parms(domain);

    maxlevel = gparms->maxlevel;
    level = this_patch->level;

    if (level < maxlevel)
    {
        refine_patch  =
            vt.regrid_tag4refinement(domain,this_patch,this_block_idx,
                                    this_patch_idx, domain_init);
        if (refine_patch == 1)
        {
            fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx);
        }
    }
}

/* Tag family for coarsening */
static
void cb_regrid_tag4coarsening(fclaw2d_domain_t *domain,
                              fclaw2d_patch_t *fine_patches,
                              int blockno, int fine0_patchno,
                              void *user)
{
    const amr_options_t *gparms = get_domain_parms(domain);
    fclaw2d_vtable_t vt;
    vt = fclaw2d_get_vtable(domain);

    int minlevel = gparms->minlevel;

    int level = fine_patches[0].level;

    if (level > minlevel)
    {
        int family_coarsened = 1;
        family_coarsened = vt.regrid_tag4coarsening(domain,&fine_patches[0],
                                                  blockno, fine0_patchno);
        if (family_coarsened == 1)
        {
            for (int igrid = 0; igrid < NumSiblings; igrid++)
            {
                int fine_patchno = fine0_patchno + igrid;
                fclaw2d_patch_mark_coarsen(domain,blockno, fine_patchno);
            }
        }
    }
}

/* ----------------------------------------------------------------
   Public interface
   -------------------------------------------------------------- */

void cb_fclaw2d_regrid_repopulate(fclaw2d_domain_t * old_domain,
                                  fclaw2d_patch_t * old_patch,
                                  fclaw2d_domain_t * new_domain,
                                  fclaw2d_patch_t * new_patch,
                                  fclaw2d_patch_relation_t newsize,
                                  int blockno,
                                  int old_patchno,
                                  int new_patchno,
                                  void *user)
{
    fclaw2d_vtable_t vt;
    vt = fclaw2d_get_vtable(new_domain);

    int domain_init = *((int*) user);

    fclaw2d_domain_data_t *ddata_old = fclaw2d_domain_get_data (old_domain);
    fclaw2d_domain_data_t *ddata_new = fclaw2d_domain_get_data (new_domain);
    fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;

    if (newsize == FCLAW2D_PATCH_SAMESIZE)
    {
        new_patch->user = old_patch->user;
        old_patch->user = NULL;
        ++ddata_old->count_delete_clawpatch;
        ++ddata_new->count_set_clawpatch;
#if 0
        fclaw2d_clawpatch_initialize_after_regrid(new_domain,
                                                  new_patch,
                                                  blockno,
                                                  new_patchno);
#endif
    }
    else if (newsize == FCLAW2D_PATCH_HALFSIZE)
    {
        fclaw2d_patch_t *fine_siblings = new_patch;
        fclaw2d_patch_t *coarse_patch = old_patch;

        for (int i = 0; i < NumSiblings; i++)
        {
            fclaw2d_patch_t *fine_patch = &fine_siblings[i];
            int fine_patchno = new_patchno + i;
            fclaw2d_patch_data_new(new_domain,fine_patch);
            fclaw2d_clawpatch_build(new_domain,fine_patch,blockno,
                                    fine_patchno,(void*) &build_mode);
            if (domain_init)
            {
                vt.patch_initialize(new_domain,fine_patch,blockno,fine_patchno);
            }
        }

        if (!domain_init)
        {
            int coarse_patchno = old_patchno;
            int fine_patchno = new_patchno;

            vt.regrid_interpolate2fine(new_domain,coarse_patch,fine_siblings,
                                      blockno,coarse_patchno,fine_patchno);
        }
        fclaw2d_patch_data_delete(old_domain,coarse_patch);
    }
    else if (newsize == FCLAW2D_PATCH_DOUBLESIZE)
    {
        if (domain_init)
        {
            fclaw_debugf("fclaw2d_regrid.cpp (repopulate): We shouldn't end up here\n");
            exit(0);
        }

        /* Old grids are the finer grids;  new grid is the coarsened grid */
        fclaw2d_patch_t *fine_siblings = old_patch;
        int fine_patchno = old_patchno;

        fclaw2d_patch_t *coarse_patch = new_patch;
        int coarse_patchno = new_patchno;
        fclaw2d_patch_data_new(new_domain,coarse_patch);

        /* Area (and possibly other things) should be averaged to coarse grid. */
        fclaw2d_clawpatch_build_from_fine(new_domain,fine_siblings,coarse_patch,
                                          blockno,coarse_patchno,fine_patchno,
                                          build_mode);

        /* Average the solution. Does this need to be customizable? */
        vt.regrid_average2coarse(new_domain,fine_siblings,coarse_patch,
                                blockno,coarse_patchno, fine_patchno);

        for(int i = 0; i < 4; i++)
        {
            fclaw2d_patch_t* fine_patch = &fine_siblings[i];
            fclaw2d_patch_data_delete(old_domain,fine_patch);
        }
    }
    else
    {
        fclaw_global_essentialf("cb_adapt_domain : newsize not recognized\n");
        exit(1);
    }
}

/* ----------------------------------------------------------------
   Public interface
   -------------------------------------------------------------- */
void fclaw2d_regrid(fclaw2d_domain_t **domain)
{
    fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain);
    fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]);

    fclaw_global_infof("Regridding domain\n");

    /* First determine which families should be coarsened. */
    fclaw2d_domain_iterate_families(*domain, cb_regrid_tag4coarsening,
                                    (void*) NULL);

    int domain_init = 0;
    fclaw2d_domain_iterate_patches(*domain, cb_fclaw2d_regrid_tag4refinement,
                                   (void *) &domain_init);

    /* Rebuild domain if necessary */
    /* Will return be NULL if no refining was done */
    fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_EXTRA4]);
    fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);
    fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_EXTRA4]);
    fclaw_bool have_new_refinement = new_domain != NULL;

    /* Domain data may go out of scope now. */
    ddata = NULL;

    if (have_new_refinement)
    {
        fclaw_global_essentialf("-----> We should not be here\n");
        exit(0);
        fclaw_global_infof(" -- Have new refinement\n");

        /* allocate memory for user patch data and user domain data in the new
           domain;  copy data from the old to new the domain. */
        fclaw2d_domain_setup(*domain, new_domain);
        ddata = fclaw2d_domain_get_data(new_domain);

        /* Average to new coarse grids and interpolate to new fine grids */
        fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);
        fclaw2d_domain_iterate_adapted(*domain, new_domain,
                                       cb_fclaw2d_regrid_repopulate,
                                       (void *) &domain_init);
        fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]);

        /* free memory associated with old domain */
        fclaw2d_domain_reset(domain);
        *domain = new_domain;
        new_domain = NULL;

        /* Repartition for load balancing.  Second arg (mode) for vtk output */
        fclaw2d_partition_domain(domain, -1);

        /* Need a new timer */
        ddata = fclaw2d_domain_get_data(*domain);

        /* Set up ghost patches. No parallel communication is done here */
        fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);
        fclaw2d_exchange_setup(*domain);
        fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);

        /* Update ghost cells.  This is needed because we have new coarse or fine
           patches without valid ghost cells.   Time_interp = 0, since we only
           only regrid when all levels are time synchronized. */
        int minlevel = (*domain)->global_minlevel;
        int maxlevel = (*domain)->global_maxlevel;
        int time_interp = 0;
        double sync_time = fclaw2d_domain_get_time(*domain);
        fclaw2d_ghost_update(*domain,
                             minlevel,
                             maxlevel,
                             sync_time,
                             time_interp,
                             FCLAW2D_TIMER_REGRID);
    }
    else
    {
#if 0
        /* We updated all the ghost cells when leaving advance, so don't need to do
           it here */
        /* Set up ghost patches. No parallel communication is done here */
        fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);
        fclaw2d_exchange_setup(*domain);
        fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]);
#endif
    }

    /* Stop timer */
    ddata = fclaw2d_domain_get_data(*domain);
    fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]);

    /* Count calls to this function */
    ++ddata->count_amr_regrid;
}

#ifdef __cplusplus
#if 0
{
#endif
}
#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <dali/public-api/dali-core.h>
#include <dali-test-suite-utils.h>

using namespace Dali;

void utc_dali_resource_image_startup(void)
{
  test_return_value = TET_UNDEF;
}

void utc_dali_resource_image_cleanup(void)
{
  test_return_value = TET_PASS;
}

static const char* gTestImageFilename = "icon_wrt.png";

namespace
{

void LoadBitmapResource(TestPlatformAbstraction& platform)
{
  Integration::ResourceRequest* request = platform.GetRequest();
  Integration::Bitmap* bitmap = Integration::Bitmap::New( Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD );
  Integration::ResourcePointer resource(bitmap);
  bitmap->GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGBA8888, 80, 80, 80, 80);

  if(request)
  {
    platform.SetResourceLoaded(request->GetId(), request->GetType()->id, resource);
  }
}

} // namespace

// 1.1
int UtcDaliResourceImageNew01(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageNew01 - ResourceImage::New(const std::string&)");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename);

  DALI_TEST_CHECK( image );
  END_TEST;
}

// 1.2
int UtcDaliResourceImageNew02(void)
{
  TestApplication application;

  tet_infoline("UtcDaliREsourceImageNew02 - ResourceImage New( const std::string& url, ImageDimensions size, FittingMode scalingMode, SamplingMode samplingMode, bool orientationCorrection = true )");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename, ImageDimensions( 128, 256 ), FittingMode::FIT_HEIGHT );

  DALI_TEST_CHECK( image );
  END_TEST;
}

// 1.7
int UtcDaliResourceImageDownCast(void)
{
  TestApplication application;
  tet_infoline("Testing Dali::ResourceImage::DownCast()");

  ResourceImage image = ResourceImage::New(gTestImageFilename);

  BaseHandle object(image);

  ResourceImage image2 = ResourceImage::DownCast(object);
  DALI_TEST_CHECK(image2);

  ResourceImage image3 = DownCast< ResourceImage >(object);
  DALI_TEST_CHECK(image3);

  BaseHandle unInitializedObject;
  ResourceImage image4 = ResourceImage::DownCast(unInitializedObject);
  DALI_TEST_CHECK(!image4);

  ResourceImage image5 = DownCast< ResourceImage >(unInitializedObject);
  DALI_TEST_CHECK(!image5);

  Image image6 = ResourceImage::New(gTestImageFilename);
  ResourceImage image7 = ResourceImage::DownCast(image6);
  DALI_TEST_CHECK(image7);
  END_TEST;
}

// 1.8
int UtcDaliResourceImageGetImageSize(void)
{
  TestApplication application;
  TestPlatformAbstraction& platform = application.GetPlatform();

  tet_infoline("UtcDaliResourceImageGetImageSize - ResourceImage::GetImageSize()");

  Vector2 testSize(8.0f, 16.0f);
  platform.SetClosestImageSize(testSize);

  const ImageDimensions size = ResourceImage::GetImageSize(gTestImageFilename);

  DALI_TEST_CHECK( application.GetPlatform().GetTrace().FindMethod("GetClosestImageSize"));
  DALI_TEST_EQUALS( Vector2( size.GetX(), size.GetY() ), testSize, TEST_LOCATION);
  END_TEST;
}

// 1.9
int UtcDaliResourceImageGetUrl(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageGetFilename - ResourceImage::GetUrl()");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename);

  DALI_TEST_EQUALS( image.GetUrl(), gTestImageFilename, TEST_LOCATION);
  END_TEST;
}

// 1.10
int UtcDaliResourceImageGetLoadingState01(void)
{
  TestApplication application;
  tet_infoline("UtcDaliResourceImageGetLoadingState01");

  ResourceImage image = ResourceImage::New(gTestImageFilename);
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);

  // simulate load success
  PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );
  image.Reload();

  // Test state == ResourceLoadingSucceeded
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);
  END_TEST;
}

// 1.11
int UtcDaliResourceImageGetLoadingState02(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageGetLoadingState02");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename);

  // Test state == ResourceLoadingFailed
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);

  PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );
  image.Reload();

  // Test state == ResourceLoadingFailed
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);
  END_TEST;
}

static bool SignalLoadFlag = false;

static void SignalLoadHandler(ResourceImage image)
{
  tet_infoline("Received image load finished signal");

  SignalLoadFlag = true;
}

// 1.13
int UtcDaliResourceImageSignalLoadingFinished(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageSignalLoadingFinished");

  SignalLoadFlag = false;

  PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );
  ResourceImage image = ResourceImage::New(gTestImageFilename);

  image.LoadingFinishedSignal().Connect( SignalLoadHandler );
  image.Reload();
  application.SendNotification();
  application.Render(16);

  Integration::ResourceRequest* request = application.GetPlatform().GetRequest();
  if(request)
  {
    application.GetPlatform().SetResourceLoaded(request->GetId(), request->GetType()->id, Integration::ResourcePointer(Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD)));
  }

  application.Render(16);
  application.SendNotification();

  DALI_TEST_CHECK( SignalLoadFlag == true );
  END_TEST;
}
<commit_msg>(GCC 6.2) Remove unused functions from automated tests<commit_after>/*
 * Copyright (c) 2017 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include <algorithm>
#include <stdlib.h>
#include <dali/public-api/dali-core.h>
#include <dali-test-suite-utils.h>

using namespace Dali;

void utc_dali_resource_image_startup(void)
{
  test_return_value = TET_UNDEF;
}

void utc_dali_resource_image_cleanup(void)
{
  test_return_value = TET_PASS;
}

namespace
{
const char* gTestImageFilename = "icon_wrt.png";
} // unnamed namespace

// 1.1
int UtcDaliResourceImageNew01(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageNew01 - ResourceImage::New(const std::string&)");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename);

  DALI_TEST_CHECK( image );
  END_TEST;
}

// 1.2
int UtcDaliResourceImageNew02(void)
{
  TestApplication application;

  tet_infoline("UtcDaliREsourceImageNew02 - ResourceImage New( const std::string& url, ImageDimensions size, FittingMode scalingMode, SamplingMode samplingMode, bool orientationCorrection = true )");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename, ImageDimensions( 128, 256 ), FittingMode::FIT_HEIGHT );

  DALI_TEST_CHECK( image );
  END_TEST;
}

// 1.7
int UtcDaliResourceImageDownCast(void)
{
  TestApplication application;
  tet_infoline("Testing Dali::ResourceImage::DownCast()");

  ResourceImage image = ResourceImage::New(gTestImageFilename);

  BaseHandle object(image);

  ResourceImage image2 = ResourceImage::DownCast(object);
  DALI_TEST_CHECK(image2);

  ResourceImage image3 = DownCast< ResourceImage >(object);
  DALI_TEST_CHECK(image3);

  BaseHandle unInitializedObject;
  ResourceImage image4 = ResourceImage::DownCast(unInitializedObject);
  DALI_TEST_CHECK(!image4);

  ResourceImage image5 = DownCast< ResourceImage >(unInitializedObject);
  DALI_TEST_CHECK(!image5);

  Image image6 = ResourceImage::New(gTestImageFilename);
  ResourceImage image7 = ResourceImage::DownCast(image6);
  DALI_TEST_CHECK(image7);
  END_TEST;
}

// 1.8
int UtcDaliResourceImageGetImageSize(void)
{
  TestApplication application;
  TestPlatformAbstraction& platform = application.GetPlatform();

  tet_infoline("UtcDaliResourceImageGetImageSize - ResourceImage::GetImageSize()");

  Vector2 testSize(8.0f, 16.0f);
  platform.SetClosestImageSize(testSize);

  const ImageDimensions size = ResourceImage::GetImageSize(gTestImageFilename);

  DALI_TEST_CHECK( application.GetPlatform().GetTrace().FindMethod("GetClosestImageSize"));
  DALI_TEST_EQUALS( Vector2( size.GetX(), size.GetY() ), testSize, TEST_LOCATION);
  END_TEST;
}

// 1.9
int UtcDaliResourceImageGetUrl(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageGetFilename - ResourceImage::GetUrl()");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename);

  DALI_TEST_EQUALS( image.GetUrl(), gTestImageFilename, TEST_LOCATION);
  END_TEST;
}

// 1.10
int UtcDaliResourceImageGetLoadingState01(void)
{
  TestApplication application;
  tet_infoline("UtcDaliResourceImageGetLoadingState01");

  ResourceImage image = ResourceImage::New(gTestImageFilename);
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);

  // simulate load success
  PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );
  image.Reload();

  // Test state == ResourceLoadingSucceeded
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);
  END_TEST;
}

// 1.11
int UtcDaliResourceImageGetLoadingState02(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageGetLoadingState02");

  // invoke default handle constructor
  ResourceImage image;

  DALI_TEST_CHECK( !image );

  // initialise handle
  image = ResourceImage::New(gTestImageFilename);

  // Test state == ResourceLoadingFailed
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed);

  PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );
  image.Reload();

  // Test state == ResourceLoadingFailed
  DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded);
  END_TEST;
}

static bool SignalLoadFlag = false;

static void SignalLoadHandler(ResourceImage image)
{
  tet_infoline("Received image load finished signal");

  SignalLoadFlag = true;
}

// 1.13
int UtcDaliResourceImageSignalLoadingFinished(void)
{
  TestApplication application;

  tet_infoline("UtcDaliResourceImageSignalLoadingFinished");

  SignalLoadFlag = false;

  PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 );
  ResourceImage image = ResourceImage::New(gTestImageFilename);

  image.LoadingFinishedSignal().Connect( SignalLoadHandler );
  image.Reload();
  application.SendNotification();
  application.Render(16);

  Integration::ResourceRequest* request = application.GetPlatform().GetRequest();
  if(request)
  {
    application.GetPlatform().SetResourceLoaded(request->GetId(), request->GetType()->id, Integration::ResourcePointer(Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD)));
  }

  application.Render(16);
  application.SendNotification();

  DALI_TEST_CHECK( SignalLoadFlag == true );
  END_TEST;
}
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CFunctionDB.cpp,v $
//   $Revision: 1.83 $
//   $Name:  $
//   $Author: aekamal $
//   $Date: 2009/06/12 19:58:24 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

/**
 * CFunctionDB
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2001
 */

#include <algorithm>

#include "copasi.h"

#include "CFunctionDB.h"
#include "CFunction.h"
#include "FunctionDB.xml.h"

#include "utilities/CCopasiException.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "xml/CCopasiXML.h"
#include "model/CModel.h"

CFunctionDB::CFunctionDB(const std::string & name,
                         const CCopasiContainer * pParent):
    CCopasiContainer(name, pParent, "FunctionDB"),
    mFilename(),
    mLoadedFunctions("Functions", this)
{
  initObjects();
  CONSTRUCTOR_TRACE;
}

CFunctionDB::~CFunctionDB()
{
  cleanup();
  DESTRUCTOR_TRACE;
}

void CFunctionDB::cleanup() {mLoadedFunctions.cleanup();}

void CFunctionDB::initObjects()
{
  addObjectReference("File", mFilename);
}

bool CFunctionDB::load()
{
  CCopasiXML XML;
  XML.setFunctionList(&mLoadedFunctions);

  std::stringstream DB;
  DB.str(FunctionDBxml);

  if (DB.fail())
    return false;

  if (!XML.load(DB, ""))
    return false;

  return true;
}

C_INT32 CFunctionDB::load(CReadConfig &configbuffer)
{
  CFunction Function;
  CFunction * pFunction = NULL;

  C_INT32 Size = 0;
  C_INT32 Fail = 0;

  configbuffer.getVariable("TotalUDKinetics", "C_INT32", &Size,
                           CReadConfig::LOOP);

  for (C_INT32 i = 0; i < Size; i++)
    {
      Function.load(configbuffer);

      switch (Function.getType())
        {
          case CEvaluationTree::Function:
            pFunction = new CFunction(Function);
            break;

          case CEvaluationTree::MassAction:
            pFunction = new CMassAction(Function);
            break;

          case CEvaluationTree::PreDefined:
          case CEvaluationTree::UserDefined:
            pFunction = new CKinFunction(Function,
                                         &configbuffer);
            break;

          default:
            fatalError();
        }

      pFunction->compile();

      if (!mLoadedFunctions.add(pFunction, true))
        {
          pdelete(pFunction);

          // We ignore:
          // CCopasiVector (2): Object '%s' allready exists.
          if ((MCCopasiVector + 2) != CCopasiMessage::peekLastMessage().getNumber())
            return Fail = 1;

          // Remove the ignored meesage.
          CCopasiMessage::getLastMessage();
        }
    }

  return Fail;
}

void CFunctionDB::setFilename(const std::string & filename)
{mFilename = filename;}

std::string CFunctionDB::getFilename() const
{return mFilename;}

#ifdef FFFF
CFunction * CFunctionDB::dBLoad(const std::string & functionName)
{
  CFunction Function("NoName", &mLoadedFunctions);
  CFunction * pFunction = NULL;

  if (mFilename == "") return NULL;

  CReadConfig inbuf(mFilename);

  while (functionName != Function.getObjectName())
    {
      Function.cleanup();
      Function.load(inbuf);
    }

  switch (Function.getType())
    {
      case CFunction::Base:
        pFunction = new CFunction(Function);
        break;

      case CFunction::MassAction:
        pFunction = new CMassAction(Function.isReversible());
        break;

      case CFunction::PreDefined:

      case CFunction::UserDefined:
        pFunction = new CKinFunction(Function, &inbuf);
        break;

      case CFunction::Expression:
        fatalError(); //disabled
        //pFunction = new CUDFunction(Function);
        break;

      default:
        fatalError();
    }

  if (!mLoadedFunctions.add(pFunction))
    {
      pdelete(pFunction);

      // We ignore:
      // CCopasiVector (2): Object '%s' allready exists.
      if ((MCCopasiVector + 2) != CCopasiMessage::getLastMessage().getNumber())

        pFunction = mLoadedFunctions[Function.getObjectName()];
    }

  return pFunction;
}
#endif // FFFF

#ifdef FFFF
CEvaluationTree * CFunctionDB::createFunction(const std::string & name, const CEvaluationTree::Type & type)
{
  if (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)
    return NULL;

  //CFunction * pFunction = new CFunction(name);

  CEvaluationTree * pFunction = NULL;

  switch (type)
    {
      case CEvaluationTree::Base:
        pFunction = new CFunction(name);
        break;

      case CEvaluationTree::MassAction:
        pFunction = new CMassAction(name);
        break;

      case CEvaluationTree::PreDefinedKineticLaw:
      case CEvaluationTree::UserDefinedKineticLaw:
        pFunction = new CKinFunction(name);
        break;

      default:
        fatalError();
    }

  if (!mLoadedFunctions.add(pFunction, true))
    {
      delete pFunction;
      return NULL;
    }

  return pFunction;
}
#endif // FFFF

bool CFunctionDB::add(CEvaluationTree * pFunction,
                      const bool & adopt)
{return mLoadedFunctions.add(pFunction, adopt);}

void CFunctionDB::addAndAdaptName(CEvaluationTree * pFunction)
{
  if (!pFunction) return;

  std::string basename = pFunction->getObjectName();
  std::string name = basename;
  //CFunction* pFunc;
  //CCopasiVectorN<CEvaluationTree>& FunctionList
  //= this->loadedFunctions();
  int i = 0;

  while (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)
    {
      i++;
      std::ostringstream ss; ss << "_" << i;
      name = basename + ss.str();
    }

  pFunction->setObjectName(name);

  this->add(pFunction, true);
}

bool CFunctionDB::removeFunction(unsigned C_INT32 index)
{
  if (index == C_INVALID_INDEX) return false;

  mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index);

  return true;
}

bool CFunctionDB::removeFunction(const std::string &key)
{
  CEvaluationTree* func = dynamic_cast< CEvaluationTree * >(CCopasiRootContainer::getKeyFactory()->get(key));

  if (!func) return false;

  unsigned C_INT32 index =
    mLoadedFunctions.CCopasiVector<CEvaluationTree>::getIndex(func);

  if (index == C_INVALID_INDEX) return false;

  mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index);

  return true;
}

CEvaluationTree * CFunctionDB::findFunction(const std::string & functionName)
{
  unsigned C_INT32 index = mLoadedFunctions.getIndex(functionName);

  if (index != C_INVALID_INDEX)
    return mLoadedFunctions[index];
  else
    return NULL;
}

CEvaluationTree * CFunctionDB::findLoadFunction(const std::string & functionName)
{
  unsigned C_INT32 i;

  for (i = 0; i < mLoadedFunctions.size(); i++)
    if (functionName == mLoadedFunctions[i]->getObjectName())
      return mLoadedFunctions[i];

  return NULL;
}

CCopasiVectorN < CEvaluationTree > & CFunctionDB::loadedFunctions()
{return mLoadedFunctions;}

std::vector<CFunction*>
CFunctionDB::suitableFunctions(const unsigned C_INT32 noSubstrates,
                               const unsigned C_INT32 noProducts,
                               const TriLogic reversibility)
{
  std::vector<CFunction*> ret;
  CFunction *pFunction;

  unsigned C_INT32 i, imax = mLoadedFunctions.size();

  for (i = 0; i < imax; i++)
    {
      pFunction = dynamic_cast<CFunction *>(mLoadedFunctions[i]);

      if (!pFunction) continue;

      if (pFunction->isSuitable(noSubstrates, noProducts, reversibility))
        ret.push_back(pFunction);
    }

  //always add constant flux it is is missing
  if (reversibility == TriTrue)
    {
      if ((noSubstrates > 0) || (noProducts > 0)) //constant flux was not yet added
        {
          pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (reversible)"));

          if (!pFunction) fatalError();

          ret.push_back(pFunction);
        }
    }
  else //irreversible
    {
      if (noSubstrates > 0) //constant flux was not yet added
        {
          pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (irreversible)"));

          if (!pFunction) fatalError();

          ret.push_back(pFunction);
        }
    }

  return ret;
}

bool CFunctionDB::appendDependentFunctions(std::set< const CCopasiObject * > candidates,
    std::set< const CCopasiObject * > & dependentFunctions) const
{
  size_t Size = dependentFunctions.size();

  CCopasiVectorN< CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();
  CCopasiVectorN< CEvaluationTree >::const_iterator end = mLoadedFunctions.end();

  for (; it != end; ++it)
    if (candidates.find(*it) == candidates.end() &&
        (*it)->dependsOn(candidates))
      dependentFunctions.insert((*it));

  return Size < dependentFunctions.size();
}

std::set<std::string>
CFunctionDB::listDependentTrees(const std::string & name) const
{
  std::set<std::string> List;

  CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();
  CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();

  for (; it != end; ++it)
    if ((*it)->dependsOnTree(name))
      List.insert((*it)->getObjectName());

  return List;
}

std::vector< CEvaluationTree * > CFunctionDB::getUsedFunctions(const CModel* pModel) const
{
  std::vector< CEvaluationTree * > UsedFunctions;
  CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();
  CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();

  for (; it != end; ++it)
    {
      // :TODO: Bug 719
      // This will have to be modified as soon as the optimization problem stores its on expression
      if ((*it)->getType() == CEvaluationTree::Expression)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      std::set< const CCopasiObject * > Function;
      Function.insert(*it);

      std::set< const CCopasiObject * > Reactions;
      std::set< const CCopasiObject * > Metabolites;
      std::set< const CCopasiObject * > Values;
      std::set< const CCopasiObject * > Compartments;
      std::set< const CCopasiObject * > Events;

      pModel->appendDependentModelObjects(Function,
                                          Reactions, Metabolites, Compartments, Values, Events);

      if (Reactions.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Metabolites.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Values.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Compartments.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Events.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }
    }

  CEvaluationTree::completeEvaluationTreeList(UsedFunctions);

  return UsedFunctions;
}
<commit_msg>Removed obsolete code.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CFunctionDB.cpp,v $
//   $Revision: 1.84 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2009/10/26 22:08:51 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

/**
 * CFunctionDB
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2001
 */

#include <algorithm>

#include "copasi.h"

#include "CFunctionDB.h"
#include "CFunction.h"
#include "FunctionDB.xml.h"

#include "utilities/CCopasiException.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "xml/CCopasiXML.h"
#include "model/CModel.h"

CFunctionDB::CFunctionDB(const std::string & name,
                         const CCopasiContainer * pParent):
    CCopasiContainer(name, pParent, "FunctionDB"),
    mFilename(),
    mLoadedFunctions("Functions", this)
{
  initObjects();
  CONSTRUCTOR_TRACE;
}

CFunctionDB::~CFunctionDB()
{
  cleanup();
  DESTRUCTOR_TRACE;
}

void CFunctionDB::cleanup() {mLoadedFunctions.cleanup();}

void CFunctionDB::initObjects()
{
  addObjectReference("File", mFilename);
}

bool CFunctionDB::load()
{
  CCopasiXML XML;
  XML.setFunctionList(&mLoadedFunctions);

  std::stringstream DB;
  DB.str(FunctionDBxml);

  if (DB.fail())
    return false;

  if (!XML.load(DB, ""))
    return false;

  return true;
}

C_INT32 CFunctionDB::load(CReadConfig &configbuffer)
{
  CFunction Function;
  CFunction * pFunction = NULL;

  C_INT32 Size = 0;
  C_INT32 Fail = 0;

  configbuffer.getVariable("TotalUDKinetics", "C_INT32", &Size,
                           CReadConfig::LOOP);

  for (C_INT32 i = 0; i < Size; i++)
    {
      Function.load(configbuffer);

      switch (Function.getType())
        {
          case CEvaluationTree::Function:
            pFunction = new CFunction(Function);
            break;

          case CEvaluationTree::MassAction:
            pFunction = new CMassAction(Function);
            break;

          case CEvaluationTree::PreDefined:
          case CEvaluationTree::UserDefined:
            pFunction = new CKinFunction(Function,
                                         &configbuffer);
            break;

          default:
            fatalError();
        }

      pFunction->compile();

      if (!mLoadedFunctions.add(pFunction, true))
        {
          pdelete(pFunction);

          // We ignore:
          // CCopasiVector (2): Object '%s' allready exists.
          if ((MCCopasiVector + 2) != CCopasiMessage::peekLastMessage().getNumber())
            return Fail = 1;

          // Remove the ignored meesage.
          CCopasiMessage::getLastMessage();
        }
    }

  return Fail;
}

void CFunctionDB::setFilename(const std::string & filename)
{mFilename = filename;}

std::string CFunctionDB::getFilename() const
{return mFilename;}

#ifdef FFFF
CFunction * CFunctionDB::dBLoad(const std::string & functionName)
{
  CFunction Function("NoName", &mLoadedFunctions);
  CFunction * pFunction = NULL;

  if (mFilename == "") return NULL;

  CReadConfig inbuf(mFilename);

  while (functionName != Function.getObjectName())
    {
      Function.cleanup();
      Function.load(inbuf);
    }

  switch (Function.getType())
    {
      case CFunction::Base:
        pFunction = new CFunction(Function);
        break;

      case CFunction::MassAction:
        pFunction = new CMassAction(Function.isReversible());
        break;

      case CFunction::PreDefined:

      case CFunction::UserDefined:
        pFunction = new CKinFunction(Function, &inbuf);
        break;

      case CFunction::Expression:
        fatalError(); //disabled
        //pFunction = new CUDFunction(Function);
        break;

      default:
        fatalError();
    }

  if (!mLoadedFunctions.add(pFunction))
    {
      pdelete(pFunction);

      // We ignore:
      // CCopasiVector (2): Object '%s' allready exists.
      if ((MCCopasiVector + 2) != CCopasiMessage::getLastMessage().getNumber())

        pFunction = mLoadedFunctions[Function.getObjectName()];
    }

  return pFunction;
}
#endif // FFFF

#ifdef FFFF
CEvaluationTree * CFunctionDB::createFunction(const std::string & name, const CEvaluationTree::Type & type)
{
  if (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)
    return NULL;

  //CFunction * pFunction = new CFunction(name);

  CEvaluationTree * pFunction = NULL;

  switch (type)
    {
      case CEvaluationTree::Base:
        pFunction = new CFunction(name);
        break;

      case CEvaluationTree::MassAction:
        pFunction = new CMassAction(name);
        break;

      case CEvaluationTree::PreDefinedKineticLaw:
      case CEvaluationTree::UserDefinedKineticLaw:
        pFunction = new CKinFunction(name);
        break;

      default:
        fatalError();
    }

  if (!mLoadedFunctions.add(pFunction, true))
    {
      delete pFunction;
      return NULL;
    }

  return pFunction;
}
#endif // FFFF

bool CFunctionDB::add(CEvaluationTree * pFunction,
                      const bool & adopt)
{return mLoadedFunctions.add(pFunction, adopt);}

void CFunctionDB::addAndAdaptName(CEvaluationTree * pFunction)
{
  if (!pFunction) return;

  std::string basename = pFunction->getObjectName();
  std::string name = basename;
  //CFunction* pFunc;
  //CCopasiVectorN<CEvaluationTree>& FunctionList
  //= this->loadedFunctions();
  int i = 0;

  while (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX)
    {
      i++;
      std::ostringstream ss; ss << "_" << i;
      name = basename + ss.str();
    }

  pFunction->setObjectName(name);

  this->add(pFunction, true);
}

bool CFunctionDB::removeFunction(unsigned C_INT32 index)
{
  if (index == C_INVALID_INDEX) return false;

  mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index);

  return true;
}

bool CFunctionDB::removeFunction(const std::string &key)
{
  CEvaluationTree* func = dynamic_cast< CEvaluationTree * >(CCopasiRootContainer::getKeyFactory()->get(key));

  if (!func) return false;

  unsigned C_INT32 index =
    mLoadedFunctions.CCopasiVector<CEvaluationTree>::getIndex(func);

  if (index == C_INVALID_INDEX) return false;

  mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index);

  return true;
}

CEvaluationTree * CFunctionDB::findFunction(const std::string & functionName)
{
  unsigned C_INT32 index = mLoadedFunctions.getIndex(functionName);

  if (index != C_INVALID_INDEX)
    return mLoadedFunctions[index];
  else
    return NULL;
}

CEvaluationTree * CFunctionDB::findLoadFunction(const std::string & functionName)
{
  unsigned C_INT32 i;

  for (i = 0; i < mLoadedFunctions.size(); i++)
    if (functionName == mLoadedFunctions[i]->getObjectName())
      return mLoadedFunctions[i];

  return NULL;
}

CCopasiVectorN < CEvaluationTree > & CFunctionDB::loadedFunctions()
{return mLoadedFunctions;}

std::vector<CFunction*>
CFunctionDB::suitableFunctions(const unsigned C_INT32 noSubstrates,
                               const unsigned C_INT32 noProducts,
                               const TriLogic reversibility)
{
  std::vector<CFunction*> ret;
  CFunction *pFunction;

  unsigned C_INT32 i, imax = mLoadedFunctions.size();

  for (i = 0; i < imax; i++)
    {
      pFunction = dynamic_cast<CFunction *>(mLoadedFunctions[i]);

      if (!pFunction) continue;

      if (pFunction->isSuitable(noSubstrates, noProducts, reversibility))
        ret.push_back(pFunction);
    }

  //always add constant flux it is is missing
  if (reversibility == TriTrue)
    {
      if ((noSubstrates > 0) || (noProducts > 0)) //constant flux was not yet added
        {
          pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (reversible)"));

          if (!pFunction) fatalError();

          ret.push_back(pFunction);
        }
    }
  else //irreversible
    {
      if (noSubstrates > 0) //constant flux was not yet added
        {
          pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (irreversible)"));

          if (!pFunction) fatalError();

          ret.push_back(pFunction);
        }
    }

  return ret;
}

bool CFunctionDB::appendDependentFunctions(std::set< const CCopasiObject * > candidates,
    std::set< const CCopasiObject * > & dependentFunctions) const
{
  size_t Size = dependentFunctions.size();

  CCopasiVectorN< CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();
  CCopasiVectorN< CEvaluationTree >::const_iterator end = mLoadedFunctions.end();

  for (; it != end; ++it)
    if (candidates.find(*it) == candidates.end() &&
        (*it)->dependsOn(candidates))
      dependentFunctions.insert((*it));

  return Size < dependentFunctions.size();
}

std::set<std::string>
CFunctionDB::listDependentTrees(const std::string & name) const
{
  std::set<std::string> List;

  CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();
  CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();

  for (; it != end; ++it)
    if ((*it)->dependsOnTree(name))
      List.insert((*it)->getObjectName());

  return List;
}

std::vector< CEvaluationTree * > CFunctionDB::getUsedFunctions(const CModel* pModel) const
{
  std::vector< CEvaluationTree * > UsedFunctions;
  CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin();
  CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end();

  for (; it != end; ++it)
    {
      std::set< const CCopasiObject * > Function;
      Function.insert(*it);

      std::set< const CCopasiObject * > Reactions;
      std::set< const CCopasiObject * > Metabolites;
      std::set< const CCopasiObject * > Values;
      std::set< const CCopasiObject * > Compartments;
      std::set< const CCopasiObject * > Events;

      pModel->appendDependentModelObjects(Function,
                                          Reactions, Metabolites, Compartments, Values, Events);

      if (Reactions.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Metabolites.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Values.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Compartments.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }

      if (Events.size() != 0)
        {
          UsedFunctions.push_back(*it);
          continue;
        }
    }

  CEvaluationTree::completeEvaluationTreeList(UsedFunctions);

  return UsedFunctions;
}
<|endoftext|>