opengl -- how to call a function and draw it from the beginning (from menu option) - function

i have the following code ,which draws mandelbrot set.I created a menu with an option "black&white" which i want to draw the mandelbrot in black and white color.I haven't figured how to do this (if it can be done this way).mandelbrot is called through the display function ,but how can i call mandelbrot_black?
Also, if someone knows hot to make "zoom" in my code...here...http://stackoverflow.com/questions/5705554/how-to-do-zoom-in-my-code-mandelbrot
void mandelbrot();
void mandelbrot_black();
GLsizei width = 600;
GLsizei height = 600;
GLfloat AspectRatio;
int max = 500;
double xpos=0,ypos=0;
int CLEARFLAG=1;
double xmax = 2.0;
double xmin = -2.0;
double ymax = 2.0;
double ymin = -2.0;
using namespace std;
void display()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-2, width, -2, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT );
mandelbrot();
glutSwapBuffers();
}
void reshape(GLsizei w, GLsizei h) {
width=w; height=h;
glViewport(0,0,width,height);
glutPostRedisplay();
}
void setXYpos(int px, int py)
{
xpos=xmin+(xmax-xmin)*px/width;
ypos=ymax-(ymax-ymin)*py/height;
}
void mouse(int button, int state, int x, int y)
{
if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) {CLEARFLAG=0; setXYpos(x,y);}
glutPostRedisplay();
}
void mandelbrot()
{
...}
void mandelbrot_black(){
...}
void mymenu(int n)
{
switch(n) {
case 1: zoom_in();break;
case 2: zoom_out();break;
case 3: mandelbrot_black();break;
case 4: exit(0);
}
glutPostRedisplay();
}
void SetupMenu()
{
glutCreateMenu(mymenu);
glutAddMenuEntry("zoom in",1);
glutAddMenuEntry("zoom out",2);
glutAddMenuEntry("black&white",3);
glutAddMenuEntry("exit",4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutCreateWindow("Mandelbrot");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}

Your display function needs to draw either mandelbrot() or mandelbrot_black() depending on the current state (which can/should be a global variable).
//in global scope
static bool black = false;
...
//in display()
if(black)
mandelbrot_black();
else
mandelbrot();
Change black accordingly in mymenu(). You still need to attach your menu to a mouse button and call SetupMenu().

Related

How to use boolean function inside class in Arduino?

I am making a library for the MPR121 sensor and in that I want to use a bool function inside a class in Arduino IDE but it is not working.
Here's my code.
#include <Wire.h>
#include "Adafruit_MPR121.h"
#ifndef _BV
#define _BV(bit) (1 << (bit))
#endif
Adafruit_MPR121 cap = Adafruit_MPR121();
uint16_t lasttouched = 0;
uint16_t currtouched = 0;
class PaperTron {
private:
uint8_t i;
uint8_t a;
public:
PaperTron(){
}
void touchBegin(){
Serial.begin(9600);
Serial.println("Hi! I'm PaperTron.");
if (!cap.begin(0x5A)) {
Serial.println("Error! TOUCH pins not found. Please check wiring.");
while (1);
}
Serial.println("Hurray! Now you can use my TOUCH pins.");
}
**//This is the boolean function which is not working**
bool isHigh(uint8_t touchpin) {
currtouched = cap.touched();
for (i=0; i<12; i++) {
if ((currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) {
if(i==touchpin) return true;
}
if (!(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) {
if(i==touchpin) return false;
}
}
lasttouched = currtouched;
}
};
PaperTron papertron;
void setup() {
papertron.Begin();
papertron.touchBegin();
}
void loop() {
if(papertron.isHigh(2)){Serial.println("Hello");}
}
The serial monitor is showing "Hello" continuously whereas it should print "Hello" only when I press the touch pin on MPR121.

calling Thrust device_vector from a device function

I have a struct Cap which inside I have a thrust::device_vector of another structure. When I compile the code, I get an error which complains about calling a host function (thrust::device_vector<FloatIntPair>) from a device function SphericalFaceManager::makeCaps. When I add __host__ __device__ instead of only __device__ to the member functions and constructors the code then compiles but I receive a warning same as aforementioned error and I think it copies data between host and device. My question is how can I access to device vectors in my classes avoiding any data transfer between CPU and GPU?
Hereafter you can find the code:
struct ParticleID {
Int solver;
Int ngb;
Int oldNgb;
LLInt no;
LLInt masterNo;
__device__ ParticleID() {
solver = -8;
ngb = 0;
oldNgb = 0;
no = 0;
masterNo = -1;
}
};
struct BaseParticle {
Float h;
Float3 pos;
ParticleID id;
__device__ BaseParticle(const Float3& _pos, const Float& _h, const ParticleID& _id) :
h(_h), pos(_pos), id(_id) { }
};
struct FloatIntPair{
Float first;
Int second;
__device__ FloatIntPair(const Float& _first, Int _second) : first(_first), second(_second) { }
__device__ FloatIntPair(const FloatIntPair& sample) : first(sample.first), second(sample.second) { }
static struct {
__device__ bool operator()(const FloatIntPair& a, const FloatIntPair& b) { return a.first < b.first; }
} LessOp;
};
struct Cap {
Float3 eX;
Float3 eY;
Float radius;
Float height;
Float3 center;
Float3 normal;
BaseParticle* aP;
BaseParticle* bP;
thrust::device_vector<FloatIntPair> vertices; // The ordered list of vertices generated from intersections by other circles
__device__ inline Float findAngle(const Float3& vertex) const {
Float result;
Float3 r = (vertex - center);
result = atan2(r|eY,r|eX);
return result += (result < 0.0) * (2.0 * _PI);
}
__device__ void insertVertex(const Float3& vertex, Int id) {
Float theta;
if (!vertices.empty())
theta = findAngle(vertex);
else {
eX = normalVec(vertex - center);
eY = normal ^ eX;
theta = 0.0;
}
vertices.push_back(FloatIntPair(theta,id));
}
__device__ Cap(BaseParticle* _aP, BaseParticle* _bP) : aP(_aP), bP(_bP) {
//Compute normal, center, radius
Float d = mag(bP->pos - aP->pos);
if(d == 0.0){
normal = Vector1(0.0);
center = aP->pos;
radius = height = 0.0;
} else {
normal = (bP->pos - aP->pos) / d;
Float x = (d * d - bP->h * bP->h + aP->h * aP->h) / (2.0 * d);
center = aP->pos + normal * x;
if (x >= aP->h) {
radius = height = 0.0;
return;
}
radius = sqrt(aP->h * aP->h - x * x);
height = min(2.0 * aP->h, aP->h - x);
Float3 vec001 = Vector(0.0,0.0,1.0);
Float3 vec011 = Vector(0.0,1.0,1.0);
eX = normalVec(vec001 ^ normal);
if (mag2(eX) < geoEps()) {
eX = eX = normalVec(vec011 ^ normal);
}
eY = normal ^ eX;
}
}
};
class SphericalFaceManager {
BaseParticle* particle;
Int baseSigma;
public:
thrust::device_vector<Cap> caps;
thrust::device_vector<Float3> vertexPool;
__device__ void makeCaps();
};
__device__ void SphericalFaceManager::makeCaps() {
BaseParticle* aP;
BaseParticle* bP;
Cap aCap(aP,bP);
}
You cannot use thrust vectors (or std::vector) directly in device code. This is mentioned in various other SO questions such as here
If you want to use the data in a thrust::device_vector in device code, you should pass a pointer to the data as a functor initializing parameter. Various other SO questions give examples of this, such as here
Likewise, you cannot use vector methods, e.g. .empty() or .push_back() in device code.
You will need to replace these with ordinary C-style allocators and C-style indexed data access.
For a multi-threaded implementation of push_back in device code, I would recommend something like this. That is a fully worked example that demonstrates how to allocate space for the vector and how each thread can use it for insertVertex for example.

Passing class function using function pointer to external library

I have a class that uses a preexisting library. There is a function call that needs a function pointer, and I am trying to pass in the function that is in my class. It doesn't compile though. What can I do to fix this? (Also, I'm sure this was asked before in a much clearer way. I'm out of my element with this, so my apologies).
Note: This is for an arduino.
In my main program I have the following code...
#include "CM.h"
CM cm;
void setup() {
cm.setup();
}
CM.h
class CM {
private:
LibClass *lib;
void onInit();
public:
void setup();
};
CM.cpp
#include "CM.h"
void CM::setup() {
lib->attach(onInit); // <-- this isn't working.
}
void CM::onInit() {
Serial.println("HERE I AM");
}
To pass a member function, you need to make it "static" and then pass it with a full scope qualifier:
#include <iostream>
void attach( void (*func)(void) );
class CM {
private:
static void onInit();
public:
void setup();
};
void CM::setup()
{
attach(CM::onInit);
}
void CM::onInit(void)
{
std::cout << "HERE I AM";
}
// a global function pointer for this example
void (*p_func)(void);
// a "library" attach function
void attach( void (*func)(void) )
{
p_func = func;
}
int main(int argc, const char * argv[]) {
CM my;
my.setup();
p_func(); // like the library call
return 0;
}

Passing Host Function as a function pointer in __global__ OR __device__ function in CUDA

I am currently developing a GPU version of a CPU function
(e.g. function Calc(int a, int b, double* c, souble* d, CalcInvFunction GetInv )), in which a host function is passes as a function pointer(e.g. in above example GetInv is the host function of CalcInvFunction type). My question is, if i have to put Calc() function entirely in GPU, i have to pass the GetInv function as a function pointer argument in device function/kernel function, and is that possible?
Yes, for a GPU implementation of Calc, you should pass the GetInv as a __device__ function pointer.
It is possible, here are some worked examples:
Ex. 1
Ex. 2
Ex. 3
Most of the above examples demonstrate bringing the device function pointer all the way back to the host code. This may not be necessary for your particular case. But it should be fairly obvious from above how to grab a __device__ function pointer (in device code) and use it in a kernel.
Finally, i have been able to pass a host function as a function pointer in cuda kernel function (__global__ function). Thanks to Robert Crovella and njuffa for the answer. I have been able to pass a class member function(cpu function) as a function pointer to a cuda kernel. But, the main problem is, i can only pass the static class member function. I am not being able to pass the function not declared as static.
For Example:
/**/
__host__ __device__
static int
CellfunPtr(
void*ptr, int a
);
/**/
The above function work because this member function is declared as static member function. If i do not declare this member function as a static member as ,
/**/
__host__ __device__
int
CellfunPtr(
void*ptr, int a
);
/**/
then it doesnt work.
The complete code has four files.
First file
/*start of fundef.h file*/
typedef int (*pFunc_t)(void* ptr, int N);
/*end of fundef.h file*/
Second file
/*start of solver.h file*/
class CalcVars {
int eqnCount;
int numCell;
int numTri;
int numTet;
public:
double* cellVel;
double* cellPre;
/** Constructor */
CalcVars(
const int eqnCount_,
const int numCell_,
const int numTri_,
const int numTet_
);
/** Destructor */
~CalcVars(void);
public:
void
CalcAdv();
__host__ __device__
static int
CellfunPtr(
void*ptr, int a
);
};
/*end of solver.h file*/
Third file
/*start of solver.cu file*/
#include "solver.h"
__device__ pFunc_t pF1_d = CalcVars::CellfunPtr;
pFunc_t pF1_h ;
__global__ void kernel(int*a, pFunc_t func, void* thisPtr_){
int tid = threadIdx.x;
a[tid] = (*func)(thisPtr_, a[tid]);
};
/* Constructor */
CalcVars::CalcVars(
const int eqnCount_,
const int numCell_,
const int numTri_,
const int numTet_
)
{
this->eqnCount = eqnCount_;
this->numCell = numCell_;
this->numTri = numTri_;
this->cellVel = (double*) calloc((size_t) eqnCount, sizeof(double));
this->cellPre = (double*) calloc((size_t) eqnCount, sizeof(double));
}
/* Destructor */
CalcVars::~CalcVars(void)
{
free(this->cellVel);
free(this->cellPre);
}
void
CalcVars::CalcAdv(
){
/*int b1 = 0;
b1 = CellfunPtr(this, 1);*/
int Num = 50;
int *a1, *a1_dev;
a1 = (int *)malloc(Num*sizeof(int));
cudaMalloc((void**)&a1_dev, Num*sizeof(int));
for(int i = 0; i <Num; i++){
a1[i] = i;
}
cudaMemcpy(a1_dev, a1, Num*sizeof(int), cudaMemcpyHostToDevice);
//copy addresses of device functions to host
cudaMemcpyFromSymbol(&pF1_h, pF1_d, sizeof(pFunc_t));
kernel<<<1,42>>>(a1_dev, pF1_h, this);
cudaDeviceSynchronize();
cudaMemcpy(a1, a1_dev, Num*sizeof(int), cudaMemcpyDeviceToHost);
};
int
CalcVars::CellfunPtr(
void* ptr, int a
){
//CalcVars* ClsPtr = (CalcVars*)ptr;
printf("Printing from CPU function\n");
//int eqn_size = ClsPtr->eqnCount;
//printf("The number is %d",eqn_size);
return a-1;
};
/*end of solver.cu file*/
Fourth file
/*start of main.cpp file*/
#include "solver.h"
int main(){
int n_Eqn, n_cell, n_tri, n_tetra;
n_Eqn = 100;
n_cell = 200;
n_tri = 300;
n_tetra = 400;
CalcVars* calcvars;
calcvars = new CalcVars(n_Eqn, n_cell, n_tri, n_tetra );
calcvars->CalcAdv();
system("pause");
}
/*end of main.cpp file*/

Functions in struct in c only

I am having a hard time compiling this C code.
Basically what happens is:
it does compile but when I run it (on Terminal) it prints me:Illegal instruction
I tried to debug it and on Xcode and when it attempts to execute (*fraction).print() it says: EXC_BAD_ACCESS
if I delete the (*fraction).print() line everything works fine (same happens if I only delete the next line)
GNU99 and -fnested-functions flag is enabled
I do not want to change the main function just the other stuff
This code drove me crazy for a whole afternoon so a little help would be really appreciated.
Thankyou
#include <stdlib.h>
#include "string.h"
#include "stdio.h"
typedef struct
{
int numerator;
int denominator;
void (*print)(); // prints on screen "numerator/denominator"
float (*convertToNum)(); //returns value of numerator/denominator
void (*setNumerator)(int n);
void (*setDenominator)(int d);
} Fraction;
Fraction* allocFraction(Fraction* fraction); //creates an uninitialized fraction
void deleteFraction(Fraction *fraction);
Fraction* allocFraction(Fraction* fraction)
{
void print()
{
int a= 10;
printf("%i/%i", (*fraction).numerator, (*fraction).denominator);
a--;
}
float convertToNum()
{
return (float)(*fraction).numerator/(float)(*fraction).denominator;
}
void setNumerator (int n)
{
(*fraction).numerator= n;
}
void setDenominator (int d)
{
(*fraction).denominator= d;
}
if(fraction== NULL)
fraction= (Fraction*) malloc(sizeof(Fraction));
if(fraction)
{
(*fraction).convertToNum= convertToNum;
(*fraction).print= print;
(*fraction).setNumerator= setNumerator;
(*fraction).setDenominator= setDenominator;
}
return fraction;
}
void deleteFraction(Fraction *fraction)
{
free(fraction);
}
int main (int argc, const char * argv[])
{
Fraction *fraction= allocFraction(fraction);
(*fraction).setNumerator(4);
(*fraction).setDenominator(7);
(*fraction).print(); //EXC_BAD_ACCESS on debug. Illegal instruction in Terminal
printf("%f", (*fraction).convertToNum());
(*fraction).print();
deleteFraction(fraction);
return 0;
}
You can't write C in the same way you write Javascript.
Specifically, it appears that print() is a nested function inside allocFraction() (which is itself not standard C but a gcc extension). You can't call a nested function through a function pointer from outside the scope of where it's defined. This is true even if you don't access anything in the outer scope from the nested scope.
Your code appears to be attempting to do object-oriented programming in C. Have you considered C++?