993 lines · 28.2 KB · C++
RawDownload
////  //  Interface//   //  Show a field of objects rendered in 3D, with yaw and pitch of scene driven //  by accelerometer data//  serial port connected to Maple board/arduino. ////  Keyboard Commands: ////  / = toggle stats display//  spacebar = reset gyros/head//  h = render Head//  l = show incoming gyro levels// #include "InterfaceConfig.h"#include <iostream>#include <fstream>#include <math.h>#include <string.h>#include <sstream>#include <stdio.h>#include <stdlib.h> #ifdef _WIN32#include "Syssocket.h"#include "Systime.h"#else#include <sys/time.h>#include <arpa/inet.h>#include <ifaddrs.h>#endif #include <pthread.h> #include <glm/glm.hpp>#include "Field.h"#include "world.h"#include "Util.h"#ifndef _WIN32#include "Audio.h"#endif#include "Head.h"#include "Hand.h"#include "Particle.h"#include "Texture.h"#include "Cloud.h"#include <AgentList.h>#include "VoxelSystem.h"#include "Lattice.h"#include "Finger.h"#include "Oscilloscope.h"#include "UDPSocket.h"#include "SerialInterface.h"#include <SharedUtil.h> using namespace std; int audio_on = 1;                   //  Whether to turn on the audio supportint simulate_on = 1;  AgentList agentList('I');pthread_t networkReceiveThread;bool stopNetworkReceiveThread = false; //  For testing, add milliseconds of delay for received UDP packetsint packetcount = 0;int packets_per_second = 0; int bytes_per_second = 0;int bytescount = 0; //  Getting a target location from other machine (or loopback) to displayint target_x, target_y; int target_display = 0; int head_mirror = 1;                  //  Whether to mirror own head when viewing itint sendToSelf = 1; int WIDTH = 1200; int HEIGHT = 800; int fullscreen = 0; Oscilloscope audioScope(256,200,true); #define HAND_RADIUS 0.25            //  Radius of in-world 'hand' of youHead myHead;                        //  The rendered head of oneself glm::vec3 box(WORLD_SIZE,WORLD_SIZE,WORLD_SIZE);ParticleSystem balls(0,                      box,                      false,                     //  Wrap?                     0.02f,                      //  Noise                     0.3f,                       //  Size scale                      0.0                        //  Gravity                     ); Cloud cloud(20000,                         //  Particles            box,                           //  Bounding Box            false                          //  Wrap            ); VoxelSystem voxels; Lattice lattice(160,100);Finger myFinger(WIDTH, HEIGHT);Field field; #ifndef _WIN32Audio audio(&audioScope, &myHead);#endif #define RENDER_FRAME_MSECS 8int steps_per_frame = 0; float yaw =0.f;                         //  The yaw, pitch for the avatar headfloat pitch = 0.f;                      //      float start_yaw = 122;float render_pitch = 0.f;float render_yaw_rate = 0.f;float render_pitch_rate = 0.f; float lateral_vel = 0.f; //  Where one's own agent begins in the world (needs to become a dynamic thing passed to the program)glm::vec3 start_location(6.1f, 0, 1.4f); float fwd_vel = 0.0f; int stats_on = 0;					//  Whether to show onscreen text overlay with stats int noise_on = 0;					//  Whether to add random noise float noise = 1.0;                  //  Overall magnitude scaling for random noise levels  int step_on = 0;                    int display_levels = 0;int display_head = 0;int display_field = 0; int display_head_mouse = 1;         //  Display sample mouse pointer controlled by head movementint head_mouse_x, head_mouse_y; int head_lean_x, head_lean_y; int mouse_x, mouse_y;				//  Where is the mouseint mouse_start_x, mouse_start_y;   //  Mouse location at start of last down clickint mouse_pressed = 0;				//  true if mouse has been pressed (clear when finished) int nearbyAgents = 0;               //  How many other people near you is the domain server reporting? int speed; ////  Serial USB Variables//  SerialInterface serialPort; int latency_display = 1;//int adc_channels[NUM_CHANNELS];//float avg_adc_channels[NUM_CHANNELS];//int sensor_samples = 0;//int sensor_LED = 0; glm::vec3 gravity;int first_measurement = 1;//int samplecount = 0; //  Frame rate Measurement int framecount = 0;                  float FPS = 120.f;timeval timer_start, timer_end;timeval last_frame;double elapsedTime; // Particles char texture_filename[] = "images/int-texture256-v4.png";unsigned int texture_width = 256;unsigned int texture_height = 256;  float particle_attenuation_quadratic[] =  { 0.0f, 0.0f, 2.0f }; // larger Z = smaller particlesfloat pointer_attenuation_quadratic[] =  { 1.0f, 0.0f, 0.0f }; // for 2D view #ifdef MARKER_CAPTURE     /***  Marker Capture ***/    #define MARKER_CAPTURE_INTERVAL 1    MarkerCapture marker_capturer(CV_CAP_ANY); // Create a new marker capturer, attached to any valid camera.    MarkerAcquisitionView marker_acq_view(&marker_capturer);    bool marker_capture_enabled = true;    bool marker_capture_display = true;    IplImage* marker_capture_frame;    IplImage* marker_capture_blob_frame;    pthread_mutex_t frame_lock; #endif  //  Every second, check the frame rates and other stuffvoid Timer(int extra){    gettimeofday(&timer_end, NULL);    FPS = (float)framecount / ((float)diffclock(&timer_start, &timer_end) / 1000.f);    packets_per_second = (float)packetcount / ((float)diffclock(&timer_start, &timer_end) / 1000.f);    bytes_per_second = (float)bytescount / ((float)diffclock(&timer_start, &timer_end) / 1000.f);   	framecount = 0;    packetcount = 0;    bytescount = 0;    	glutTimerFunc(1000,Timer,0);    gettimeofday(&timer_start, NULL);        //  Ping the agents we can see    agentList.pingAgents();     if (0) {        //  Massive send packet speed test        timeval starttest, endtest;        gettimeofday(&starttest, NULL);        char junk[1000];        junk[0] = 'J';        for (int i = 0; i < 10000; i++)        {//            agentSocket.send((char *)"192.168.1.38", AGENT_UDP_PORT, junk, 1000);        }        gettimeofday(&endtest, NULL);        float sendTime = static_cast<float>( diffclock(&starttest, &endtest) );        printf("packet test = %4.1f\n", sendTime);    }        // if we haven't detected gyros, check for them now    if (!serialPort.active) {        serialPort.pair();    }} void display_stats(void){	//  bitmap chars are about 10 pels high     char legend[] = "/ - toggle this display, Q - exit, H - show head, M - show hand, T - test audio";    drawtext(10, 15, 0.10f, 0, 1.0, 0, legend);        char stats[200];    sprintf(stats, "FPS = %3.0f  Pkts/s = %d  Bytes/s = %d ",             FPS, packets_per_second,  bytes_per_second);    drawtext(10, 30, 0.10f, 0, 1.0, 0, stats);     if (serialPort.active) {        sprintf(stats, "ADC samples = %d, LED = %d",                 serialPort.getNumSamples(), serialPort.getLED());        drawtext(300, 30, 0.10f, 0, 1.0, 0, stats);    }        //  Output the ping times to the various agents //    std::stringstream pingTimes;//    pingTimes << "Agent Pings, msecs:";//    for (int i = 0; i < getAgentCount(); i++) {//        pingTimes << " " << getAgentAddress(i) << ": " << getAgentPing(i);//    }//    drawtext(10,50,0.10, 0, 1.0, 0, (char *)pingTimes.str().c_str());     std::stringstream voxelStats;    voxelStats << "Voxels Rendered: " << voxels.getVoxelsRendered();    drawtext(10,70,0.10f, 0, 1.0, 0, (char *)voxelStats.str().c_str());         /*    std::stringstream angles;    angles << "render_yaw: " << myHead.getRenderYaw() << ", Yaw: " << myHead.getYaw();    drawtext(10,50,0.10, 0, 1.0, 0, (char *)angles.str().c_str());    */        /*    char adc[200];	sprintf(adc, "location = %3.1f,%3.1f,%3.1f, angle_to(origin) = %3.1f, head yaw = %3.1f, render_yaw = %3.1f",            -location[0], -location[1], -location[2],            angle_to(myHead.getPos()*-1.f, glm::vec3(0,0,0), myHead.getRenderYaw(), myHead.getYaw()),            myHead.getYaw(), myHead.getRenderYaw());    drawtext(10, 50, 0.10, 0, 1.0, 0, adc);     */    } void initDisplay(void){    //  Set up blending function so that we can NOT clear the display    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    glEnable(GL_BLEND);    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);    glShadeModel (GL_SMOOTH);    glEnable(GL_LIGHTING);    glEnable(GL_LIGHT0);    glEnable(GL_DEPTH_TEST);    //    load_png_as_texture(texture_filename);     if (fullscreen) glutFullScreen();} void init(void){    voxels.init();    myHead.setRenderYaw(start_yaw);     head_mouse_x = WIDTH/2;    head_mouse_y = HEIGHT/2;     head_lean_x = WIDTH/2;    head_lean_y = HEIGHT/2;        //  Initialize Field values    field = Field();    printf( "Field Initialized.\n" );     if (noise_on) {           myHead.setNoise(noise);    }    myHead.setPos(start_location);        char output[] = "I";    char address[] = "10.0.0.10";    agentList.getAgentSocket().send(address, 40106, output, 1);        #ifdef MARKER_CAPTURE    if(marker_capture_enabled){        marker_capturer.position_updated(&position_updated);        marker_capturer.frame_updated(&marker_frame_available);        if(!marker_capturer.init_capture()){            printf("Camera-based marker capture initialized.\n");        }else{            printf("Error initializing camera-based marker capture.\n");        }    }#endif            gettimeofday(&timer_start, NULL);    gettimeofday(&last_frame, NULL);} void terminate () {    // Close serial port    //close(serial_fd);     #ifndef _WIN32    audio.terminate();    #endif    stopNetworkReceiveThread = true;    pthread_join(networkReceiveThread, NULL);        exit(EXIT_SUCCESS);} void reset_sensors(){    //      //   Reset serial I/O sensors     //     myHead.setRenderYaw(start_yaw);        yaw = render_yaw_rate = 0;     pitch = render_pitch = render_pitch_rate = 0;    lateral_vel = 0;    myHead.setPos(start_location);    fwd_vel = 0.0;    head_mouse_x = WIDTH/2;    head_mouse_y = HEIGHT/2;    head_lean_x = WIDTH/2;    head_lean_y = HEIGHT/2;         myHead.reset();        if (serialPort.active) {        serialPort.resetTrailingAverages();    }} void simulateHand(float deltaTime) {    //  If mouse is being dragged, send current force to the hand controller    if (mouse_pressed == 1)    {        //  Add a velocity to the hand corresponding to the detected size of the drag vector        const float MOUSE_HAND_FORCE = 1.5;        float dx = mouse_x - mouse_start_x;        float dy = mouse_y - mouse_start_y;        glm::vec3 vel(dx*MOUSE_HAND_FORCE, -dy*MOUSE_HAND_FORCE*(WIDTH/HEIGHT), 0);        myHead.hand->addVelocity(vel*deltaTime);    }} void simulateHead(float frametime)//  Using serial data, update avatar/render position and angles{//    float measured_pitch_rate = serialPort.getRelativeValue(PITCH_RATE);//    float measured_yaw_rate = serialPort.getRelativeValue(YAW_RATE);        float measured_pitch_rate = 0;    float measured_yaw_rate = 0;        //float measured_lateral_accel = serialPort.getRelativeValue(ACCEL_X);    //float measured_fwd_accel = serialPort.getRelativeValue(ACCEL_Z);        myHead.UpdatePos(frametime, &serialPort, head_mirror, &gravity);        //  Update head_mouse model     const float MIN_MOUSE_RATE = 30.0;    const float MOUSE_SENSITIVITY = 0.1f;    if (powf(measured_yaw_rate*measured_yaw_rate +              measured_pitch_rate*measured_pitch_rate, 0.5) > MIN_MOUSE_RATE)    {        head_mouse_x += measured_yaw_rate*MOUSE_SENSITIVITY;        head_mouse_y += measured_pitch_rate*MOUSE_SENSITIVITY*(float)HEIGHT/(float)WIDTH;     }    head_mouse_x = max(head_mouse_x, 0);    head_mouse_x = min(head_mouse_x, WIDTH);    head_mouse_y = max(head_mouse_y, 0);    head_mouse_y = min(head_mouse_y, HEIGHT);        //  Update render direction (pitch/yaw) based on measured gyro rates    const int MIN_YAW_RATE = 100;    const int MIN_PITCH_RATE = 100;        const float YAW_SENSITIVITY = 0.02;    const float PITCH_SENSITIVITY = 0.05;        if (fabs(measured_yaw_rate) > MIN_YAW_RATE)      {           if (measured_yaw_rate > 0)            render_yaw_rate += (measured_yaw_rate - MIN_YAW_RATE) * YAW_SENSITIVITY * frametime;        else             render_yaw_rate += (measured_yaw_rate + MIN_YAW_RATE) * YAW_SENSITIVITY * frametime;    }    if (fabs(measured_pitch_rate) > MIN_PITCH_RATE)     {        if (measured_pitch_rate > 0)            render_pitch_rate += (measured_pitch_rate - MIN_PITCH_RATE) * PITCH_SENSITIVITY * frametime;        else             render_pitch_rate += (measured_pitch_rate + MIN_PITCH_RATE) * PITCH_SENSITIVITY * frametime;    }             render_pitch += render_pitch_rate;        // Decay render_pitch toward zero because we never look constantly up/down     render_pitch *= (1.f - 2.0*frametime);     //  Decay angular rates toward zero     render_pitch_rate *= (1.f - 5.0*frametime);    render_yaw_rate *= (1.f - 7.0*frametime);        //  Update slide left/right based on accelerometer reading    /*    const int MIN_LATERAL_ACCEL = 20;    const float LATERAL_SENSITIVITY = 0.001;    if (fabs(measured_lateral_accel) > MIN_LATERAL_ACCEL)     {        if (measured_lateral_accel > 0)            lateral_vel += (measured_lateral_accel - MIN_LATERAL_ACCEL) * LATERAL_SENSITIVITY * frametime;        else             lateral_vel += (measured_lateral_accel + MIN_LATERAL_ACCEL) * LATERAL_SENSITIVITY * frametime;    }*/     //slide += lateral_vel;    lateral_vel *= (1.f - 4.0*frametime);        //  Update fwd/back based on accelerometer reading    /*    const int MIN_FWD_ACCEL = 20;    const float FWD_SENSITIVITY = 0.001;        if (fabs(measured_fwd_accel) > MIN_FWD_ACCEL)     {        if (measured_fwd_accel > 0)            fwd_vel += (measured_fwd_accel - MIN_FWD_ACCEL) * FWD_SENSITIVITY * frametime;        else             fwd_vel += (measured_fwd_accel + MIN_FWD_ACCEL) * FWD_SENSITIVITY * frametime;     }*/    //  Decrease forward velocity    fwd_vel *= (1.f - 4.0*frametime);            //  Update own head data    myHead.setRenderYaw(myHead.getRenderYaw() + render_yaw_rate);    myHead.setRenderPitch(render_pitch);    //myHead.setPos(glm::vec3(location[0], location[1], location[2]));        //  Get audio loudness data from audio input device    float loudness, averageLoudness;    #ifndef _WIN32    audio.getInputLoudness(&loudness, &averageLoudness);    myHead.setLoudness(loudness);    myHead.setAverageLoudness(averageLoudness);    #endif     //  Send my streaming head data to agents that are nearby and need to see it!    const int MAX_BROADCAST_STRING = 200;    char broadcast_string[MAX_BROADCAST_STRING];    int broadcast_bytes = myHead.getBroadcastData(broadcast_string);    agentList.broadcastToAgents(broadcast_string, broadcast_bytes);} 

Lines 1–500 of 993.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t