Example #1
0
void PerftTest(int depth, S_BOARD *pos) {
	S_MOVELIST list[1];
	int move;
	int MoveNum = 0;
	int start = GetTimeMs();
	long cumnodes, oldnodes;

	ASSERT(CheckBoard(pos));

	PrintBoard(pos);
	printf("\nStarting Test To Depth:%d\n", depth);
	leafNodes = 0;
	
	GenerateAllMoves(pos, list);

	for(MoveNum = 0; MoveNum < list->count; ++MoveNum) {
		move = list->moves[MoveNum].move;
		if(!MakeMove(pos, move))
			continue;

		cumnodes = leafNodes;
		Perft(depth - 1, pos);
		TakeMove(pos);
		oldnodes = leafNodes - cumnodes;
		printf("move %d : %s : %ld\n", MoveNum + 1, PrMove(move), oldnodes);
	}

	printf("\nTest Complete : %ld nodes visited in %dms\n", leafNodes, GetTimeMs() - start);
}
void* tcp_client(void *whatever){

	struct sockaddr_in server_addr;
	int sckt, status, len;
	int starttime, stoptime;
	struct hostent *server;
	int iSetOption = 1;

	sckt = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	setsockopt(sckt, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption, sizeof(iSetOption));

	if(sckt == -1)
	{
	    printf("error opening socket\n");
	    exit(EXIT_FAILURE);
	}

    if (h.server == NULL) {
        fprintf(stderr,"Cannot connect to the server\n");
        exit(EXIT_FAILURE);
    }

	server_addr.sin_port = htons(h.port);
	memcpy(&server_addr.sin_addr.s_addr, h.server->h_addr, h.server->h_length);
	server_addr.sin_family = AF_INET;

	if (connect(sckt,(struct sockaddr *) &server_addr,sizeof(server_addr)) < 0) {
		printf("Couldn't connect\n");
    	exit(EXIT_FAILURE);
	}

	starttime = GetTimeMs();
	status = write(sckt, h.buffer, lSize);
	if (status < 0){
	  	printf("Couldn't write the message\n");
	   	exit(EXIT_FAILURE);
	}
	stoptime = GetTimeMs();	    

    printf("Duration client write = %d us\n", stoptime - starttime);

    //sleep(2);

    starttime = GetTimeMs();
    char *message = (char *)calloc( 1, lSize+1 );
    status = read(sckt,message,lSize);
    if (status < 0){
    	printf("Cannot read from the socket\n");
    	exit(EXIT_FAILURE);
    }
    stoptime = GetTimeMs();

    printf("Duration client read back = %d us\n", stoptime - starttime);
    //printf("%s\n", message);

	close(sckt);
	pthread_exit(NULL);
	exit(EXIT_SUCCESS);
}
// Callback function called by GLUT to render sub-window content
void DisplaySubWindow(void)
{
    float v[4]; // will be used to set light parameters
    float mat[4*4]; // rotation matrix
    SubWindowData *win;

    win = GetCurrentSubWindowData();
    if (win == NULL) return;

    // Tell AntTweakBar which is the current window
    TwSetCurrentWindow(win->WinID);

    // Clear frame buffer
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    glEnable(GL_NORMALIZE);

    // Set light
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    v[0] = v[1] = v[2] = win->LightMultiplier*0.4f; v[3] = 1.0f;
    glLightfv(GL_LIGHT0, GL_AMBIENT, v);
    v[0] = v[1] = v[2] = win->LightMultiplier*0.8f; v[3] = 1.0f;
    glLightfv(GL_LIGHT0, GL_DIFFUSE, v);
    v[0] = -win->LightDirection[0]; v[1] = -win->LightDirection[1]; v[2] = -win->LightDirection[2]; v[3] = 0.0f;
    glLightfv(GL_LIGHT0, GL_POSITION, v);

    // Set material
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, win->MatAmbient);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, win->MatDiffuse);

    // Rotate and draw shape
    glPushMatrix();
    glTranslatef(0.5f, -0.3f, 0.0f);
    if( win->AutoRotate ) 
    {
        float axis[3] = { 0, 1, 0 };
        float angle = (float)(GetTimeMs()-win->RotateTime)/1000.0f;
        float quat[4];
        SetQuaternionFromAxisAngle(axis, angle, quat);
        MultiplyQuaternions(win->RotateStart, quat, win->Rotation);
    }
    ConvertQuaternionToMatrix(win->Rotation, mat);
    glMultMatrixf(mat);
    glScalef(win->Zoom, win->Zoom, win->Zoom);
    glCallList(win->ObjectShape);
    glPopMatrix();

    // Draw tweak bars
    TwDraw();

    // Present frame buffer
    glutSwapBuffers();

    // Recall Display at next frame
    glutPostRedisplay();
}
Example #4
0
void DebugAnalysisTest(S_BOARD *pos, S_SEARCHINFO *info) {

	FILE *file;
    file = fopen("lct2.epd","r");
    char lineIn [1024];

	info->depth = MAXDEPTH;
	info->timeset = TRUE;
	int time = 1140000;


    if(file == NULL) {
        printf("File Not Found\n");
        return;
    }  else {
        while(fgets (lineIn , 1024 , file) != NULL) {
			info->starttime = GetTimeMs();
			info->stoptime = info->starttime + time;
			ClearHashTable(pos->HashTable);
            ParseFen(lineIn, pos);
            printf("\n%s\n",lineIn);
			printf("time:%d start:%d stop:%d depth:%d timeset:%d\n",
				time,info->starttime,info->stoptime,info->depth,info->timeset);
			SearchPosition(pos, info);
            memset(&lineIn[0], 0, sizeof(lineIn));
        }
    }
}
Example #5
0
// Get the time elapsed since the Start()
u64 Timer::GetTimeElapsed()
{
	// If we have not started yet, return 1 (because then I don't
	// have to change the FPS calculation in CoreRerecording.cpp .
	if (m_StartTime == 0) return 1;

	// Return the final timer time if the timer is stopped
	if (!m_Running) return (m_LastTime - m_StartTime);

	return (GetTimeMs() - m_StartTime);
}
Example #6
0
File: iconify.c Project: Limsik/e17
static void
IB_Animate_Sleep(unsigned int t0, double a)
{
   unsigned int        t;
   double              dt;

   t = GetTimeMs() - t0;
   dt = 1e-3 * (t - a * IB_ANIM_TIME);
   dt = 1e-3 * IB_ANIM_STEP - dt;
   if (dt > 0)
      usleep((unsigned long)(1e6 * dt));
}
Example #7
0
void TW_CALL SetAutoRotateCB(const void *value, void *clientData)
{

	g_AutoRotate = *(const int *)value;
	if (g_AutoRotate != 0)
	{
		g_RotateTime = GetTimeMs();
		g_RotateStart[0] = g_Rotation[0];
		g_RotateStart[1] = g_Rotation[1];
		g_RotateStart[2] = g_Rotation[2];
		g_RotateStart[3] = g_Rotation[3];
		TwDefine(" TweakBar/ObjRotation readonly ");
	}
	else
		TwDefine(" TweakBar/ObjRotation readwrite ");
}
Example #8
0
//  Callback function called when the 'AutoRotate' variable value of the tweak bar has changed
void TW_CALL SetAutoRotateCB(const void *value, void *clientData)
{
	(void)clientData; // unused

	g_AutoRotate = *(const int *)value; // copy value to g_AutoRotate
	if (g_AutoRotate != 0)
	{
		// init rotation
		g_RotateTime = GetTimeMs();
		g_RotateStart[0] = g_Rotation[0];
		g_RotateStart[1] = g_Rotation[1];
		g_RotateStart[2] = g_Rotation[2];
		g_RotateStart[3] = g_Rotation[3];

		// make Rotation variable read-only
		TwDefine(" TweakBar/ObjRotation readonly ");
	}
	else
		// make Rotation variable read-write
		TwDefine(" TweakBar/ObjRotation readwrite ");
}
//  Callback function called when the 'AutoRotate' variable value of the tweak bar has changed
void TW_CALL SetAutoRotateCB(const void *value, void *clientData)
{
	SubWindowData *win;
	
	win = (SubWindowData *)clientData;
    win->AutoRotate = *(const int *)value; // copy value to win->AutoRotate

    if (win->AutoRotate != 0) 
    {
        // init rotation
        win->RotateTime = GetTimeMs();
        win->RotateStart[0] = win->Rotation[0];
        win->RotateStart[1] = win->Rotation[1];
        win->RotateStart[2] = win->Rotation[2];
        win->RotateStart[3] = win->Rotation[3];
    }

    // make Rotation variable read-only or read-write
    TwSetCurrentWindow(win->WinID);
    TwSetParam(win->Bar, "ObjRotation", "readonly", TW_PARAM_INT32, 1, &win->AutoRotate);
}
Example #10
0
// Get the formatted time elapsed since the Start()
std::string Timer::GetTimeElapsedFormatted() const
{
	// If we have not started yet, return zero
	if (m_StartTime == 0)
		return "00:00:00:000";

	// The number of milliseconds since the start.
	// Use a different value if the timer is stopped.
	u64 Milliseconds;
	if (m_Running)
		Milliseconds = GetTimeMs() - m_StartTime;
	else
		Milliseconds = m_LastTime - m_StartTime;
	// Seconds
	u32 Seconds = (u32)(Milliseconds / 1000);
	// Minutes
	u32 Minutes = Seconds / 60;
	// Hours
	u32 Hours = Minutes / 60;

	std::string TmpStr = StringFromFormat("%02i:%02i:%02i:%03i",
		Hours, Minutes % 60, Seconds % 60, Milliseconds % 1000);
	return TmpStr;
}
Example #11
0
void overlap() { 
  Globals::qbs = new QNode*[Globals::threads_num];
  Globals::sets = new std::map<myset,myset*>[Globals::threads_num];
  for (int i = 0; i<Globals::threads_num; i++) {
    Globals::qbs[i] = new QNode();
  }

  denominator = Globals::c2 * Globals::gamma; 
  denominator /= Globals::side_multiplier;
  
  boost::thread* thr[Globals::threads_num];
  for (int i = 0; i < Globals::threads_num; ++i)
    thr[i] = new boost::thread(Worker(i));
  for (int i = 0; i < Globals::threads_num; ++i) {
    thr[i]->join();
    delete thr[i];
  }
 
//  for (int i=0; i<Globals::threads_num; i++) {
//    rec_count(Globals::qbs[i], 1.0);
//    std::cout << Globals::ov_nodes << " " << Globals::ov_leaves << std::endl;
//    Globals::ov_nodes=1;
//    Globals::ov_leaves=0;
//  }
 
  double merging_timer = GetTimeMs();
  for (int i=1; i<Globals::threads_num; i++) {
    std::cout << "Merging " << i << std::endl;
    merge_nodes(Globals::qbs[0],Globals::qbs[i]);
    delete Globals::qbs[i];
  }
  Globals::qb = Globals::qbs[0];
  //depth_all_reprs(Globals::qb);
  make_it_deeper(Globals::qb);

  //TODO
  //std::cout << "start filling" << std::endl;

//  std::cout << "before fill vectors" << std::endl;
//  fill_vectors(Globals::qb, &Globals::hypercube_center, 1.0);

/*  for (int i=0; i<10; i++) {
    printPt(std::cout,*Globals::qt_centers[i]);
    std::cout<<std::endl;
    std::cout << Globals::qt_sides[i] << std::endl;
  }*/

  Globals::ov_nodes=1;
  Globals::ov_leaves=0;
  rec_count(Globals::qb);
  //TODO
  ////std::cout << " ovnodes " << Globals::ov_nodes << " " << Globals::ov_leaves << std::endl;
  ////std::cout << "LEAF: " << couter << std::endl;

  dothereprs();

ANNmin_k* asdf = new ANNmin_k(1);

//  fill_in_reprs(Globals::qb, &Globals::hypercube_center, 1.0, Globals::kdtree, asdf);
  find_all_reprs(Globals::qbs[0], &Globals::hypercube_center, 1.0, Globals::kdtree, asdf,0);

  Globals::merging_time = GetTimeMs() - merging_timer;

  ANNidxArray  nnIdx = new ANNidx[Globals::reprs_num];
  ANNdistArray dists = new ANNdist[Globals::reprs_num];
  //replace_reprs(Globals::qb, &Globals::hypercube_center, 1.0, nnIdx, dists); CHANGE
  delete[] nnIdx;
  delete[] dists; 
//TODO
//  std::cout << "done replacing" << std::endl; 
  /*std::map<myset,myset*>::iterator it;
  for (int i=0; i<Globals::threads_num; i++) {
    for (it=Globals::sets[i].begin(); it!=Globals::sets[i].end(); it++) {
      delete (*it).second;
    }
  }*/
  delete[] Globals::sets;

  //representatives();
}
Example #12
0
void IO::consoleLoop(Board* board, SEARCHINFO* info) {
    printf("Welcome to TidesTicTactics in Console Mode!\n");
    info->POST_THINKING = true;
    setbuf(stdin, NULL);
    setbuf(stdin, NULL);
    int depth = 81;
    int movetime = 500; // 3 sec
    Coordinate move;
    char inBuf[80], command[80], modifier[80];
    Color engineSide = COLOR_NONE;
    Engine engine;
    Movelist movecheck;
    bool init = false;
    bool initX = true;
    Movelist movelist;

    while (true) {
        fflush(stdout);
        if ((board->toMove == engineSide || engineSide == COLOR_BOTH) && board->winner == COLOR_NONE) {
            info->starttime = GetTimeMs();
            info->depth = depth;
            if (movetime != 0) {
                info->timeset = true;
                info->stoptime = info->starttime + movetime;
            }
            engine.searchPosition(board, info, true);
            engineSide = COLOR_NONE;
        }
        // print prompt
        printf("");
        fflush(stdout);
        memset(&inBuf[0], 0, sizeof(inBuf));
        fflush(stdout);
        if(!fgets(inBuf, 80, stdin))
            continue;
        std::transform(inBuf, inBuf + 80 - 1, inBuf, [](unsigned char c) { return std::tolower(c); });
        sscanf(inBuf, "%s", command);

        if(!strcmp(command, "help")) {
            printf("\nCommands:\n");
            printf("quit - quit game\n");
            printf("force - will not move\n");
            printf("print - show board\n");
            printf("post - show thinking\n");
            printf("nopost - do not show thinking\n");
            printf("new - start new game\n");
            printf("go - set computer thinking\n");
            printf("depth x - set depth to x\n");
            printf("time x - set thinking time to x seconds (depth still applies if set)\n");
            printf("view - show current depth and movetime settings\n");
            printf("moves - show valid moves\n");
            printf("captures - show moves winning a board");
            printf("test x - load first x moves of demo");
            printf("test2 x - load first x moves of demo");
            printf("** note ** - to reset time and depth, set to 0\n");
            printf("enter moves using B1..9F1..9 notation\n\n\n");
            continue;
        }

        if(!strcmp(command, "moves")) {
            board->getMoves(&movecheck);
            if (movecheck.count == 0) {
                printf("No moves found");
            }
            for(int i = 0; i < movecheck.count; i++) {
                printf("%s ", PRMOVE(movecheck.moves[i].move).c_str());
            }
            printf("\n");
            continue;
        }

        if(!strcmp(command, "player")) {
            sscanf(inBuf, "player %s init", modifier);
            if(!strcmp(modifier, "one")) {
                init = true;
                initX = true;
            } else if(!strcmp(modifier, "two")) {
                init = true;
                initX = false;
            } else {
                printf("unknown player: %s\n", modifier);
            }
            continue;
        }

        if(!strcmp(command, "start")) {
            sscanf(inBuf, "start %s", modifier);
            if(!strcmp(modifier, "turns")) {
                init = false;
                board->toMove = COLOR_X;
                board->next = SQUARE_NONE;
            } else if(!strcmp(modifier, "game")) {
                init = true;
            } else {
                printf("unknown start modifier: %s\n", modifier);
            }
            continue;
        }

        if(!strcmp(command, "captures")) {
            board->getCaptureMoves(&movecheck);
            if (movecheck.count == 0) {
                printf("no captures found");
            }
            for(int i = 0; i < movecheck.count; i++) {
                printf("%s ", PRMOVE(movecheck.moves[i].move).c_str());
            }
            printf("\n");
            continue;
        }

        if(!strcmp(command, "eval")) {
            printf(board->printBoard().c_str());
            printf("\neval:%d",board->getScore());
            continue;
        }
        if(!strcmp(command, "quit")) {
            info->quit = true;
            break;
        }

        if(!strcmp(command, "post")) {
            info->POST_THINKING = true;
            continue;
        }

        if(!strcmp(command, "print")) {
            printf(board->printBoard().c_str());
            continue;
        }

        if(!strcmp(command, "nopost")) {
            info->POST_THINKING = false;
            continue;
        }

        if(!strcmp(command, "force")) {
            engineSide = COLOR_NONE;
            continue;
        }

        if(!strcmp(command, "demo")) {
            Color temp = COLOR_NONE;
            while (temp != board->toMove && board->winner == COLOR_NONE) {
                temp = board->toMove;
                info->starttime = GetTimeMs();
                info->depth = std::min(depth, MAXMOVES - board->movecount);
                if (movetime != 0) {
                    info->timeset = true;
                    info->stoptime = info->starttime + movetime;
                }
                engine.searchPosition(board, info, true);
                printf(board->printBoard().c_str());
                // printf("\nNONE\n");
                // printf(board->printBoard(COLOR_NONE).c_str());

            }
            continue;
        }

        if(!strcmp(command, "view")) {
            if(depth == 81) printf("depth not set ");
            else printf("depth %d",depth);

            if(movetime != 0) printf(" movetime %ds\n",movetime/1000);
            else printf(" movetime not set\n");

            continue;
        }

        if(!strcmp(command, "depth")) {
            sscanf(inBuf, "depth %d", &depth);
            if(depth==0) depth = 81;
            continue;
        }

        if(!strcmp(command, "test")) {
            engineSide = COLOR_NONE;
            while (board->movecount > 0)
                board->undo();
            int target;
            sscanf(inBuf, "test %d", &target);
            demo1(board, target);
            continue;
        }

        if(!strcmp(command, "test2")) {
            engineSide = COLOR_NONE;
            while (board->movecount > 0)
                board->undo();
            int target;
            sscanf(inBuf, "test2 %d", &target);
            demo2(board, target);
            continue;
        }

        if(!strcmp(command, "time")) {
            sscanf(inBuf, "time %d", &movetime);
            movetime *= 1000;
            continue;
        }

        if(!strcmp(command, "new")) {
            engineSide = COLOR_O;
            while (board->movecount > 0)
                board->undo();
            continue;
        }

        if(!strcmp(command, "go")) {
            engineSide = board->toMove;
            info->stopped = false;
            continue;
        }

        move = parseMove(inBuf);
        if(move == NOMOVE) {
            printf("command unknown:%s\n",inBuf);
            continue;
        }
        if(init) {
            if(initX) {
                board->toMove = COLOR_X;
                board->setupmove(move);
            } else {
                board->toMove = COLOR_O;
                board->setupmove(move);
            }
        } else {
            board->getMoves(&movelist);
            bool found = false;
            for (int i = 0; i < movelist.count; i++) {
                if (move == movelist.moves[i].move) {
                    found = true;
                    break;
                }
            }
            if (found)
                board->move(move);
            else {
                printf("INVALID MOVE: %s\n", PRMOVE(move).c_str());
                printf("%s", board->printBoard().c_str());
                break;
            }
        }
    }
    printf("Engine shutting down...\n");
}
Example #13
0
// Main
int main(int argc, char *argv[])
{
	TwBar *bar; // Pointer to the tweak bar
	float axis[] = { 0.7f, 0.7f, 0.0f }; // initial model rotation
	float angle = 0.8f;

	// Initialize GLUT
	//OutputDebugStringA("Test\n");
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(800, 600);
	glutInitWindowPosition(100, 100);
	glutCreateWindow("SRTP Middle Check");
	glutCreateMenu(NULL);
	glewInit();
	initTextureList();
	for (int i = 0; i < textpoint; i++){
		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, textureObjects[i]);
	}
	glActiveTexture(GL_TEXTURE0);

	sprintf(path, "%sCook-Torrorence", root);
	programs[2] = setupShaders(path);

	// Set GLUT callbacks
	glutDisplayFunc(Display);
	glutReshapeFunc(Reshape);

	// Initialize AntTweakBar
	TwInit(TW_OPENGL, NULL);

	// Set GLUT event callbacks
	// - Directly redirect GLUT mouse button events to AntTweakBar
	glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT);
	// - Directly redirect GLUT mouse motion events to AntTweakBar
	glutMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
	// - Directly redirect GLUT mouse "passive" motion events to AntTweakBar (same as MouseMotion)
	glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
	// - Directly redirect GLUT key events to AntTweakBar
	glutKeyboardFunc((GLUTkeyboardfun)TwEventKeyboardGLUT);
	// - Directly redirect GLUT special key events to AntTweakBar
	glutSpecialFunc((GLUTspecialfun)TwEventSpecialGLUT);
	// - Send 'glutGetModifers' function pointer to AntTweakBar;
	//   required because the GLUT key event functions do not report key modifiers states.
	TwGLUTModifiersFunc(glutGetModifiers);

	// Create some 3D objects (stored in display lists)
	glNewList(SHAPE_TEAPOT, GL_COMPILE);
	glutSolidTeapot(1.0);
	glEndList();
	glNewList(SHAPE_TORUS, GL_COMPILE);
	//glutSolidTorus(0.3, 1.0, 16, 32);
	glutSolidSphere(0.75f, 20, 20);
	glEndList();
	glNewList(SHAPE_DRAGON, GL_COMPILE);
	drawBunny("dragon");
	glEndList();
	glNewList(SHAPE_SKULL, GL_COMPILE);
	drawBunny("skull");
	glEndList();
	glNewList(SHAPE_GARGO, GL_COMPILE);
	drawBunny("Gargoyle_ABF");
	glEndList();
	glNewList(DRAW_EN, GL_COMPILE);
	drawEnv(30);
	glEndList();

	// Create a tweak bar
	bar = TwNewBar("TweakBar");
	TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLUT and OpenGL.' "); // Message added to the help bar.
	TwDefine(" TweakBar size='250 540' color='96 216 224' "); // change default tweak bar size and color

	TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &g_Zoom, " min=0.01 max=7.5 step=0.01 ");
	TwAddVarRW(bar, "ObjRotation", TW_TYPE_QUAT4F, &g_Rotation, " label='Object rotation' opened=true ");
	TwAddVarCB(bar, "AutoRotate", TW_TYPE_BOOL32, SetAutoRotateCB, GetAutoRotateCB, NULL, " label='Auto-rotate' key=space ");
	TwAddVarRW(bar, "LightDir", TW_TYPE_DIR3F, &lightDirection, " label='Light direction' opened=true ");
	TwAddVarRW(bar, "LightDist", TW_TYPE_FLOAT, &lightDistance, " label='Light distance' ");
	TwAddVarRW(bar, "Ambient", TW_TYPE_COLOR3F, &lightAmbient, "");
	TwAddVarRW(bar, "Diffuse", TW_TYPE_COLOR3F, &lightDiffuse, "");
	TwAddVarRW(bar, "Rf", TW_TYPE_COLOR3F, &rf, "");
	TwAddVarRW(bar, "Roughness", TW_TYPE_FLOAT, &roughness, " label='Roughness' min=0.01 max=1.99 step=0.01 keyIncr='+' keyDecr='-' ");

	{
		TwEnumVal shaders[NUM_SHADERS] = { { SHADER_PHONG, "Phong" }, { SHADER_COOKTORRORENCE, "CookTorrorence" } };
		TwType shaderType = TwDefineEnum("ShaderType", shaders, NUM_SHADERS);
		TwAddVarRW(bar, "Shader", shaderType, &currentShader, "");
	}

	// Add the enum variable 'g_CurrentShape' to 'bar'
	// (before adding an enum variable, its enum type must be declared to AntTweakBar as follow)
	{
		// ShapeEV associates Shape enum values with labels that will be displayed instead of enum values
		TwEnumVal shapeEV[NUM_SHAPES] = { { SHAPE_TEAPOT, "Teapot" }, { SHAPE_TORUS, "Sphere" }, { SHAPE_DRAGON, "Dragon" }, { SHAPE_SKULL, "Skull" }, { SHAPE_GARGO, "Gargo" } };
		// Create a type for the enum shapeEV
		TwType shapeType = TwDefineEnum("ShapeType", shapeEV, NUM_SHAPES);
		// add 'g_CurrentShape' to 'bar': this is a variable of type ShapeType. Its key shortcuts are [<] and [>].
		TwAddVarRW(bar, "Shape", shapeType, &g_CurrentShape, "");
	}

	// Store time
	g_RotateTime = GetTimeMs();
	// Init rotation
	SetQuaternionFromAxisAngle(axis, angle, g_Rotation);
	SetQuaternionFromAxisAngle(axis, angle, g_RotateStart);

	atexit(Terminate);  // Called after glutMainLoop ends
	// Call the GLUT main loop
	glutMainLoop();

	return 0;
}
   int main() {

         // Create the variables for the time measure
         int starttime, stoptime;

         //Get initial time
         starttime = GetTimeMs();

         // This code executes on the OpenCL host

         // Host data
         float *A=NULL; // Input array
         float *B=NULL; // Input array
         float *C=NULL; // Output array

         // Elements in each array
          const int elements=2048;
         // Compute the size of the data
         size_t datasize=sizeof(int)*elements;

         // Allocate space for input/output data
         A=(float*)malloc(datasize);
         B=(float*)malloc(datasize);
         C=(float*)malloc(datasize);

         // Initialize the input data
         A[0]=2.2;
         A[1]=1.3;
         B[0]=3.7;
         B[1]=5.4;


         // Load the kernel source code into the array programSource
	     FILE *fp;
	     char *programSource;
	     size_t programSize;
	 
	     fp = fopen("fplos_kernels.cl", "r");
	     if (!fp) {
	         fprintf(stderr, "Failed to load kernel.\n");
	         exit(1);
	     }
	     programSource = (char*)malloc(MAX_SOURCE_SIZE);
	     fclose( fp );

         // Use this to check the output of each API call
         cl_int status;

         // Retrieve the number of platforms
         cl_uint numPlatforms=0;
         status=clGetPlatformIDs(0, NULL,&numPlatforms);

         // Allocate enough space for each platform
         cl_platform_id *platforms=NULL;
         platforms=(cl_platform_id*)malloc(
              numPlatforms*sizeof(cl_platform_id));

         // Fill in the platforms
         status = clGetPlatformIDs(numPlatforms, platforms, NULL);

         // Retrieve the number of devices
         cl_uint numDevices=0;
         status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_ALL, 0,
               NULL,&numDevices);

         // Allocate enough space for each device
         cl_device_id *devices;
         devices = (cl_device_id*)malloc(
               numDevices*sizeof(cl_device_id));

         // Fill in the devices
         status = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_ALL,
              numDevices, devices, NULL);

         // Create a context and associate it with the devices
         cl_context context;
         context = clCreateContext(NULL, numDevices, devices, NULL,
             NULL, &status);

         // Create a command queue and associate it with the device
         cl_command_queue cmdQueue;
         cmdQueue = clCreateCommandQueue(context, devices[0], 0,
            &status);

         // Create a buffer object that will contain the data
         // from the host array A
         cl_mem bufA;
         bufA = clCreateBuffer(context, CL_MEM_READ_ONLY, datasize,
             NULL, &status);

         // Create a buffer object that will contain the data
         // from the host array B
         cl_mem bufB;
         bufB = clCreateBuffer(context, CL_MEM_READ_ONLY, datasize,
            NULL, &status);

         // Create a buffer object that will hold the output data
         cl_mem bufC;
         bufC = clCreateBuffer(context, CL_MEM_WRITE_ONLY, datasize,
            NULL, &status);

         // Write input array A to the device buffer bufferA
         status = clEnqueueWriteBuffer(cmdQueue, bufA, CL_FALSE,
            0, datasize, A, 0, NULL, NULL);

         // Write input array B to the device buffer bufferB
         status = clEnqueueWriteBuffer(cmdQueue, bufB, CL_FALSE,
            0, datasize, B, 0, NULL, NULL);

         // Create a program with source code
         cl_program program=clCreateProgramWithSource(context, 1,
            (const char**)&programSource, NULL, &status);

         // Build (compile) the program for the device
         status=clBuildProgram(program, numDevices, devices,
            NULL, NULL, NULL);

         // Create the vector addition kernel
         cl_kernel kernel;
         kernel=clCreateKernel(program, "floatadd", &status);

         // Associate the input and output buffers with the kernel
         status=clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufA);
         status=clSetKernelArg(kernel, 1, sizeof(cl_mem), &bufB);
         status=clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufC);

         // Define an index space (global work size) of work
         // items for execution. A workgroup size (local work size)
         // is not required, but can be used.
         size_t globalWorkSize[1];

         // There are 'elements' work-items
         globalWorkSize[0]=elements;

         // Execute the kernel for execution
         status=clEnqueueNDRangeKernel(cmdQueue, kernel, 1, NULL,
            globalWorkSize, NULL, 0, NULL, NULL);

         // Read the device output buffer to the host output array
         clEnqueueReadBuffer(cmdQueue, bufC, CL_TRUE, 0,
            datasize, C, 0, NULL, NULL);

           printf("Output = %.1f\n", C[0]);
           printf("Output = %.1f\n", C[1]);

        // Free OpenCL resources
         clReleaseKernel(kernel);
         clReleaseProgram(program);
         clReleaseCommandQueue(cmdQueue);
         clReleaseMemObject(bufA);
         clReleaseMemObject(bufB);
         clReleaseMemObject(bufC);
         clReleaseContext(context);

         // Free host resources
         free(A);
         free(B);
         free(C);
         free(platforms);
         free(devices);

         //Get initial time
         stoptime = GetTimeMs();

         printf("Duration= %d ms\n", stoptime - starttime);
            
         return 0;
   }
Example #15
0
// Get the number of milliseconds since the last Update()
u64 Timer::GetTimeDifference()
{
	return GetTimeMs() - m_LastTime;
}
Example #16
0
// Stop the timer
void Timer::Stop()
{
	// Write the final time
	m_LastTime = GetTimeMs();
	m_Running = false;
}
int main(int argc, char *argv[]){
	
	int t1,t2;
	int starttime, stoptime;
	pthread_t thread1, thread2;

	h.server = gethostbyname(argv[1]);
	h.port = atoi(argv[2]);

	FILE *fp;

	if(strcmp(argv[3], "1b") == 0)fp = fopen("../txt/1b.txt", "rb");
	else if(strcmp(argv[3], "1kb") == 0)fp = fopen("../txt/1kb.txt", "rb");
	else if(strcmp(argv[3], "64kb") == 0)fp = fopen("../txt/64kb.txt", "rb");
	else if(strcmp(argv[3], "1mb") == 0)fp = fopen("../txt/1mb.txt", "rb");
	else fp = fopen("../txt/alice.txt", "rb");

    if (!fp) {
        fprintf(stderr, "Failed to load file.\n");
        return -1;
    }

	fseek( fp , 0L , SEEK_END);
	lSize = ftell( fp );
	rewind( fp );

	/* allocate memory for entire content */
	h.buffer = (char *)calloc( 1, lSize+1 );
	if( !h.buffer ){
		fclose(fp);
		printf("Couldn't allocate memory\n");
		return -1;
	}

	/* copy the file into the buffer */
	if( fread( h.buffer , lSize, 1 , fp) != true){
		fclose(fp);
		free(h.buffer);
		printf("Couldn't copy in buffer\n");
		return -1;
	}

	fclose(fp);

	const char *message1 = "Thread 1";
	const char *message2 = "Thread 2";

	starttime = GetTimeMs();
	t1 = pthread_create(&thread1, NULL, tcp_server, (void *)message1);
    if (t1) {
        printf("ERROR; thread tcp_server");
        return -1;
    }

    t2 = pthread_create(&thread2, NULL, tcp_client, (void *)message2);
    if (t2) {
        printf("ERROR; thread tcp_client");
        return -1;
    }
	stoptime = GetTimeMs();

    //printf("Duration= %d us\n", stoptime - starttime);

	pthread_exit(NULL);
	return 0;
}
Example #18
0
void Display(void)
{
	//display the background image here
	
	/*glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 1, 0, 1, -1, 1);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	glDepthMask(GL_FALSE);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glRasterPos2i(0, 0);
	glDrawPixels()*/

	/*
	glClearColor(1.0, 0.0, 0.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	glEnable(GL_TEXTURE_2D);
	*/
	//background();


		float v[4]; 
		float v1[4];
		float mat[4 * 4];

		glClearColor(0, 0, 0, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glEnable(GL_DEPTH_TEST);
		glDisable(GL_CULL_FACE);
		glEnable(GL_NORMALIZE);

		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		v[0] = v[1] = v[2] = g_LightMultiplier*0.4f; v[3] = 1.0f;
		glLightfv(GL_LIGHT0, GL_AMBIENT, v);
		v[0] = v[1] = v[2] = g_LightMultiplier*0.8f; v[3] = 1.0f;
		glLightfv(GL_LIGHT0, GL_DIFFUSE, v);
		v[0] = -g_LightDirection[0]; v[1] = -g_LightDirection[1]; v[2] = -g_LightDirection[2]; v[3] = 0.0f;
		glLightfv(GL_LIGHT0, GL_POSITION, v);
		

		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT1);
		v1[0] = v1[1] = v1[2] = g_LightMultiplier*0.4f; v1[3] = 1.0f;
		glLightfv(GL_LIGHT1, GL_AMBIENT, v1);
		v1[0] = v1[1] = v1[2] = g_LightMultiplier*0.8f; v1[3] = 1.0f;
		glLightfv(GL_LIGHT1, GL_DIFFUSE, v1);
		v1[0] = -g_LightDirection2[0]; v1[1] = -g_LightDirection2[1]; v1[2] = -g_LightDirection2[2]; v1[3] = 0.0f;
		glLightfv(GL_LIGHT1, GL_POSITION, v1);

		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, g_MatAmbient1);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, g_MatDiffuse1);

		glPushMatrix();
		glTranslatef(0.5f, -0.3f, 0.0f);
		if (g_AutoRotate)
		{
			float axis[3] = { 0, 1, 0 };
			float angle = (float)(GetTimeMs() - g_RotateTime) / 1000.0f;
			float quat[4];
			SetQuaternionFromAxisAngle(axis, angle, quat);
			MultiplyQuaternions(g_RotateStart, quat, g_Rotation);
		}
		ConvertQuaternionToMatrix(g_Rotation, mat);
		glMultMatrixf(mat);
		glScalef(g_Zoom, g_Zoom, g_Zoom);
		Matrices identity;
		animation->evaluate(newTime);
		if (animate){
			float timeDiff = currentTime - prevTime;
			prevTime = currentTime;
			currentTime = time(NULL);
			newTime = newTime + 0.01;
		}
		skeletonWasp->calculate(identity.IDENTITY);
		skinningWasp->update();
		skinningWasp->draw();		
		glPopMatrix();
	

	TwDraw();

	glutSwapBuffers();

	glutPostRedisplay();
}
// Setup new sub-window
void SetupSubWindow(int subWinIdx) 
{
    float axis[] = { 0.7f, 0.7f, 0.0f }; // initial model rotation
    float angle = 0.8f;
    SubWindowData *win;
    
    win = &g_SubWindowData[subWinIdx];
    win->ObjectShape = (subWinIdx == 0) ? SHAPE_TEAPOT : SHAPE_TORUS;
	win->Zoom = 1;
	win->AutoRotate = (subWinIdx == 0);
    win->MatAmbient[0] = (subWinIdx == 1) ? 0.0f : 0.5f;; win->MatAmbient[1] = win->MatAmbient[2] = 0.2f; win->MatAmbient[3] = 1;
    win->MatDiffuse[0] = (subWinIdx == 1) ? 0.0f : 1.0f; win->MatDiffuse[1] = 1; win->MatDiffuse[2] = 0; win->MatDiffuse[3] = 1;
	win->LightMultiplier = 1;
    win->LightDirection[0] = win->LightDirection[1] = win->LightDirection[2] = -0.57735f;
    win->RotateTime = GetTimeMs();
    SetQuaternionFromAxisAngle(axis, angle, win->Rotation);
    SetQuaternionFromAxisAngle(axis, angle, win->RotateStart);
	
	glutSetWindow(win->WinID);
    // Set GLUT callbacks
    glutDisplayFunc(DisplaySubWindow);
    glutReshapeFunc(ReshapeSubWindow);
    // Set GLUT event callbacks
    // - Register mouse button events callback
    glutMouseFunc((GLUTmousebuttonfun)MouseButtonCB);
    // - Register mouse motion events callback
    glutMotionFunc((GLUTmousemotionfun)MouseMotionCB);
    // - Register mouse "passive" motion events (same as Motion)
    glutPassiveMotionFunc((GLUTmousemotionfun)MouseMotionCB);
    // - Register keyboard events callback
    glutKeyboardFunc((GLUTkeyboardfun)KeyboardCB);
    // - Register special key events callback
    glutSpecialFunc((GLUTspecialfun)SpecialKeyCB);
    // - Send 'glutGetModifers' function pointer to AntTweakBar;
    //   required because the GLUT key event functions do not report key modifiers states.
    TwGLUTModifiersFunc(glutGetModifiers);

    // Create some 3D objects (stored in display lists)
    glNewList(SHAPE_TEAPOT, GL_COMPILE);
    glutSolidTeapot(1.0);
    glEndList();
    glNewList(SHAPE_TORUS, GL_COMPILE);
    glutSolidTorus(0.3, 1.0, 16, 32);
    glEndList();
    glNewList(SHAPE_CONE, GL_COMPILE);
    glutSolidCone(1.0, 1.5, 64, 4);
    glEndList();

    // Declare this window as current for AntTweakBar.
    // Here, this will create a new AntTweakBar context for this window,
    // which will be identified by the number WinID.
    TwSetCurrentWindow(win->WinID);

    // Create a tweak bar
    win->Bar = TwNewBar("TweakBar");
    TwDefine(" GLOBAL help='This example shows how to use AntTweakBar with multiple windows.' "); // Message added to the help bar.
    TwDefine(" TweakBar size='200 400' color='96 216 224' "); // change default tweak bar size and color

    // Add 'win->Zoom' to 'bar': this is a modifable (RW) variable of type TW_TYPE_FLOAT. Its key shortcuts are [z] and [Z].
    TwAddVarRW(win->Bar, "Zoom", TW_TYPE_FLOAT, &win->Zoom, 
               " min=0.01 max=2.5 step=0.01 keyIncr=z keyDecr=Z help='Scale the object (1=original size).' ");

    // Add 'win->Rotation' to 'bar': this is a variable of type TW_TYPE_QUAT4F which defines the object's orientation
    TwAddVarRW(win->Bar, "ObjRotation", TW_TYPE_QUAT4F, &win->Rotation, 
               " label='Object rotation' open help='Change the object orientation.' ");

    // Add callback to toggle auto-rotate mode (callback functions are defined above).
    TwAddVarCB(win->Bar, "AutoRotate", TW_TYPE_BOOL32, SetAutoRotateCB, GetAutoRotateCB, win, 
               " label='Auto-rotate' key=space help='Toggle auto-rotate mode.' ");

    // Add 'win->LightMultiplier' to 'bar': this is a variable of type TW_TYPE_FLOAT. Its key shortcuts are [+] and [-].
    TwAddVarRW(win->Bar, "Multiplier", TW_TYPE_FLOAT, &win->LightMultiplier, 
               " label='Light booster' min=0.1 max=4 step=0.02 keyIncr='+' keyDecr='-' help='Increase/decrease the light power.' ");

    // Add 'win->LightDirection' to 'bar': this is a variable of type TW_TYPE_DIR3F which defines the light direction
    TwAddVarRW(win->Bar, "LightDir", TW_TYPE_DIR3F, &win->LightDirection, 
               " label='Light direction' open help='Change the light direction.' ");

    // Add 'win->MatAmbient' to 'bar': this is a variable of type TW_TYPE_COLOR3F (3 floats color, alpha is ignored)
    // and is inserted into a group named 'Material'.
    TwAddVarRW(win->Bar, "Ambient", TW_TYPE_COLOR3F, &win->MatAmbient, " group='Material' ");

    // Add 'win->MatDiffuse' to 'bar': this is a variable of type TW_TYPE_COLOR3F (3 floats color, alpha is ignored)
    // and is inserted into group 'Material'.
    TwAddVarRW(win->Bar, "Diffuse", TW_TYPE_COLOR3F, &win->MatDiffuse, " group='Material' ");

    // Add the enum variable 'win->ObjectShape' to 'bar'
    // (before adding an enum variable, its enum type must be declared to AntTweakBar as follow)
    {
        // ShapeEV associates Shape enum values with labels that will be displayed instead of enum values
        TwEnumVal shapeEV[NUM_SHAPES] = { {SHAPE_TEAPOT, "Teapot"}, {SHAPE_TORUS, "Torus"}, {SHAPE_CONE, "Cone"} };
        // Create a type for the enum shapeEV
        TwType shapeType = TwDefineEnum("ShapeType", shapeEV, NUM_SHAPES);
        // add 'win->CurrentShape' to 'bar': this is a variable of type ShapeType. Its key shortcuts are [<] and [>].
        TwAddVarRW(win->Bar, "Shape", shapeType, &win->ObjectShape, " keyIncr='<' keyDecr='>' help='Change object shape.' ");
    }
}
Example #20
0
// Main
int main(int argc, char *argv[])
{
    TwBar *bar; // Pointer to the tweak bar
    float axis[] = { 0.7f, 0.7f, 0.0f }; // initial model rotation
    float angle = 0.8f;

    // Initialize GLUT
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(640, 480);
    glutCreateWindow("AntTweakBar simple example using GLUT");
    glutCreateMenu(NULL);

    // Set GLUT callbacks
    glutDisplayFunc(Display);
    glutReshapeFunc(Reshape);
    atexit(Terminate);  // Called after glutMainLoop ends

    // Initialize AntTweakBar
    TwInit(TW_OPENGL, NULL);

    // Set GLUT event callbacks
    // - Directly redirect GLUT mouse button events to AntTweakBar
    glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT);
    // - Directly redirect GLUT mouse motion events to AntTweakBar
    glutMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
    // - Directly redirect GLUT mouse "passive" motion events to AntTweakBar (same as MouseMotion)
    glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
    // - Directly redirect GLUT key events to AntTweakBar
    glutKeyboardFunc((GLUTkeyboardfun)TwEventKeyboardGLUT);
    // - Directly redirect GLUT special key events to AntTweakBar
    glutSpecialFunc((GLUTspecialfun)TwEventSpecialGLUT);
    // - Send 'glutGetModifers' function pointer to AntTweakBar;
    //   required because the GLUT key event functions do not report key modifiers states.
    TwGLUTModifiersFunc(glutGetModifiers);

    // Create some 3D objects (stored in display lists)
    glNewList(SHAPE_TEAPOT, GL_COMPILE);
    glutSolidTeapot(1.0);
    glEndList();
    glNewList(SHAPE_TORUS, GL_COMPILE);
    glutSolidTorus(0.3, 1.0, 16, 32);
    glEndList();
    glNewList(SHAPE_CONE, GL_COMPILE);
    glutSolidCone(1.0, 1.5, 64, 4);
    glEndList();

    // Create a tweak bar
    bar = TwNewBar("TweakBar");
    TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLUT and OpenGL.' "); // Message added to the help bar.
    TwDefine(" TweakBar size='200 400' color='96 216 224' "); // change default tweak bar size and color

    // Add 'g_Zoom' to 'bar': this is a modifable (RW) variable of type TW_TYPE_FLOAT. Its key shortcuts are [z] and [Z].
    TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &g_Zoom, 
               " min=0.01 max=2.5 step=0.01 keyIncr=z keyDecr=Z help='Scale the object (1=original size).' ");

    // Add 'g_Rotation' to 'bar': this is a variable of type TW_TYPE_QUAT4F which defines the object's orientation
    TwAddVarRW(bar, "ObjRotation", TW_TYPE_QUAT4F, &g_Rotation, 
               " label='Object rotation' opened=true help='Change the object orientation.' ");

    // Add callback to toggle auto-rotate mode (callback functions are defined above).
    TwAddVarCB(bar, "AutoRotate", TW_TYPE_BOOL32, SetAutoRotateCB, GetAutoRotateCB, NULL, 
               " label='Auto-rotate' key=space help='Toggle auto-rotate mode.' ");

    // Add 'g_LightMultiplier' to 'bar': this is a variable of type TW_TYPE_FLOAT. Its key shortcuts are [+] and [-].
    TwAddVarRW(bar, "Multiplier", TW_TYPE_FLOAT, &g_LightMultiplier, 
               " label='Light booster' min=0.1 max=4 step=0.02 keyIncr='+' keyDecr='-' help='Increase/decrease the light power.' ");

    // Add 'g_LightDirection' to 'bar': this is a variable of type TW_TYPE_DIR3F which defines the light direction
    TwAddVarRW(bar, "LightDir", TW_TYPE_DIR3F, &g_LightDirection, 
               " label='Light direction' opened=true help='Change the light direction.' ");

    // Add 'g_MatAmbient' to 'bar': this is a variable of type TW_TYPE_COLOR3F (3 floats color, alpha is ignored)
    // and is inserted into a group named 'Material'.
    TwAddVarRW(bar, "Ambient", TW_TYPE_COLOR3F, &g_MatAmbient, " group='Material' ");

    // Add 'g_MatDiffuse' to 'bar': this is a variable of type TW_TYPE_COLOR3F (3 floats color, alpha is ignored)
    // and is inserted into group 'Material'.
    TwAddVarRW(bar, "Diffuse", TW_TYPE_COLOR3F, &g_MatDiffuse, " group='Material' ");

    // Add the enum variable 'g_CurrentShape' to 'bar'
    // (before adding an enum variable, its enum type must be declared to AntTweakBar as follow)
    {
        // ShapeEV associates Shape enum values with labels that will be displayed instead of enum values
        TwEnumVal shapeEV[NUM_SHAPES] = { {SHAPE_TEAPOT, "Teapot"}, {SHAPE_TORUS, "Torus"}, {SHAPE_CONE, "Cone"} };
        // Create a type for the enum shapeEV
        TwType shapeType = TwDefineEnum("ShapeType", shapeEV, NUM_SHAPES);
        // add 'g_CurrentShape' to 'bar': this is a variable of type ShapeType. Its key shortcuts are [<] and [>].
        TwAddVarRW(bar, "Shape", shapeType, &g_CurrentShape, " keyIncr='<' keyDecr='>' help='Change object shape.' ");
    }

    // Store time
    g_RotateTime = GetTimeMs();
    // Init rotation
    SetQuaternionFromAxisAngle(axis, angle, g_Rotation);
    SetQuaternionFromAxisAngle(axis, angle, g_RotateStart);

    // Call the GLUT main loop
    glutMainLoop();

    return 0;
}
Example #21
0
/*
	Graphics general concepts:
	Each display element shown is based on a ClusterElement.
	We maintain a vector of elements to be drawn. The list is kept in z-order.
	The lowest order element is the background element.

	ClusterElements can draw to their own framebuffers, or directly to the screen (which
	may be double buffered itself.) Wherever possible, it is best to pre-render elements
	to framebuffers that can quickly be copied to the screen using DMA or BitBlits.
	The mBackgrond element is an example of this. It draws a gradient at boot time, and then
	never has to recreate the gradient again. It can simply copy the rendered image from its
	framebuffer to the screen.

	ClusterElements keep track of their foreground and background regions that need repainting
	using the Region class. The drawing cycle consists of two phases:

	Phase 1 Update() : 
		During the update phase, ClusterElements determine what state changes have occurred since
		the last Update/Draw cycle. If their internal elements have moved, they may have exposed 
		an area from the element below it. This is indicated by returning a Region object from
		the Update() call. The Update() phase is called in reverse z-order. So, the top elements
		are updated first. Since each object returns a region of what it exposed, the next element
		called will be passed the Region that was just invalidated. If this next element called
		can completely draw the exposed area, it will n
*/
InstrumentCluster::InstrumentCluster()
{
	mNextFlasherChange	= GetTimeMs();
}
Example #22
0
File: iconify.c Project: Limsik/e17
static void
IB_Animate_A(char iconify, EWin * ewin, EWin * ibox)
{
   EWin               *fr, *to;
   unsigned int        t0;
   double              a, aa, spd;
   int                 x, y, x1, y1, x2, y2, x3, y3, x4, y4, w, h;
   int                 fx, fy, fw, fh, tx, ty, tw, th;
   Window              root = WinGetXwin(VROOT);
   GC                  gc;
   XGCValues           gcv;

   /* Window: Extents, Iconbox: Center */
   if (iconify)
     {
	fr = ewin;
	to = ibox;
	fw = EoGetW(fr) + 4;
	fh = EoGetH(fr) + 4;
	fx = EoGetX(fr) - 2;
	fy = EoGetY(fr) - 2;
	tw = 4;
	th = 4;
	tx = EoGetX(to) + EoGetW(to) / 2 - 2;
	ty = EoGetY(to) + EoGetH(to) / 2 - 2;
     }
   else
     {
	fr = ibox;
	to = ewin;
	fw = 4;
	fh = 4;
	fx = EoGetX(fr) + EoGetW(fr) / 2 - 2;
	fy = EoGetY(fr) + EoGetH(fr) / 2 - 2;
	tw = EoGetW(to) + 4;
	th = EoGetH(to) + 4;
	tx = EoGetX(to) + 2;
	ty = EoGetY(to) + 2;
     }
   fx += EoGetX(EoGetDesk(fr));
   fy += EoGetY(EoGetDesk(fr));
   tx += EoGetX(EoGetDesk(to));
   ty += EoGetY(EoGetDesk(to));

   gcv.subwindow_mode = IncludeInferiors;
   gcv.function = GXxor;
   gcv.line_width = 2;
   gcv.foreground = Dpy.pixel_white;
   if (gcv.foreground == 0)
      gcv.foreground = Dpy.pixel_black;
   gc = EXCreateGC(root,
		   GCFunction | GCForeground | GCSubwindowMode | GCLineWidth,
		   &gcv);

   spd = (1. * IB_ANIM_STEP) / IB_ANIM_TIME;

   t0 = GetTimeMs();
   for (a = 0.0; a < 1.0; a += spd)
     {
	aa = 1.0 - a;

	x = (int)((fx * aa) + (tx * a));
	y = (int)((fy * aa) + (ty * a));
	w = (int)((fw * aa) + (tw * a));
	h = (int)((fh * aa) + (th * a));

	x = (2 * x + w) / 2;	/* x middle */
	y = (2 * y + h) / 2;	/* y middle */
	w /= 2;			/* width/2 */
	h /= 2;			/* height/2 */

	x1 = (int)(x + w * (1 - .5 * sin(3.14159 + a * 6.2831853072)));
	y1 = (int)(y + h * cos(a * 6.2831853072));
	x2 = (int)(x + w * (1 - .5 * sin(a * 6.2831853072)));
	y2 = (int)(y - h * cos(a * 6.2831853072));
	x3 = (int)(x - w * (1 - .5 * sin(3.14159 + a * 6.2831853072)));
	y3 = (int)(y - h * cos(a * 6.2831853072));
	x4 = (int)(x - w * (1 - .5 * sin(a * 6.2831853072)));
	y4 = (int)(y + h * cos(a * 6.2831853072));

	XDrawLine(disp, root, gc, x1, y1, x2, y2);
	XDrawLine(disp, root, gc, x2, y2, x3, y3);
	XDrawLine(disp, root, gc, x3, y3, x4, y4);
	XDrawLine(disp, root, gc, x4, y4, x1, y1);

	ESync(0);
	IB_Animate_Sleep(t0, a);

	XDrawLine(disp, root, gc, x1, y1, x2, y2);
	XDrawLine(disp, root, gc, x2, y2, x3, y3);
	XDrawLine(disp, root, gc, x3, y3, x4, y4);
	XDrawLine(disp, root, gc, x4, y4, x1, y1);
     }

   EXFreeGC(gc);
}
Example #23
0
// Write the starting time
void Timer::Start()
{
	m_StartTime = GetTimeMs();
	m_Running = true;
}
Example #24
0
File: events.c Project: Limsik/e17
/*
 * This is the primary event loop.  Everything that is going to happen in the
 * window manager has to start here at some point.  This is where all the
 * events from the X server are interpreted, timer events are inserted, etc
 */
void
EventsMain(void)
{
   static int          evq_alloc = 0;
   static int          evq_fetch = 0;
   static XEvent      *evq_ptr = NULL;
   fd_set              fdset;
   struct timeval      tval;
   unsigned int        time1, time2;
   int                 dt;
   int                 count, pfetch;
   int                 fdsize, fd, i;

   time1 = GetTimeMs();

   for (;;)
     {
	pfetch = 0;
	count = EventsProcess(&evq_ptr, &evq_alloc, &pfetch);

	if (pfetch)
	  {
	     evq_fetch =
		(pfetch > evq_fetch) ? pfetch : (3 * evq_fetch + pfetch) / 4;
	     if (EDebug(EDBUG_TYPE_EVENTS))
		Eprintf("EventsMain - Alloc/fetch/pfetch/peak=%d/%d/%d/%d)\n",
			evq_alloc, evq_fetch, pfetch, count);
	     if ((evq_ptr) && ((evq_alloc - evq_fetch) > 64))
	       {
		  evq_alloc = 0;
		  Efree(evq_ptr);
		  evq_ptr = NULL;
	       }
	  }

	/* time2 = current time */
	time2 = GetTimeMs();
	dt = time2 - time1;
	Mode.events.time_ms = time1 = time2;
	/* dt = time spent since we last were here */

	/* Run all expired timers */
	TimersRun(time2);

	/* Run idlers */
	IdlersRun();

	if (Mode.wm.exit_mode)
	   break;

	if (XPending(disp))
	   continue;

	FD_ZERO(&fdset);
	fdsize = -1;
	for (i = 0; i < nfds; i++)
	  {
	     fd = pfds[i].fd;
	     if (fd < 0)
		continue;
	     if (fdsize < fd)
		fdsize = fd;
	     FD_SET(fd, &fdset);
	  }
	fdsize++;

	/* Get time to first non-expired (0 means none) */
	time2 = TimersRunNextIn(time2);
	if (time2 > 0.)
	  {
	     tval.tv_sec = (long)time2 / 1000;
	     tval.tv_usec = ((long)time2 - tval.tv_sec * 1000) * 1000;
	     count = select(fdsize, &fdset, NULL, NULL, &tval);
	  }
	else
	  {
	     count = select(fdsize, &fdset, NULL, NULL, NULL);
	  }

	if (EDebug(EDBUG_TYPE_EVENTS))
	   Eprintf
	      ("EventsMain - count=%d xfd=%d:%d dt=%.6lf time2=%.6lf\n",
	       count, pfds[0].fd, FD_ISSET(pfds[0].fd, &fdset), dt * 1e-3,
	       time2 * 1e-3);

	if (count <= 0)
	   continue;		/* Timeout (or error) */

	/* Excluding X fd */
	for (i = 1; i < nfds; i++)
	  {
	     fd = pfds[i].fd;
	     if ((fd >= 0) && (FD_ISSET(fd, &fdset)))
	       {
		  if (EDebug(EDBUG_TYPE_EVENTS))
		     Eprintf("Event fd %d\n", i);
		  pfds[i].handler();
	       }
	  }
     }
}
Example #25
0
// Update the last time variable
void Timer::Update()
{
	m_LastTime = GetTimeMs();
	//TODO(ector) - QPF
}
Example #26
0
// Callback function called by GLUT to render screen
void Display(void)
{

	// Clear frame buffer
	glClearColor(0.7, 0.7, 0.7, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
	glEnable(GL_NORMALIZE);

	float lightPositon[4];
	float l = sqrtf(powf(lightDirection[0], 2) + powf(lightDirection[1], 2) + powf(lightDirection[2], 2));
	lightPositon[0] = -lightDistance*lightDirection[0] / l;
	lightPositon[1] = -lightDistance*lightDirection[1] / l;
	lightPositon[2] = -lightDistance*lightDirection[2] / l;
	lightPositon[3] = 1.0f;                                 // point light

	glUseProgram(0);
	glPushMatrix();
	glTranslatef(0.5f, -0.3f, 0.0f);
	if (g_AutoRotate)
	{
		float axis[3] = { 0, 1, 0 };
		float angle = (float)(GetTimeMs() - g_RotateTime) / 1000.0f;
		float quat[4];
		SetQuaternionFromAxisAngle(axis, angle, quat);
		MultiplyQuaternions(g_RotateStart, quat, g_Rotation);
	}
	ConvertQuaternionToMatrix(g_Rotation, mat);
	glMultMatrixf(mat);
	glScalef(g_Zoom, g_Zoom, g_Zoom);
	glCallList(DRAW_EN);
	glPopMatrix();

	GLuint currentProgram = programs[currentShader];
	if (currentShader == 1) {
		glUseProgram(0);
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
		glLightfv(GL_LIGHT0, GL_SPECULAR, lightDiffuse);
		glLightfv(GL_LIGHT0, GL_POSITION, lightPositon);

		float materialAmbient[] = { rf[0] * 0.2f, rf[1] * 0.2f, rf[2] * 0.2f };
		float materialDiffuse[] = { rf[0] * 0.6f, rf[1] * 0.6f, rf[2] * 0.6f };
		float materialSpecular[] = { 1 - rf[0] * roughness / 2, 1 - rf[1] * roughness / 2, 1 - rf[2] * roughness / 2 };
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, materialAmbient);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, materialDiffuse);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular);
		glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 24);
	} else {
		glUseProgram(currentProgram);
		glUniform1i(glGetUniformLocation(currentProgram, "env_brdf"), IBL);
		//#####glUniform1i(glGetUniformLocation(currentProgram, "env_map"), MAP);
		glUniform1i(glGetUniformLocation(currentProgram, "cubemap"), MAP);
		glUniform1i(glGetUniformLocation(currentProgram, "tex"), TEX);
		//glUniform1i(glGetUniformLocation(currentShader, "lightNum"), 0);
		//glUniform1f(glGetUniformLocation(currentProgram, "density"), lightAmbient[1]);
		//glUniform3fv(glGetUniformLocation(currentProgram, "ambient"), 1, lightAmbient);
		glLightfv(GL_LIGHT0, GL_POSITION, lightPositon);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse);
		glLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient);
		//glUniform3fv(glGetUniformLocation(currentProgram, "lightPos"), 1, lightPositon);
		//glUniform3fv(glGetUniformLocation(currentProgram, "diffuse"), 1, lightDiffuse);
		glUniform3fv(glGetUniformLocation(currentProgram, "rf"), 1, rf);
		glUniform1f(glGetUniformLocation(currentProgram, "roughness"), roughness);
		glUniform1i(glGetUniformLocation(currentProgram, "iftex"), -1);
		glUniformMatrix4fv(glGetUniformLocation(currentProgram, "g_rotation"), 1, GL_FALSE, mat);		
	}

	// Rotate and draw shape
	glPushMatrix();
	glTranslatef(0.5f, -0.3f, 0.0f);
	if (g_AutoRotate)
	{
		float axis[3] = { 0, 1, 0 };
		float angle = (float)(GetTimeMs() - g_RotateTime) / 1000.0f;
		float quat[4];
		SetQuaternionFromAxisAngle(axis, angle, quat);
		MultiplyQuaternions(g_RotateStart, quat, g_Rotation);
	}
	ConvertQuaternionToMatrix(g_Rotation, mat);
	glMultMatrixf(mat);
	glScalef(g_Zoom, g_Zoom, g_Zoom);
	glCallList(g_CurrentShape);
	glPopMatrix();

	glUseProgram(0);
	// Draw tweak bars
	TwDraw();

	// Present frame buffer
	glutSwapBuffers();

	// Recall Display at next frame
	glutPostRedisplay();
}
Example #27
0
int main(int argc, char *argv[])
{
	TwBar *bar; 
	float axis[] = { 0.7f, 0.7f, 0.0f }; 
	float angle = 0.8f;
	winW = 640;
	winH = 480;
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(640, 480);
	glutCreateWindow("Assignment3- Skinning");
	glutCreateMenu(NULL);

	glutDisplayFunc(Display);
	glutReshapeFunc(Reshape);
	atexit(Terminate);  

	TwInit(TW_OPENGL, NULL);

	glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT);

	glutMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
	glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
	glutKeyboardFunc((GLUTkeyboardfun)TwEventKeyboardGLUT);
	glutSpecialFunc((GLUTspecialfun)TwEventSpecialGLUT);
	TwGLUTModifiersFunc(glutGetModifiers);

	//Todo
	Matrices identity;
	skeletonWasp = new Skeleton("wasp_walk.skel");
	skinningWasp = new skin("wasp_walk.skin", skeletonWasp->worldMatrixes);
	animation = new Animation("wasp_walk.anim", skeletonWasp->joints);
	skeletonWasp->calculate(identity.IDENTITY);
	skinningWasp->update();
	
	bar = TwNewBar("TweakBar");
	TwDefine(" GLOBAL help='This is rotate and zoom the skeleton also to change the lighting effects' ");
	TwDefine(" TweakBar size='200 400' color='96 216 224' ");

	TwAddButton(bar, "Reset", ResetValues, NULL, " label='Resets the View' ");
	TwAddButton(bar, "Animate", StartAnimation, NULL, " label='Starts the animation' ");
	TwAddVarRW(bar, "Zoom", TW_TYPE_FLOAT, &g_Zoom,
		" min=0.01 max=2.5 step=0.01 keyIncr=z keyDecr=Z help='Scale the object (1=original size).' ");
	TwAddVarRW(bar, "ObjRotation", TW_TYPE_QUAT4F, &g_Rotation,
		" label='Object rotation' opened=true help='Change the object orientation.' ");

	TwAddVarCB(bar, "AutoRotate", TW_TYPE_BOOL32, SetAutoRotateCB, GetAutoRotateCB, NULL,
		" label='Auto-rotate' key=space help='Toggle auto-rotate mode.' ");
	TwAddVarRW(bar, "Multiplier", TW_TYPE_FLOAT, &g_LightMultiplier,
		" label='Light booster' min=0.1 max=4 step=0.02 keyIncr='+' keyDecr='-' help='Increase/decrease the light power.' ");
	TwAddVarRW(bar, "LightDir", TW_TYPE_DIR3F, &g_LightDirection,
		" label='Light direction' opened=true help='Change the light direction.' ");
	TwAddVarRW(bar, "LightDir2", TW_TYPE_DIR3F, &g_LightDirection2,
		" label='Light direction' opened=true help='Change the light direction.' ");

	TwAddVarRW(bar, "Ambient", TW_TYPE_COLOR3F, &g_MatAmbient1, " group='Material' ");

	TwAddVarRW(bar, "Diffuse", TW_TYPE_COLOR3F, &g_MatDiffuse1, " group='Material' ");

	{
		TwEnumVal shapeEV[NUM_SHAPES] = { { WASP, "Wasp" } };
		TwType shapeType = TwDefineEnum("ShapeType", shapeEV, NUM_SHAPES);
		TwAddVarRW(bar, "Shape", shapeType, &g_CurrentShape, " keyIncr='<' keyDecr='>' help='Change object shape.' ");
	}

	g_RotateTime = GetTimeMs();
	SetQuaternionFromAxisAngle(axis, angle, g_Rotation);
	SetQuaternionFromAxisAngle(axis, angle, g_RotateStart);
	CreateBar();
	glutMainLoop();

	return 0;
}
int main(void) {
    // Create the variables for the time measure
    int starttime, stoptime;
    // Create the two input vectors and instance the output vector
    int i, N;
    const int LIST_SIZE = 1;
    float *sum = (float*)malloc(sizeof(int)*LIST_SIZE);

    for(i = 0; i < LIST_SIZE; i++) {
        sum[i] = 0.4;
    }

    //Ask to the user, how many interactions he wants to see
    printf("How many interactions:\n");
    scanf("%d",&N);

    // Load the kernel source code into the array source_str
    FILE *fp;
    char *source_str;
    size_t source_size;

    fp = fopen("simplefloatadd_kernels.cl", "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char*)malloc(MAX_SOURCE_SIZE);
    source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp);
    fclose( fp );

    //Get initial time
    starttime = GetTimeMs();

    cl_uint ret_num_devices = 0;
    cl_uint ret_num_platforms = 0;

    // Use this to check the output of each API call
    cl_int ret;

    // Retrieve the number of platforms
    ret = clGetPlatformIDs(0, NULL, &ret_num_platforms);

    // Allocate enough space for each platform
    cl_platform_id *platforms = NULL;
    platforms = (cl_platform_id*)malloc(ret_num_platforms*sizeof(cl_platform_id));

    // Fill in the platforms
    ret = clGetPlatformIDs(ret_num_platforms, platforms, NULL);

    // Retrieve the number of devices
    ret = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, 0, NULL, &ret_num_devices);

    // Allocate enough space for each device
    cl_device_id *devices;
    devices = (cl_device_id*)malloc(ret_num_devices*sizeof(cl_device_id));

    // Fill in the devices
    ret = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, ret_num_devices, devices,  NULL);

    // Create an OpenCL context
    cl_context context = clCreateContext( NULL, ret_num_devices, devices, NULL, NULL, &ret);

    // Create a command queue
    cl_command_queue command_queue = clCreateCommandQueue(context, devices[0], 0, &ret);

    // Create memory buffers on the device for each vector
    cl_mem sum_mem_obj = clCreateBuffer(context, CL_MEM_WRITE_ONLY,
                                        LIST_SIZE * sizeof(int), NULL, &ret);

    // Copy the lists A and B to their respective memory buffers
    ret = clEnqueueWriteBuffer(command_queue, sum_mem_obj, CL_TRUE, 0,
                               LIST_SIZE * sizeof(int), sum, 0, NULL, NULL);

    // Create a program from the kernel source
    cl_program program = clCreateProgramWithSource(context, 1,
                         (const char **)&source_str, (const size_t *)&source_size, &ret);

    // Build the program
    ret = clBuildProgram(program, ret_num_devices, devices, NULL, NULL, NULL);

    // Create the OpenCL kernel
    cl_kernel kernel = clCreateKernel(program, "simplefloatadd", &ret);

    // Set the arguments of the kernel
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&sum_mem_obj);
    ret = clSetKernelArg(kernel, 1, sizeof(int), &N);

    // Execute the OpenCL kernel on the list
    size_t global_item_size = LIST_SIZE; // Process the entire lists
    ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL,
                                 &global_item_size, NULL, 0, NULL, NULL);

    // Read the memory buffer C on the device to the local variable C
    ret = clEnqueueReadBuffer(command_queue, sum_mem_obj, CL_TRUE, 0,
                              LIST_SIZE * sizeof(int), sum, 0, NULL, NULL);

    //Get stop time
    stoptime = GetTimeMs();

    // Display the result to the screen
    for(i = 0; i < LIST_SIZE; i++)
        printf("%d += %.1f = %.1f\n", N, 0.3, sum[0]);

    printf("Duration= %d ms\n", stoptime - starttime);

    // Clean up
    ret = clFlush(command_queue);
    ret = clFinish(command_queue);
    ret = clReleaseKernel(kernel);
    ret = clReleaseProgram(program);
    ret = clReleaseMemObject(sum_mem_obj);
    ret = clReleaseCommandQueue(command_queue);
    ret = clReleaseContext(context);
    free(sum);
    return 0;
}
void* tcp_server(void *whatever){

	struct sockaddr_in server_addr, client_addr;
	int sckt, sckt_client, status;
	int starttime, stoptime;
	char *buffer;
	socklen_t client;
	int iSetOption = 1;

	sckt = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	setsockopt(sckt, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption, sizeof(iSetOption));

	if(sckt == -1)
	{
	    printf("error opening socket\n");
	    exit(EXIT_FAILURE);
	}

	server_addr.sin_port = htons(h.port);
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //loopback interface
	server_addr.sin_family = AF_INET;

	if(bind(sckt, (struct sockaddr *)&server_addr,sizeof(struct sockaddr_in) ) == -1)
	{
	    printf("error binding socket\n");
	    exit(EXIT_FAILURE);
	}

	//keep listening
	listen(sckt,5);
	client = sizeof(client_addr);
    sckt_client = accept(sckt, (struct sockaddr *) &client_addr, &client);

    if (sckt_client < 0){
    	printf("Didn't accept\n");
    	exit(EXIT_FAILURE);
    } 

    starttime = GetTimeMs();
    buffer = (char *)calloc( 1, lSize+1 );
    status = read(sckt_client,buffer,lSize);
    if (status < 0){
    	printf("Cannot read from the socket\n");
    	exit(EXIT_FAILURE);
    }
    stoptime = GetTimeMs();

    //printf("Message: %s\n",buffer);
    printf("Duration server read = %d us\n", stoptime - starttime);

    starttime = GetTimeMs();
    status = write(sckt_client,buffer,lSize);
	if (status < 0){
	  	printf("Couldn't write the message\n");
	   	exit(EXIT_FAILURE);
	}
	stoptime = GetTimeMs();
    printf("Duration server write back = %d us\n", stoptime - starttime);

	close(sckt);
	close(sckt_client);
	pthread_exit(NULL);
	exit(EXIT_SUCCESS);
}
Example #30
0
int main(void) {
    // Create the variables for the time measure
    int starttime, stoptime;
    // Create the two input vectors
    int i;
    const int LIST_SIZE = 1024;
    int *A = (int*)malloc(sizeof(int)*LIST_SIZE);
    int *B = (int*)malloc(sizeof(int)*LIST_SIZE);
    for(i = 0; i < LIST_SIZE; i++) {
        A[i] = i;
        B[i] = LIST_SIZE - i;
    }
 
    // Load the kernel source code into the array source_str
    FILE *fp;
    char *source_str;
    size_t source_size;
 
    fp = fopen("vector_kernels.cl", "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char*)malloc(MAX_SOURCE_SIZE);
    source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp);
    fclose( fp );

    //Get the initial time
    starttime = GetTimeMs();
 
    // Get platform and device information
    cl_platform_id platform_id = NULL;
    cl_device_id device_id = NULL;   
    cl_uint ret_num_devices;
    cl_uint ret_num_platforms;
    cl_int ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
    ret = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_CPU, 1, 
            &device_id, &ret_num_devices);
 
    // Create an OpenCL context
    cl_context context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &ret);
 
    // Create a command queue
    cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
 
    // Create memory buffers on the device for each vector 
    cl_mem a_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, 
            LIST_SIZE * sizeof(int), NULL, &ret);
    cl_mem b_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY,
            LIST_SIZE * sizeof(int), NULL, &ret);
    cl_mem c_mem_obj = clCreateBuffer(context, CL_MEM_WRITE_ONLY, 
            LIST_SIZE * sizeof(int), NULL, &ret);
 
    // Copy the lists A and B to their respective memory buffers
    ret = clEnqueueWriteBuffer(command_queue, a_mem_obj, CL_TRUE, 0,
            LIST_SIZE * sizeof(int), A, 0, NULL, NULL);
    ret = clEnqueueWriteBuffer(command_queue, b_mem_obj, CL_TRUE, 0, 
            LIST_SIZE * sizeof(int), B, 0, NULL, NULL);
 
    // Create a program from the kernel source
    cl_program program = clCreateProgramWithSource(context, 1, 
            (const char **)&source_str, (const size_t *)&source_size, &ret);
 
    // Build the program
    ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);
 
    // Create the OpenCL kernel
    cl_kernel kernel = clCreateKernel(program, "vector_add", &ret);
 
    // Set the arguments of the kernel
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&a_mem_obj);
    ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&b_mem_obj);
    ret = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&c_mem_obj);
 
    // Execute the OpenCL kernel on the list
    size_t global_item_size = LIST_SIZE; // Process the entire lists
    size_t local_item_size = 64; // Divide work items into groups of 64
    ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, 
            &global_item_size, &local_item_size, 0, NULL, NULL);
 
    // Read the memory buffer C on the device to the local variable C
    int *C = (int*)malloc(sizeof(int)*LIST_SIZE);
    ret = clEnqueueReadBuffer(command_queue, c_mem_obj, CL_TRUE, 0, 
            LIST_SIZE * sizeof(int), C, 0, NULL, NULL);
 
    // Display the result to the screen
    //for(i = 0; i < LIST_SIZE; i++)
    //    printf("%d + %d = %d\n", A[i], B[i], C[i]);

    //Get final time
    stoptime = GetTimeMs();

    printf("Duration = %d ms\n", stoptime - starttime);
 
    // Clean up
    ret = clFlush(command_queue);
    ret = clFinish(command_queue);
    ret = clReleaseKernel(kernel);
    ret = clReleaseProgram(program);
    ret = clReleaseMemObject(a_mem_obj);
    ret = clReleaseMemObject(b_mem_obj);
    ret = clReleaseMemObject(c_mem_obj);
    ret = clReleaseCommandQueue(command_queue);
    ret = clReleaseContext(context);
    free(A);
    free(B);
    free(C);
    return 0;
}