Exemple #1
0
void testSerializedPCB(t_pcb *newPCB, void *pcb_buffer) {
    int auxIndex = 0;
    printf("\n===(1)Loaded PCB vs Serialized PCB===\n");

    printf("pid: %d=%d\n", newPCB->pid, *(int*)(pcb_buffer+auxIndex));
    assert(newPCB->pid == *(int*)(pcb_buffer+auxIndex));
    auxIndex+=sizeof(int);

    printf("pc: %d=%d\n", newPCB->program_counter, *(int*)(pcb_buffer+auxIndex));
    assert(newPCB->program_counter == *(int*)(pcb_buffer+auxIndex));
    auxIndex+=sizeof(int);

    printf("sp: %d=%d\n", newPCB->stack_pointer, *(int*)(pcb_buffer+auxIndex));
    assert(newPCB->stack_pointer == *(int*)(pcb_buffer+auxIndex));
    auxIndex+=sizeof(int);

    auxIndex+= printStackValuesVsBuffer(newPCB->stack_index, pcb_buffer + auxIndex);

    printf("status: %d=%d\n", newPCB->status, *(int*)(pcb_buffer+auxIndex));
    assert(newPCB->status == *(int*)(pcb_buffer+auxIndex));
    auxIndex+=sizeof(int);

    printf("instrucciones_size: %d=%d\n", newPCB->instrucciones_size, *(int*)(pcb_buffer+auxIndex));
    assert(newPCB->instrucciones_size == *(int*)(pcb_buffer+auxIndex));
    auxIndex+=sizeof(int);

    auxIndex+= printInstructions(newPCB->instrucciones_serializado, newPCB->instrucciones_size, pcb_buffer+auxIndex);

    printf("etiquetas_size: %d=%d\n", newPCB->etiquetas_size, *(int*)(pcb_buffer+auxIndex));
    assert(newPCB->etiquetas_size == *(int*)(pcb_buffer+auxIndex));
    auxIndex+=sizeof(int);
    printEtiquetas(newPCB->etiquetas, (char*)(pcb_buffer+auxIndex));
    auxIndex+=newPCB->etiquetas_size;
    assert(memcmp(newPCB->etiquetas, (char*)(pcb_buffer+auxIndex),  newPCB->etiquetas_size) == 0);
}
Exemple #2
0
// Construct window using SFML
Game::Game()
{
	//this->boidsSize = rand() % 10 - 3;
	sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
	this->_window_height = desktop.height;
	this->_window_width = desktop.width;
	this->_window.create(sf::VideoMode(_window_width, _window_height, desktop.bitsPerPixel), "Boids", sf::Style::None);
	printInstructions();
}
Exemple #3
0
properties TrainParameters(int* argc, char*** argv) {

    properties props;
    props.Kgamma = 1.0;
    props.C = 1.0;
    props.Threads=1;
    props.MaxSize=500;

    int i,j;
    for (i = 1; i < *argc; ++i) {
        if ((*argv)[i][0] != '-') break;
        if (++i >= *argc) {
            printInstructions();
            exit(1);
        }

        char* param_name = &(*argv)[i-1][1];
        char* param_value = (*argv)[i];
        if (strcmp(param_name, "g") == 0) {    	
            props.Kgamma = atof(param_value);
        } else if (strcmp(param_name, "c") == 0) {
            props.C = atof(param_value);
        } else if (strcmp(param_name, "t") == 0) {
            props.Threads = atoi(param_value);
        } else if (strcmp(param_name, "w") == 0) {
            props.MaxSize = atoi(param_value);
        } else {
            fprintf(stderr, "Unknown parameter %s\n",param_name);
            printInstructions();
            exit(2);
        }
    }
  
    for (j = 1; i + j - 1 < *argc; ++j) {
        (*argv)[j] = (*argv)[i + j - 1];
    }
    *argc -= i - 1;

    return props;

}
int main(int argc, char** argv) {
  printInstructions();
  initGLUT(&argc, argv);
  gluOrtho2D(0, W, H, 0);
  glutKeyboardFunc(keyboard);
  glutSpecialFunc(handleSpecialKeypress);
  glutPassiveMotionFunc(mouseMove);
  glutMotionFunc(mouseDrag);
  glutDisplayFunc(display);
  initPixelBuffer();
  glutMainLoop();
  atexit(exitfunc);
  return 0;
}
Exemple #5
0
void startUpMessages(void)
{
	MYSERIAL.print("Open Bionics - Artichoke V");
  MYSERIAL.println((float)VERSION_N);
  
  MYSERIAL.print(textString.board[OB_BOARD]);
  MYSERIAL.println(" board");

	MYSERIAL.print(textString.right_left[advancedSettings.handFlag-1]);
	MYSERIAL.println(" Hand");

	#if defined(USE_I2C_ADC)
	MYSERIAL.println("I2C Muscle Sensors");
	#endif
	#if defined(USE_I2C_IO)
	MYSERIAL.println("I2C Port Expander");
	#endif

	if(advancedSettings.muscleCtrlFlag > 0)
	{
		// if muscle mode is on, print on
		switch(advancedSettings.muscleCtrlFlag)
		{
			case 1:             // standard muscle control
				MYSERIAL.println("Standard Muscle Control ON");
				digitalWrite(LED_KNUCKLE,HIGH); // turn on muscle control LED in knuckle
				break;
			case 2:             // position muscle control
				MYSERIAL.println("Muscle Position Control ON");
				digitalWrite(LED_KNUCKLE,HIGH);   // turn on muscle control LED in knuckle
				break;
			default:
				break;
		}
		MYSERIAL.print("Grip Change Mode ");
		MYSERIAL.println(textString.off_on[advancedSettings.gripFlag]);
	}
	
	if(advancedSettings.instructionsFlag) 
		printInstructions();			// if instructions not turned off, print initial instructions

	// if demo mode is enabled from start up
	if(advancedSettings.demoFlag)
	{
		MYSERIAL.println("Start up demo mode ON");
		MYSERIAL.println("Enter A0 to disable this mode");
		MYSERIAL.println("The hand is only responsive to serial commands \nat the end of each demo cycle");
	}
}
Exemple #6
0
void main(int argc, char **argv)
{
	printInstructions();

	glutInit(&argc, argv);

	Init_Parent();
	Init_Intro();
	//Init_View_Mode();
	//Init_View_Play();
	//Init_Help_Menu();

	// Infinite loop
	glutMainLoop();
}
Exemple #7
0
int main(int argc, char** argv) {
  cudaMalloc(&d_vol, NX*NY*NZ*sizeof(float)); // 3D volume data
  volumeKernelLauncher(d_vol, volumeSize, id, params);
  printInstructions();
  initGLUT(&argc, argv);
  createMenu();
  gluOrtho2D(0, W, H, 0);
  glutKeyboardFunc(keyboard);
  glutSpecialFunc(handleSpecialKeypress);
  glutDisplayFunc(display);
  initPixelBuffer();
  glutMainLoop();
  atexit(exitfunc);
  return 0;
}
Exemple #8
0
int main(int argc, char** argv)
{

    //srand(getpid());	
    //srand48(getpid());

    srand(0);	
    srand48(0);

    properties props = TrainParameters(&argc, &argv);
  
    if (argc != 3) {
        printInstructions();
        return 4;
    }

    char * data_file = argv[1];
    char * data_model = argv[2];
  	

    svm_dataset dataset = readTrainFile(data_file);
    printf("\nDataset Loaded from file: %s\n\nTraining samples: %d\nNumber of features: %d\n\n",data_file, dataset.l,dataset.maxdim);

    struct timeval tiempo1, tiempo2;
    omp_set_num_threads(props.Threads);

    printf("Running IRWLS\n");	
    gettimeofday(&tiempo1, NULL);

    initMemory(props.Threads,(props.MaxSize+1));
    double * W = trainFULL(dataset,props);

    gettimeofday(&tiempo2, NULL);
    printf("\nWeights calculated in %ld\n\n",((tiempo2.tv_sec-tiempo1.tv_sec)*1000+(tiempo2.tv_usec-tiempo1.tv_usec)/1000));

    model modelo = calculateModel(props, dataset, W);

    printf("Saving model in file: %s\n\n",data_model);	
 
    FILE *Out = fopen(data_model, "w+");
    storeModel(&modelo, Out);
    fclose(Out);

    return 0;
}
int main(int argc, char** argv) {
    
    success = mesh.read(paths[0]);
    if (success) boundingBox.computeAxisAlignedBox(mesh.vertices);
    
    printInstructions();
    glutInitWindowSize(gridX, gridY);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutInit(&argc, argv);
    glutCreateWindow("Bounding Box - Axis Aligned");
    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(special);
    glutMainLoop();
    
    return 0;
}
Exemple #10
0
int main(int argc, char** argv) {
    
    success = mesh.read(path);
    mesh.computeCurvatures();
    
    printInstructions();
    glutInitWindowSize(gridX, gridY);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutInit(&argc, argv);
    glutCreateWindow("Gaussian Curvature");
    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(special);
    glutMainLoop();
    
    return 0;
}
Exemple #11
0
int main(int argc, char** argv) {

    success = mesh.read(path);
    
    printInstructions();
    glutInitWindowSize(gridX, gridY);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutInit(&argc, argv);
    std::stringstream title;
    title << "Mesh Simplification, Reduction ratio: " << percent << "%";
    glutCreateWindow(title.str().c_str());
    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(special);
    glutMainLoop();
    
    return 0;
}
Exemple #12
0
void testOldPCBvsNewPCB(t_pcb *newPCB, t_pcb *incomingPCB) {
    printf("\n===(2)Loaded PCB vs Deserialized PCB===\n");
    printf("pid: %d=%d\n", newPCB->pid, incomingPCB->pid);
    assert(newPCB->pid == incomingPCB->pid);
    printf("pc: %d=%d\n", newPCB->program_counter, incomingPCB->program_counter);
    assert(newPCB->program_counter == incomingPCB->program_counter);
    printf("sp: %d=%d\n", newPCB->stack_pointer, incomingPCB->stack_pointer);
    assert(newPCB->stack_pointer == incomingPCB->stack_pointer);
    printStackValuesVsStruct(newPCB->stack_index, incomingPCB->stack_index);
    printf("status: %d=%d\n", newPCB->status, incomingPCB->status);
    assert(newPCB->status == incomingPCB->status);
    printf("instrucciones_size: %d=%d\n", newPCB->instrucciones_size, incomingPCB->instrucciones_size);
    assert(newPCB->instrucciones_size == incomingPCB->instrucciones_size);
    printInstructions(newPCB->instrucciones_serializado, newPCB->instrucciones_size, incomingPCB->instrucciones_serializado);
    printf("etiquetas_size: %d=%d\n", newPCB->etiquetas_size, incomingPCB->etiquetas_size);
    assert(newPCB->etiquetas_size == incomingPCB->etiquetas_size);
    printEtiquetas(newPCB->etiquetas, incomingPCB->etiquetas);
    assert(memcmp(newPCB->etiquetas, incomingPCB->etiquetas,incomingPCB->etiquetas_size) == 0);
}
Exemple #13
0
int main(int argc, char** argv) {
    
    success = mesh.read(path);
    setHandleAndAnchors();

    printInstructions();
    glutInitWindowSize(gridX, gridY);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutInit(&argc, argv);
    std::string title = "Deformation, iterations: " + std::to_string(iterations);
    glutCreateWindow(title.c_str());
    init();
    glutDisplayFunc(display);
    glutMouseFunc(mousePressed);
    glutMotionFunc(mouseMove);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(special);
    glutMainLoop();
    
    return 0;
}
/*
This function is called before entering the main rendering loop.
Use it for all your initialisation stuff
*/
void init(GLWrapper *glw)
{
	printInstructions();
	textureLoad = textureLoader();
	/* Set the object transformation controls to their initial values */
	x = 0;
	y = 0;
	z = 0;
	angle_x = 0;
	angle_y = angle_z = 0;
	angle_inc_x = angle_inc_y = angle_inc_z = 0;
	scale = 0.33f;
	aspect_ratio = 1.3333f;
	colourmode = 0;
	weather = 0;

	px, py, pz = 0;

	// Generate index (name) for one vertex array object
	glGenVertexArrays(1, &vao);

	// Create the vertex array object and make it current
	glBindVertexArray(vao);

	/* Define the Blending function */
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	GLfloat vertexColours[] =
	{
		0.0f, 0.0f, 1.0f, 1.0f,
		0.0f, 0.0f, 1.0f, 1.0f,
		0.0f, 0.0f, 1.0f, 1.0f,
		0.0f, 0.0f, 1.0f, 1.0f,
		0.0f, 0.0f, 1.0f, 1.0f,
		0.0f, 0.0f, 1.0f, 1.0f
	};

	/* Create the colours buffer for the cube */
	glGenBuffers(1, &colourObject);
	glBindBuffer(GL_ARRAY_BUFFER, colourObject);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertexColours), vertexColours, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);


	/* Load and create our monkey object*/
	birchTree.load_obj("birch_tree.obj");
	walls.createRoom(roomLength, roomHeight);
	walls.setTexture(textureLoad.loadTexture("images/brickwork_texture.png", program));
	walls.setNormalsMap(textureLoad.loadNormals("images/brickwork_normal_map.png", program));

	flooring.createFloor(roomLength, roomHeight);
	flooring.setTexture(textureLoad.loadTexture("images/masonry_wall_texture.png", program));
	flooring.setNormalsMap(textureLoad.loadNormals("images/masonry_wall_normal_map.png", program));

	//sky.createSky();
	createPlanters();


	/* Calculate vertex normals using cross products from the surrounding faces*/
	/* A better way to do this would be to generate the vertex normals in Blender and
	/* then extract the vertex normals from the face definitions and use that to create an
	/* accurate array of veretx normals */
	birchTree.smoothNormals();
	birchTree.createObject();


	tree2 = tree3 = tree4 = tree5 = tree6 = tree6 = tree8 = tree9 = birchTree;
	
	/* Load and build the vertex and fragment shaders */
	try
	{
		particle_program = glw->LoadShader("particle_object.vert", "particle_object.frag");
		program = glw->LoadShader("terrain.vert", "terrain.frag");
	}
	catch (std::exception &e)
	{
		std::cout << "Caught exception: " << e.what() << std::endl;
		std::cin.ignore();
		exit(0);
	}

	/* Define uniforms to send to vertex shader */
	modelID = glGetUniformLocation(program, "model");
	colourmodeID = glGetUniformLocation(particle_program, "weather");
	viewID = glGetUniformLocation(program, "view");
	projectionID = glGetUniformLocation(program, "projection");

	

	/* Define the texture behaviour parameters */
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);

	particleObject.create(particle_program);
	/* Create the heightfield object */
	
	octaves = 1;
	perlin_scale = 1.0f;
	perlin_frequency = 50.0f;
	land_size = 15.0f;
	snow = new terrain_object(octaves, perlin_frequency, perlin_scale);
	snow->createTerrain(1000, 1000, land_size, land_size);
	snow->createObject();
	snow->setTexture(textureLoad.loadTexture("images/snow.png", program));
}
Exemple #15
0
static bool pollKeyboard(void)
{
    bool result = false;
    uint8_t ch;
    
    if (!kbhit())
        return result;
    
    ch = cgetc();
    switch (ch) {
        case 'i':
        case 'I':
        case CH_CURS_UP:
            if (!isAppleButtonPressed()) {
                moveDir(DIR_UP);
                break;
            }
            // Fallthrough...
        case 139:
            result = swapDir(DIR_UP);
            break;
            
        case 'j':
        case 'J':
        case CH_CURS_LEFT:
            if (!isAppleButtonPressed()) {
                moveDir(DIR_LEFT);
                break;
            }
            // Fallthrough...
        case 136:
            result = swapDir(DIR_LEFT);
            break;
            
        case 'k':
        case 'K':
        case CH_CURS_RIGHT:
            if (!isAppleButtonPressed()) {
                moveDir(DIR_RIGHT);
                break;
            }
            // Fallthrough...
        case 149:
            result = swapDir(DIR_RIGHT);
            break;
            
        case 'm':
        case 'M':
        case CH_CURS_DOWN:
            if (!isAppleButtonPressed()) {
                moveDir(DIR_DOWN);
                break;
            }
            // Fallthrough...
        case 138:
            result = swapDir(DIR_DOWN);
            break;
            
        case CH_ESC:
        case 'q':
        case 'Q':
            if (gShouldSave) {
                videomode(VIDEOMODE_80x24);
                mixedTextMode();
                gotoxy(0, 0);
                cprintf("Saving your game so you can continue\r\n    later...");
                saveGame();
            }
            quitGame();
            break;
            
        case 'r':
        case 'R':
            refreshScore(0);
            startNewGame();
            gShouldSave = false;
            return true;
            
        case 'o':
        case 'O':
            selectOptions();
            showAndClearDblLoRes();
            drawBoard();
            break;
            
        case 'h':
        case 'H':
            getHint();
            break;
            
        case '?':
            printInstructions();
            showAndClearDblLoRes();
            drawBoard();
            break;
            
        default:
            badThingHappened();
            break;
    }
    
    return result;
}
int main(int argc, char *argv[])
{
    // Initialize read and write files
    FILE *ifp = fopen(argv[1], "r");
    FILE *ofp = fopen(argv[2], "w+");

    // Exit program if a file was not opened
    if(ifp == NULL) { printf("Input File Not Found\n");  return 0; }
    if(ofp == NULL) { printf("Output File Not Found\n"); return 0; }

    // Register architecture
    int BP = 1; // Base Pointer
    int SP = 0; // Stack Pointer
    int PC = 0; // Program Counter
    instruction *IR; // Instructions (Opcode, Lexi. Level, Parameter)
    int prev;

    // Initialize stack
    int stack[MAX_STACK_HEIGHT];
    memset(stack, 0, MAX_STACK_HEIGHT * sizeof(int));

    // Create and intialize an array of structs
    instruction instructions[MAX_CODE_LENGTH];
    read(ifp, instructions);

    // Close input file
    fclose(ifp);

    // Print the instructions to be executed
    printInstructions(ofp, instructions);

    // Print header for the stacktrace
    fprintf(ofp, "\n\n\t\t\t\t\tPC\tBP\tSP\tStack \nInitial Values \t\t\t\t\t%d\t%d\t%d\n", 0, 1, stack[0]);

    printf("Fetch -> Execute Cycle\n");

    // Fetch -> Execute Cycle
    bool halt = false;
    while(halt == false)
    {
        // Get instruction
        IR = &instructions[PC];

        // Save last program counter
        prev = PC;

        // Set instructions for cleaner usage
        int OP = IR->OP;
        int L = IR->L;
        int M = IR->M;

        switch(OP)
        {
            // LIT - Push value M onto the stack
            case 1:
                SP++;
                stack[SP] = M;
                PC++;
                break;
            /* OPR - Return from a procedure call
             *       or do an ALU op, specified by M */
            case 2:
                switch(M)
                {
                    // Return from a procedure call
                    case 0:
                       SP = BP - 1;
                       PC = stack[SP + 4];
                       BP = stack[SP + 3];
                        break;
                    // NEG - Pop once -> push the negation of the result
                    case 1:
                        stack[SP] = -stack[SP];
                        break;
                    // ADD - Pop twice -> add -> push
                    case 2:
                        SP--;
                        stack[SP] = stack[SP] + stack[SP + 1];
                        break;
                    // SUB - Pop twice -> subtract top value from bottom value -> push
                    case 3:
                        SP--;
                        stack[SP] = stack[SP] - stack[SP + 1];
                        break;
                    // MUL - Pop twice -> multiply -> push
                    case 4:
                        SP--;
                        stack[SP] = stack[SP] * stack[SP + 1];
                        break;
                    // DIV - Pop twice -> divide top value from bottom value -> push
                    case 5:
                        SP--;
                        stack[SP] = stack[SP] / stack[SP + 1];
                        break;
                    // ODD - Pop once -> push 1 if odd and 0 if even
                    case 6:
                        stack[SP] = stack[SP] % 2;
                        break;
                    // MOD - Pop twice -> mod top value from bottom value -> push
                    case 7:
                        SP--;
                        stack[SP] = stack[SP] % stack[SP + 1];
                        break;
                    // EQL - Pop twice -> push 1 if first = second, 0 otherwise
                    case 8:
                        SP--;
                        stack[SP] = stack[SP] == stack[SP + 1];
                    // NEQ - Pop twice -> push 1 if first does not equal second, 0 otherwise
                    case 9:
                        SP--;
                        stack[SP] = stack[SP] != stack[SP + 1];
                        break;
                    // LSS - Pop twice -> push 1 if second < first, 0 otherwise
                    case 10:
                        SP--;
                        stack[SP] = stack[SP] < stack[SP + 1];
                        break;
                    // LEQ - Pop twice -> push 1 if second <= first, 0 otherwise
                    case 11:
                        SP--;
                        stack[SP] = stack[SP] <= stack[SP + 1];
                        break;
                    // GTR - Pop twice -> push 1 if second > first, 0 otherwise
                    case 12:
                        SP--;
                        stack[SP] = stack[SP] > stack[SP + 1];
                    // GEQ - Pop twice -> push 1 if second >= first, 0 otherwise
                    case 13:
                        SP--;
                        stack[SP] = stack[SP] >= stack[SP + 1];
                }
                break;
            // LOD - Read the value at offset M, L levels down, and push onto stack
            case 3:
                SP++;
                stack[SP] = stack[base(L, BP, stack) + M];
                PC++;
                break;
            // STO - Pop the stack and write value into offset M, L levels down
            case 4:
                stack[base(L, BP, stack) + M] = stack[SP];
                stack[SP] = 0;
                SP--;
                PC++;
                break;
            // CAL - Call the procedure at M
            case 5:
                stack[SP + 1] = 0;
                stack[SP + 2] = base(L, BP, stack);
                stack[SP + 3] = BP;
                stack[SP + 4] = PC + 1;
                BP = SP + 1;
                PC = M;
                break;
            // INC - Allocate space for M local variables, will always allocate atleast 4
            case 6:
                SP = SP + M;
                PC++;
                break;
            // JMP - Branch to M
            case 7:
                PC = M;
                break;
            // JPC - Pop the stack and branch to M if result is 0
            case 8:
                if(stack[SP] == 0)
                    PC = M;
                else
                    PC++;
                SP--;
                break;
            // SIO 1 - Pop the stack and write result to screen
            case 9:
                printf("%d\n", stack[SP]);
                SP--;
                PC++;
                break;
            // SIO 2 - Take user input and push on the stack
            case 10:
                printf("Enter Value:\n");
                SP++;
                scanf("%d", &stack[SP]);
                PC++;
                break;
            // SIO 3 - Terminate
            case 11:
                printf("Halt\n");
                halt = true;
                BP = 0;
                PC = 0;
                SP = 0;
                break;
            default:
                printf("Invalid Opcode\n");
                return 0;
        }

        // Print the stacktrace for the instructions that were just executed
        printStacktrace(ofp, prev, IR, PC, BP, SP, stack);
    }

    // Close
    fclose(ofp);

    return 0;
}
int main(int argc, char *argv[])
{
    char *shader = "mandelbrot (copy).frag";
    if (argc > 1)
    {
        shader = argv[1];
    }

    glfwInit();



    /*int major, minor, rev;
    glfwGetGLVersion(&major, &minor, &rev);
    printf("using openGL %d.%d.%d\n", major, minor, rev);*/

    GLFWvidmode mode;
    glfwGetDesktopMode( &mode );

    window_width = mode.Width;
    window_height = mode.Height;

    printf("%dx%d\n", window_width, window_height);
    //glfwOpenWindow(window_width, window_height, 5, 6, 5, 0, 8, 0, GLFW_FULLSCREEN);
    glfwOpenWindow(mode.Width, mode.Height, mode.RedBits,  mode.GreenBits, mode.BlueBits, 0, 0, 0, GLFW_FULLSCREEN);

    // setup opengl perspective stuff.
    glMatrixMode(GL_PROJECTION);
    float aspect_ratio = ((float)window_height) / window_width;
    glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1, 50);
    glDisable( GL_DEPTH_TEST );
    glTranslatef(0.0, 0.0, -1.00);
    glClearColor(0.0, 1.0, 1.0, 0.0);


    // will create and set shader program.
    GLhandleARB program = SetupFragmentShader(shader);
    // get the location of all the uniforms
    prepareUniforms(program);
    // must call use program before setting uniforms values
    glUseProgram(program);

    uint param_i = 0;
    parameters[WIDTH]   = createParameter1i(program, "wW", window_width );
    parameters[HEIGHT]  = createParameter1i(program, "wH", window_height );
    parameters[TIME]    = createParameter1f(program, "time", 0.0 );
    parameters[MINX]    = createParameter1f(program, "minx", -2.0);
    parameters[MINY]    = createParameter1f(program, "miny", 1.0);
    parameters[DELTA]   = createParameter1f(program, "deltax", 3.0);
    parameters[THETA]   = createParameter1f(program, "theta", 1.0);
    //synchParameters ( parameters );

    /*for ( param_i = 0; param_i < NPARAMS; param_i++ )
    {
        Parameter *param = &parameters[param_i];
        switch ( param->utype )
        {
            case INT:
                glUniform1i(param->loc, param->u.ival);
                break;
            case FLOAT:
                glUniform1f(param->loc, param->u.fval);
                break;
            default:
                break;
        }
    }*/

    // set the dimension, must be after program is used.
    //glUniform1i(wWLoc, window_width );
    //glUniform1i(wHLoc, window_height );

    printInstructions();

    double frame_start = glfwGetTime();
    double frame_time = 0.0;
    double temp_time = 0.0;

    //bool need_draw = true;
    bool need_view_synch = true;


    int mouseWheel = 0;
    int mouseWheelDelta = 0;

    double fIterations = (double)(iterations);

    int mouseX, mouseY, curMouseX, curMouseY;
    mouseX = mouseY = 0;

    bool joystickPresent = glfwGetJoystickParam( GLFW_JOYSTICK_1, GLFW_PRESENT );
    if(joystickPresent)
    {
        printf("Joystick present. Can be used to navigate in addition to mouse.\n");
    }else
    {
        printf("no joystick present.\n");
    }

    // set up fonts

    FTGLfont *font = NULL;
    //font = ftglCreateBufferFont("/usr/share/fonts/truetype/freefont/FreeMono.ttf");
    font = ftglCreatePixmapFont("/usr/share/fonts/truetype/freefont/FreeMono.ttf");
    if( !font )
    {
        printf("failed to load font.");
    }
    ftglSetFontFaceSize(font, 50, 50);
    //printf("%d\n", ftglGetFontError(font));
    //ftglSetFontCharMap(font, ft_encoding_unicode);
    //printf("%d\n", ftglGetFontError(font));

    bool show_fps = true;
    char text[256];

    // keep on rendering the frame until escape is pressed.
    while(glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS)
    {
        temp_time = glfwGetTime();
        frame_time = temp_time - frame_start;
        frame_start = temp_time;

        // process input
        if(glfwGetKey('E') == GLFW_PRESS)
        {
            printf("minx: %.31f\n", minx);
            printf("miny: %.31f\n", miny);
            printf("deltax: %.31f\n",deltax);
            printf("deltay: %.31f\n",deltay);
            printf("====================================\n");
        }else if(glfwGetKey('P') == GLFW_PRESS)
        {
            saveFrameBuffer();
        }else if(glfwGetKey('R') == GLFW_PRESS)
        {
            minx = -2.0;
            miny = -1.0;
            deltax = 3.0;
            deltay = 2.0;
            need_view_synch = true;
        }else if(glfwGetKey('F') == GLFW_PRESS)
        {
            show_fps=~show_fps;
            //printf("fps display toggled to: %d\n", show_fps);
        }

        else if(glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS)
        {
            fIterations += 5*(60*frame_time);
            iterations = floor(fIterations);
            need_view_synch = true;
        }else if(glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS)
        {
            if(iterations>1)
            {
                fIterations -= 5*(60*frame_time);
            }
            iterations = floor(fIterations);
            need_view_synch = true;
        }
        // zooming using the arrow keys
        if(glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS)
        {
            zoomIn(2.0*zoom_factor*(frame_time*60.0));
            need_view_synch = true;
        }else if(glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS)
        {
            zoomIn(-2.0*zoom_factor*(frame_time*60.0));
            need_view_synch = true;
        }

        //changing the julia set constant
        if(glfwGetKey('W') == GLFW_PRESS)
        {
            realc += .0025*frame_time*60.0;
            need_view_synch = true;
        }else if(glfwGetKey('S') == GLFW_PRESS)
        {
            realc -= .0025*frame_time*60.0;
            need_view_synch = true;
        }
        if(glfwGetKey('A') == GLFW_PRESS)
        {
            imagc += .0025*frame_time*60.0;
            need_view_synch = true;
        }else if(glfwGetKey('D') == GLFW_PRESS)
        {
            imagc -= .0025*frame_time*60.0;
            need_view_synch = true;
        }

        // changing the area visible (panning left and right)
        glfwGetMousePos(&curMouseX, &curMouseY);
        int mouseDeltax = curMouseX - mouseX;
        int mouseDeltay = curMouseY - mouseY;

        if(mouseDeltax||mouseDeltay)//if one of them is different
        {
            //printf("delta coordinates: (%d, %d)\n", mouseDeltax, mouseDeltay);
            mouseX=curMouseX;
            mouseY=curMouseY;
            //printf("new mouse coordinates: (%d, %d)\n", x, y);
            pan(zoom_factor*deltax*mouseDeltax/20.0, -1*zoom_factor*deltay*mouseDeltay/20.0);
            need_view_synch = true;
        }
        if(joystickPresent)
        {
            float pos[4];
            glfwGetJoystickPos(GLFW_JOYSTICK_1, pos, 4);
            //the above function gives us bad results for my particular joystick :(, must fiddle around with numbers to get correct answer.
            float xJoyPos = pos[0];//(pos[0]*32767)/128.0 - 1.0;
            float yJoyPos = pos[1];//(pos[1]*32767)/128.0 + 1.0;
            float zJoyPos = -1*pos[2];//-1*((pos[2]*32767)/128.0 - 1.0);
            float rJoyPos = pos[3];
            float temp = 0.0;
            //printf("%f\n", xJoyPos);

            if(xJoyPos>.02||xJoyPos<-.02)
            {
                temp = zoom_factor*xJoyPos*deltax*1.0*frame_time*60.0;
                pan(temp, 0);
                need_view_synch = true;
            }
            if(yJoyPos>.02||yJoyPos<-.02)
            {
                temp = zoom_factor*yJoyPos*deltay*1.0*frame_time*60.0;
                pan(0, temp);
                need_view_synch = true;
            }
            if(zJoyPos>.04||zJoyPos<-.04)
            {
                zoomIn(zJoyPos*scroll_zoom_factor*(frame_time*10.0));
                need_view_synch = true;
            }
            if(rJoyPos>.02 || rJoyPos<-.02)
            {
                rotate( rJoyPos/5.0*frame_time );
                need_view_synch = true;
            }
            unsigned char buttons[5];

            glfwGetJoystickButtons(GLFW_JOYSTICK_1, buttons, 4);
            if(buttons[0]==GLFW_PRESS)
            {
                saveFrameBuffer();
            }
            if(buttons[1]==GLFW_PRESS)
            {
                rotate( 0.35*frame_time );
                need_view_synch = true;
            }else if(buttons[2]==GLFW_PRESS)
            {
                rotate( -0.35*frame_time );
                need_view_synch = true;
            }

            //printf("x:%f, y:%f\n", xJoyPos, yJoyPos);
        }

        // zooming using the mouse scroll
        mouseWheelDelta = glfwGetMouseWheel() - mouseWheel;
        mouseWheel = mouseWheel+mouseWheelDelta;
        if(mouseWheelDelta != 0)
        {
            zoomIn(mouseWheelDelta*scroll_zoom_factor*(frame_time*60.0));
            need_view_synch = true;
        }

        //printf("mouse wheel: %d\n", mouseWheelDelta);

        if(need_view_synch)
        {
            synchVariableUniforms();
            need_view_synch = false;
        }

        // update the time inside the shader for cool animations.

        parameters[2].val.fval = frame_start;
        parameters[2].needs_update = true;

        synchParameters ( parameters );

        //glUniform1f(timeLoc, frame_start);

        // write fps and iterations to a string.
        sprintf(text, "FPS: %4.1d; ITER: %d; ZOOMX: %-10.1f", (int)(floor(1.0/frame_time)), iterations, (3.0/deltax));

        //sprintf("fps %f\n", 1.0/frame_time);

        // clear the buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //since all calculations are being done in the fragment shader, all we draw is a surface.
        glUseProgram(program);
        glRects(-1, -1, 1, 1);

        // render font on top of this?
        if(show_fps != 0){
            glUseProgram(0);
            glColor3f(0.0f, 0.0f, 0.0f);
            ftglRenderFont(font, text, FTGL_RENDER_ALL);
            glUseProgram(program);
        }
        // note: swap buffers also updates the input events for glfw
        glfwSwapBuffers();
    }
    // clean up the font and exit.
    ftglDestroyFont(font);
    return 1;
}
Exemple #18
0
//This is the main function.  It takes arguments from the command line to determine
//the wheel size to use and whether or not to print out the primes.
int main(int argc, char *argv[])
{
    int wheelSize;
    u_int64_t maxNum;

    //Checks the program was passed the proper number of arguments
    if (( argc < 3 ) || ( argc > 4))
    {
        printInstructions(argv[0]);
        return 1;
    }

    //Get command line arguments
    maxNum = strtol(argv[1], NULL, 0);;
    wheelSize = atoi(argv[2]);

    //Checks the passed arguments are all integers and within bounds
    if ((maxNum == 0) || (maxNum > MAX_NUMBER) || (wheelSize <= 0) || (wheelSize > 6))
    {
        printInstructions(argv[0]);
        return 1;
    }

    int i;
    int j;

    for (j = 0; j < PARRAY_SIZE; j++)
    {
        lastNum[j] = 0;
        lastCycle[j] = 1;
    }

    //This conditional makes sure we get all the primes desired
    if (maxNum < 210)
    {
        //If we're looking for a small number of primes, just sieve up to 210
        maxSlots = 21;
    }
    else
    {
        if (maxNum%10 == 0)
        {
            maxSlots = maxNum/10;
        }
        else
        {
            maxSlots = maxNum/10+1;
        }
    }

    //Checks that the wheel size doesn't exceed the number of slots we're using
    u_int64_t wheelCheck = getWheelSize(wheelSize);
    if (wheelCheck > maxSlots)
    {
        printf("Error: Wheel size specified is larger than the Max slots specified.\n");
        printf("Please try smaller wheel size\n");
        return 1;
    }

    //malloc memory for the table, which is a bit field of 8-bit integers, that keeps
    //track of all the primes
    if ((table = (u_int8_t *) malloc(maxSlots*sizeof(u_int8_t))) == NULL)
    {
        printf("Error: problem allocating memory for the table\n");
        return 1;
    }

    //The first four primes are hardcoded.
    primes[0] = 2;
    primes[1] = 3;
    primes[2] = 5;
    primes[3] = 7;

    //Set the values in the table for 3's cycle.  3 generates (Z/10,+) (The group of
    //integers mod 10 under addition) every 30 numbers.
    table[0] = 5;
    table[1] = 15;
    table[2] = 10;

    //Set tabslot to 21 since 3's cycle takes 30 numbers, 7's cycle takes 70 numbers.
    //Their cycles both start with no overlap at 210, which is 3*7*10.
    tabslot = 21;

    //Copy the values for 3's cycle until it completes through 210
    for (i = 3; i<tabslot; i+=3)
    {
        table[i] = table[0];
        table[i+1] = table[1];
        table[i+2] = table[2];
    }

    //Remove 3 as a potential prime for future cycles
    table[0] = 1;

    //
    switch (maxSlots%3)
    {
    case 0:
    {
        //We're already done
        break;
    }
    case 1:
    {
        table[i] = table[0];
        break;
    }
    case 2:
    {
        table[i] = table[0];
        table[i+1] = table[1];
        break;
    }
    default:
    {
        printf("Error: hit the default case while filling the table with 3's wheel\n");
        return 1;
    }
    }

    //Get primes up to 49
    getPrimes(3);

    //Mark off wheels up to wheelSize and then roll the wheel to maxSlots
    int nextPrime = rollWheel(wheelSize, 3);

    //Get primes up to the square of the next prime number
    getPrimes(nextPrime);
    nextPrime++;

    //Determine if single or multithreaded and mark off remaining composites
    //If BLOCK_SIZE>maxSlots, just ignore NUM_THREADS and use single thread
    if ((NUM_THREADS == 1) || (BLOCK_SIZE > maxSlots))
    {
        finishPrimes(nextPrime);
    }
    else if (NUM_THREADS > 1)
    {
        multiFinishPrimes(nextPrime);
    }
    else
    {
        printf("Error: NUM_THREADS must be greater than or equal to 1\n");
        printf("Please change the value of NUM_THREADS and recompile\n");
        exit(-1);
    }

    //If a fourth argument is supplied at runtime, print the list of primes.
    if (argv[3])
    {
        singlePrintPrimes(maxNum);
    }

    //Cleanup
    //free(table);

}
void interpretPrompt(References* r, CPUStatus* cpu, int* status)
{
    // show prompt ready
    printf("> ");
    fflush(stdout);

    // get new command
    char* line = (char*) calloc(MAX_STRING_LENGTH, sizeof(char));
    if (line == NULL)
    {
        perror("calloc error in interpretPrompt\n");
        exit(EXIT_FAILURE);
    }
    if (fgets(line, MAX_STRING_LENGTH, stdin) == NULL)
    {
        perror("fgets error in interpretPrompt\n");
        exit(EXIT_FAILURE);
    }

    // remove endline
    removeEndLine(line);

    int assembleCode = 0;

    // interpreter commands
    if (stringEquals(line, "regs") == 0)
    {
        printRegisters(cpu);
        *status = RUN_COMMAND;
        free(line);
        return;
    } else if (stringEquals(line, "mem") == 0)
    {
        printMemory(cpu);
        *status = RUN_COMMAND;
        free(line);
        return;
    } else if (stringEquals(line, "exit") == 0)
    {
        *status = EXECUTE_HALT;
        free(line);
        return;
    } else if (stringEquals(line, "show") == 0)
    {
        printInstructions(r);
        *status = RUN_COMMAND;
        free(line);
        return;
    } else
    {
        // assemble One Pass
        assembleCode = onePass(r, cpu, line);
    }

    // execute interpreter
    if (assembleCode == ASSEMBLE_OK ||
        (assembleCode == ASSEMBLE_LABEL && r->currentAddress > 4))
    {
        interpret(r, cpu, status);
    }

    free(line);
}
Exemple #20
0
int main(){
    //imposta il seme del random al tempo attuale. Necessario per la funzione rand()
    srand(time(0));

    /*                                                                                  *\
    **  Ciclo principale, chiede la modalita' di gioco e inizializza il ciclo di gioco  **
    **  Decide casualmente il giocatore iniziale.                                       **
    \*                                                                                  */

    do{
        emptyArray(gameBoard);
        printf("Seleziona modalita:\n 0 -- umano vs pc\n 1 -- umano vs umano\n 2 -- pc vs pc\n");
        scanf("%d", &mod);
        if(mod == -1){
            break;
        }

        if(rand() % 2 + 1 == 1){
            turn = 1;
            printf("Giocatore 2 inizia per primo.\n");
        }
        else{
            turn = 0;
            printf("Giocatore 1 inizia per primo.\n");
        }

        /*                                                                                      *\
        **  Ciclo di gioco. Inizia cercando un vincitore.                                       **
        **  In base alla modalita' selezionata e al turno, richiede un input al giocatore umano **
        **  o calcola le mosse dell'IA.                                                         **
        **  Stampa il campo da gioco e infine controlla se il e' pieno                          **
        \*                                                                                      */

        do{
            if(checkForWinner(gameBoard) == 1 || checkForWinner(gameBoard) == 2){
                break;
            }

            if(turn == 0 && pc == 2 || turn == 1 && pc == 1){
                printf("-------------------\n");
                (mod == 0 || mod == 2) ? printf("Turno del computer\n") : printf("Turno del giocatore 1\n");
                printf("-------------------\n");

                if(mod == 1) printInstructions();

                (mod == 0 || mod == 2) ? (moveResult = elaborateMove(gameBoard, pc)) : (moveResult = makeMove(gameBoard, pc));
            }
            else if(turn == 0 && player == 2 || turn == 1 && player == 1){

                printf("-------------------\n");
                (mod == 2) ? printf("Turno del computer\n") : printf("Turno del giocatore 2\n");
                printf("-------------------\n");

                printInstructions();

                (mod == 2) ? (moveResult = elaborateMove(gameBoard, player)) : (moveResult = makeMove(gameBoard, player));
            }

            if(moveResult != -1){
                if(turn == 0){
                    turn = 1;
                }
                else{
                    turn = 0;
                }
            }
            else{
                printf("Partita terminata.\n");
                turn = -1;
            }

            createTable(gameBoard);

            if(gameBoardFull(gameBoard) && turn != -1){
                checkForWinner(gameBoard);
                turn = -1;
            }
        }while(turn != -1);
        turn = 0;
    }while(mod != -1);

    getchar();
}
Exemple #21
0
/*
	Initial function, called before display
*/
void init(GLWrapper *glw)
{
	printInstructions();
	angle_x = 0.0f;
	angle_x_inc = 0.0f;
	angle_y = 0.0f;
	angle_y_inc = 0.0f;
	angle_z = 0.0f;
	angle_z_inc = 0.1f;
	scale_val = 1.0;
	move_model_x = 0;
	move_model_y = 0;
	move_model_z = 0;
	look_x = 0;
	look_y = 0;
	look_z = 0;

	aspect_ratio = 1.3333f;

	// Generate index (name) for one vertex array object
	glGenVertexArrays(1, &vao);

	// Create the vertex array object and make it current
	glBindVertexArray(vao);


	/* Define an array of colours */
	float vertexColours[] = {
		0.627f, 0.627f, 0.627f, 1.0f
	};
	
	/* Create vec4 arrays for each object and vec3 arrays to contain normals*/
	Gear gear;
	glm::vec4 * gearTest = gear.createGear(radius, sides, teeth, 0.195f, 0.0f);
	glm::vec3 * gearOneNormal = gear.calculateNormals(gearTest, sides, teeth);
	glm::vec4 * gearTwo = gear.createGear(0.3, 10, 5, 0.180f, 35.0f);
	glm::vec3 * gearTwoNormal = gear.calculateNormals(gearTwo, 10, 5);
	glm::vec4 * gearThree = gear.createGear(radius, sides, teeth, 0.195f, 24.0f);
	glm::vec3 * gearThreeNormal = gear.calculateNormals(gearThree, sides, teeth);
	glm::vec4 * gearFour = gear.createGear(1.0, 26, 16, 0.195f, 10.0f);
	glm::vec3 * gearFourNormal = gear.calculateNormals(gearFour, 26, 20);
	Crank crankClass;
	glm::vec4 * crank = crankClass.buildCrank();
	glm::vec3 * crankNormal = crankClass.calculateNormals(crank);
	
	/* Create a vertex buffer object to store vertices */
	glGenBuffers(1, &positionBufferGearOne);
	glBindBuffer(GL_ARRAY_BUFFER, positionBufferGearOne);
	glBufferData(GL_ARRAY_BUFFER, (368 * sizeof(glm::vec4)), gearTest, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	/* Create a vertex buffer object to store normals */
	glGenBuffers(1, &gearOneNormals);
	glBindBuffer(GL_ARRAY_BUFFER, gearOneNormals);
	glBufferData(GL_ARRAY_BUFFER, (368 * sizeof(glm::vec3)), gearOneNormal, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	/* Create a vertex buffer object to store vertices */
	glGenBuffers(1, &positionBufferGearTwo);
	glBindBuffer(GL_ARRAY_BUFFER, positionBufferGearTwo);
	glBufferData(GL_ARRAY_BUFFER, (368 * sizeof(glm::vec4)), gearTwo, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	/* Create a vertex buffer object to store normals */
	glGenBuffers(1, &gearTwoNormals);
	glBindBuffer(GL_ARRAY_BUFFER, gearTwoNormals);
	glBufferData(GL_ARRAY_BUFFER, (368 * sizeof(glm::vec3)), gearTwoNormal, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	/* Create a vertex buffer object to store vertices */
	glGenBuffers(1, &positionBufferGearThree);
	glBindBuffer(GL_ARRAY_BUFFER, positionBufferGearThree);
	glBufferData(GL_ARRAY_BUFFER, (368 * sizeof(glm::vec4)), gearThree, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	/* Create a vertex buffer object to store normals */
	glGenBuffers(1, &gearThreeNormals);
	glBindBuffer(GL_ARRAY_BUFFER, gearThreeNormals);
	glBufferData(GL_ARRAY_BUFFER, (368 * sizeof(glm::vec3)), gearThreeNormal, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	/* Create a vertex buffer object to store vertices */
	glGenBuffers(1, &positionBufferGearFour);
	glBindBuffer(GL_ARRAY_BUFFER, positionBufferGearFour);
	glBufferData(GL_ARRAY_BUFFER, (700 * sizeof(glm::vec4)), gearFour, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	/* Create a vertex buffer object to store normals */
	glGenBuffers(1, &gearFourNormals);
	glBindBuffer(GL_ARRAY_BUFFER, gearFourNormals);
	glBufferData(GL_ARRAY_BUFFER, (700 * sizeof(glm::vec3)), gearFourNormal, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	/* Create a vertex buffer object to store vertices */
	glGenBuffers(1, &positionBufferCrank);
	glBindBuffer(GL_ARRAY_BUFFER, positionBufferCrank);
	glBufferData(GL_ARRAY_BUFFER, (72 * sizeof(glm::vec4)), crank, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	/* Create a vertex buffer object to store normals */
	glGenBuffers(1, &crankNormals);
	glBindBuffer(GL_ARRAY_BUFFER, crankNormals);
	glBufferData(GL_ARRAY_BUFFER, (72 * sizeof(glm::vec3)), crankNormal, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);


	/* Create a vertex buffer object to store vertex colours */
	glGenBuffers(1, &colourObject);
	glBindBuffer(GL_ARRAY_BUFFER, colourObject);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertexColours), vertexColours, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	try
	{
		program = glw->LoadShader("lab2.vert", "lab2.frag");
	}
	catch (std::exception &e)
	{
		std::cout << "Caught exception: " << e.what() << std::endl;
		std::cin.ignore();
		exit(0);
	}

	/* Define uniforms to send to vertex shader */
	modelID = glGetUniformLocation(program, "model");
	viewID = glGetUniformLocation(program, "view");
	projectionID = glGetUniformLocation(program, "projection");
}
Exemple #22
0
void manageSerialSettings(void)
{
	if(serialCmd.fingerNum != BLANK)
	{
		MYSERIAL.print("\n");
		MYSERIAL.print("Finger ");
		MYSERIAL.println(serialCmd.fingerNum);
		
		MYSERIAL.print("Direction ");
		if(serialCmd.direction != BLANK)
			MYSERIAL.println(textString.open_close[serialCmd.direction]);
		else
		{	
			int fingerDir = !finger[serialCmd.fingerNum].readDir();
			MYSERIAL.println(textString.open_close[fingerDir]);
		}
		
		MYSERIAL.print("Stop Position ");
		if(serialCmd.stopPos != BLANK)
			MYSERIAL.println(serialCmd.stopPos);
		else
		MYSERIAL.println("None");
		
		MYSERIAL.print("Speed ");
		if(serialCmd.speed != BLANK)
			MYSERIAL.println(serialCmd.speed);
		else
			MYSERIAL.println(finger[serialCmd.fingerNum].readTargetSpeed());

		fingerControl(serialCmd.fingerNum, serialCmd.stopPos, serialCmd.direction, serialCmd.speed);
	}
	else if(serialCmd.gripNum != BLANK)
	{
		MYSERIAL.print("Grip ");
		MYSERIAL.println(textString.grips[serialCmd.gripNum]);
		
		MYSERIAL.print("Direction ");
		if(serialCmd.direction != BLANK)
			MYSERIAL.println(textString.open_close[serialCmd.direction]);
		else
			MYSERIAL.println("None");
		
		MYSERIAL.print("Stop Position ");
		if(serialCmd.stopPos != BLANK)
			MYSERIAL.println(serialCmd.stopPos);
		else
			MYSERIAL.println((100 * serialCmd.direction));
			
		MYSERIAL.print("Speed ");
		if(serialCmd.speed != BLANK)
			MYSERIAL.println(serialCmd.speed);
		else
		{
			int fingerToRead = (serialCmd.gripNum==THUMBSUP_GRIP)?FINGER0:FINGER1;
			MYSERIAL.println(finger[fingerToRead].readTargetSpeed());
		}
			
		MYSERIAL.print("\n");

		gripMovement(serialCmd.gripNum, serialCmd.stopPos, serialCmd.direction, serialCmd.speed);
	}
  
	else if(serialCmd.instructionsFlag != BLANK)
	{
		printInstructions();
	}
  
	else if(serialCmd.advancedFlag != BLANK)
	{
		switch(serialCmd.advancedFlag)
		{
			case 0: // demo mode
				advancedSettings.demoFlag = !advancedSettings.demoFlag;   // toggle flag
				demoFlag = advancedSettings.demoFlag;      
				MYSERIAL.print("Demo mode toggled ");
				MYSERIAL.println(textString.off_on[advancedSettings.demoFlag]); // print ON/OFF
				break;
			case 1: // serial instructions
				advancedSettings.instructionsFlag = !advancedSettings.instructionsFlag; // toggle flag
				MYSERIAL.print("Initial serial instructions toggled ");
				MYSERIAL.println(textString.off_on[advancedSettings.instructionsFlag]); // print ON/OFF
				break;
			case 2: // muscle graph
				advancedSettings.muscleGraphFlag = !advancedSettings.muscleGraphFlag; // toggle flag
				MYSERIAL.print("Muscle graph mode toggled ");
				MYSERIAL.println(textString.off_on[advancedSettings.muscleGraphFlag]);  // print ON/OFF
				break;
			case 3: // motor enable/disable
				advancedSettings.motorEnable = !advancedSettings.motorEnable;   // toggle flag
				MYSERIAL.print("Motors ");
				
				MYSERIAL.println(textString.disabled_enabled[advancedSettings.motorEnable]);  // print Disabled/Enabled
				for(int i=0;i<NUM_FINGERS;i++)
				{
					if(advancedSettings.motorEnable)
						finger[i].enableMotor();
					else
						finger[i].disableMotor();
				}
				break;
			case 5: // motors emergency stop
				stopMotors();
				MYSERIAL.println("Stop Motors");
				break;
			case 10:
				advancedSettings.researchFlag = !advancedSettings.researchFlag;
				MYSERIAL.print("Research mode 1 toggled ");
				MYSERIAL.println(textString.off_on[advancedSettings.researchFlag]);
				break;
#ifdef HANDLE_EN
			case 11:
				advancedSettings.HANDle_en = !advancedSettings.HANDle_en;
				MYSERIAL.print("HANDle mode ");
				MYSERIAL.println(textString.disabled_enabled[advancedSettings.HANDle_en]);
				EEPROM_writeStruct(ADVANCED_CTRL_LOC, advancedSettings);
				break;
			case 12:
				toggleHANDleSerial();
				break;
#endif
			default:
				break;
		}
		EEPROM_writeStruct(ADVANCED_CTRL_LOC,advancedSettings);   // save settings to EEPROM
	}
  
	else if(serialCmd.muscleCtrlFlag != BLANK)
	{
		switch(serialCmd.muscleCtrlFlag)
		{
			case -1:            // default
				break;
			case 0:             // muscle control off
				advancedSettings.muscleCtrlFlag = 0;
				MYSERIAL.println("Muscle control OFF ");
				digitalWrite(LED_KNUCKLE,LOW);  // turn off muscle control LED in knuckle
				break;
			case 1:             // standard muscle control
				advancedSettings.muscleCtrlFlag = 1;
				MYSERIAL.println("Standard muscle control ON");
				digitalWrite(LED_KNUCKLE,HIGH);   // turn on muscle control LED in knuckle
				break;
			case 2:             // position muscle control
				advancedSettings.muscleCtrlFlag = 2;
				MYSERIAL.println("Muscle position control ON");
				digitalWrite(LED_KNUCKLE,HIGH);   // turn on muscle control LED in knuckle
				break;
			case 3:             // print muscle readings
				if(advancedSettings.muscleCtrlFlag != 0)
				{
					printADCvals = !printADCvals;
					MYSERIAL.print("Display muscle readings ");
					MYSERIAL.println(textString.off_on[printADCvals]);     // print ON/OFF
				}
				break;
			default:
				break;
		}
      
		EEPROM_writeStruct(ADVANCED_CTRL_LOC,advancedSettings);   // store muscle mode in EEPROM
	}
 
	else if(serialCmd.handFlag != BLANK)  // if 'H#'
	{
		if(serialCmd.handFlag != 0)
		{
			advancedSettings.handFlag = serialCmd.handFlag;
			IOconfig();             // reconfigure finger pins
			EEPROM_writeStruct(ADVANCED_CTRL_LOC,advancedSettings);    // store hand in EEPROM
		}
		MYSERIAL.print("Hand is ");
		MYSERIAL.println(textString.right_left[advancedSettings.handFlag-1]); // print which hand is entered
	}
 
	else if(serialCmd.demoFlag == 0) // if 'D'
	{
		demoFlag = 1;
		MYSERIAL.println("Demo Mode");
		MYSERIAL.println(" The hand is only responsive to serial commands\n at the end of each demo cycle");
	}
  
	else if(serialCmd.sensitivityAdjust != BLANK)
	{
		if(serialCmd.sensitivityAdjust != 0)
		{
			userSettings.sensitivityOffset = serialCmd.sensitivityAdjust;
			EEPROM_writeStruct(USER_SETTINGS_LOC,userSettings);
		}
		MYSERIAL.print("Muscle sensor sensitivity ");
		MYSERIAL.println(userSettings.sensitivityOffset);
	}
  
	else if(serialCmd.noiseFloor != BLANK)
	{
		runNoiseFloorCalc();
	}

	else if(serialCmd.holdTime != BLANK)
	{
		if(serialCmd.holdTime != 0)
		{
			userSettings.holdTime = serialCmd.holdTime;
			EEPROM_writeStruct(USER_SETTINGS_LOC,userSettings);
		}
		MYSERIAL.print("Grip change hold duration ");
		MYSERIAL.println(userSettings.holdTime);
	}

	// if research mode == 1, and no other command is recognised, use CSV string as target motor positions 
	else if (advancedSettings.researchFlag == 1)		// if 'A10'
	{
		researchMode_CSV_RX(serialCmd.cmdBuff);
	}

	clearAll();									// clear all serial commands (clear serialCmd.buffs)
}