コード例 #1
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
void servo_out_handler(const lcm_recv_buf_t *rbuf, const char* channel, const lcmt_deltawing_u *msg, void *user) {

    Hud *hud = (Hud*)user;

    hud->SetServoCommands((msg->throttle - 1100) * 100/797, (msg->elevonL-1000)/10.0, (msg->elevonR-1000)/10.0);
    hud->SetAutonomous(msg->is_autonomous);
}
コード例 #2
0
ファイル: main.cpp プロジェクト: aystarik/loader
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(basicdrawing);

    QApplication app(argc, argv);
    Hud window;
    window.show();
    return app.exec();
}
コード例 #3
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
void log_size_handler(const lcm_recv_buf_t *rbuf, const char* channel, const lcmt_log_size *msg, void *user) {
    Hud *hud = (Hud*)user;

    // plane number is the last character of the channel name
    char last_char = channel[strlen(channel)-1];
    int plane_number = last_char - '0'; // this converts a single character to an integer
                                        // and is standards conforming C

    hud->SetPlaneNumber(plane_number);
    hud->SetLogNumber(msg->log_number);
}
コード例 #4
0
void RealTimeTest::run() {

	game.initialize();
	game.getPopupHelpScreen()->hide();
	Hud *testingHud = game.getHudsManager()->createHud(HudAlignment::RIGHT);
	testingHud->setText("TESTING...");
	
	std::thread startHoverTest(RealTimeTest::hover);
	std::thread startMaxSpeadTest(RealTimeTest::maxSpead);
	
	game.run();
	
	startHoverTest.join();
	startMaxSpeadTest.join();
	
	delete testingHud;
}
コード例 #5
0
void RealTimeTest::maxSpead() {
    
	Hud *maxSpeadTestingHud = game.getHudsManager()->createHud(HudAlignment::RIGHT);
	maxSpeadTestingHud->setText("MAX SPEAD TESTING STARTED...");
	
	DelayCommand dc(15);
	dc.execute();
	
	Helicopter *helicopter = game.getHelicopter();
	JoystickMoveForward jmf(helicopter->getJoystick());
	RotorNeutral rn(helicopter->getMainRotor());
	float oldV = 0;
	float newV = 0;
	
	std::cout << "\nmaxSpead test started:" << std::endl;
	
	game.getConfiguration()->activateFriction();
	helicopter->reset();
	helicopter->setPosistion(osg::Vec3f(0, 0, 600));
	jmf.execute();
	rn.execute();
	
	
	do {
		oldV = newV;
		dc.execute();
		newV = helicopter->getVelocity().x();
	} while (oldV < newV);
	
	
	// viscous resistance = v * (6 * WORLD_PI * 0.001 * 4)
	// if joystick(theta = 15, phi = 0) and throttle(9.8), then
	// ax = sin15 * 9.8 = 0.2588 * 9.8 = 2.53624
	// viscous resistance should be equal 2.53624
	// v * (6 * WORLD_PI * 0.001 * 4) = 2.53624 <= now solve for v
	// v = 2.53624 / (6 * WORLD_PI * 0.001 * 4)
	// v = 33.6379
	Assert(33.6379, helicopter->getVelocity().x(), 0.01);
	
	std::cout << "maxSpead test passed" << std::endl;
	std::cout << "maxSpead test results:" << std::endl;
	std::cout << "vx = " << helicopter->getVelocity().x() << std::endl;
    maxSpeadTestingHud->setText("HOVER TESTING PASSED...");
}
コード例 #6
0
void RealTimeTest::hover() {
	
	Hud *hoverTestingHud = game.getHudsManager()->createHud(HudAlignment::RIGHT);
	hoverTestingHud->setText("HOVER TESTING STARTED...");
	
	DelayCommand dc(2);
	DelayCommand wait10s(10);
	dc.execute();
	
	std::cout << "\nhover test started:" << std::endl;
	
	game.getConfiguration()->deactivateFriction();
	Helicopter *helicopter = game.getHelicopter();
	
	helicopter->reset();
	helicopter->setPosistion(osg::Vec3f(0, 0, 0));
	helicopter->getMainRotor()->increaseMagnitude();
	helicopter->getMainRotor()->increaseMagnitude();
	helicopter->getMainRotor()->increaseMagnitude();
	
	wait10s.execute();
	
	
	// after 10s should be at position 15m
	// a = 0.3
	// x = 0 + 0*10 + 0.5 * 0.3 * (10)^2 = 15
	// v = 0 + a * t
	// v = 0.3 * 10 = 3
    
	Assert(15.0, helicopter->getPosistion().z(), 1.0e-1);
	Assert(3.0, helicopter->getVelocity().z(), 1.0e-1);
	Assert(0.3, helicopter->getAcceleration().z(), 1.0e-1);
	
	std::cout << "hover test passed" << std::endl;
	std::cout << "hover test results:" << std::endl;
	std::cout << "pz = " << helicopter->getPosistion().z() << std::endl;
	std::cout << "vz = " << helicopter->getVelocity().z() << std::endl;
	std::cout << "az = " << helicopter->getAcceleration().z() << std::endl;
    
	hoverTestingHud->setText("HOVER TESTING PASSED...");
}
コード例 #7
0
Hud* HudsManager::createHud(HudAlignment hudAlignment) {
	Hud *hud = new Hud();
	unsigned long hudPosition;
	
	hud->initializeHudText();
	
	if (hudAlignment == HudAlignment::LEFT) {
		this->leftHuds.push_back(hud);
		hud->setPosition(osg::Vec3(10, this->initial_Y_Position, 0));
	} else {
		this->rightHuds.push_back(hud);
		hud->setPosition(osg::Vec3(900, this->initial_Y_Position, 0));
	}
	
	hud->setText("");
	osg::Camera *hudCamera = hud->getHudCamera();
	game->getRoot()->addChild(hudCamera);
	
	
	// update huds positions
	hudPosition = this->leftHuds.size();
	for (Hud* h : this->leftHuds)
		h->setPosition(osg::Vec3(h->getPosition().x(), ((hudPosition--) * 25) + this->initial_Y_Position + 10, 0));

	hudPosition = this->rightHuds.size();
	for (Hud* h : this->rightHuds)
		h->setPosition(osg::Vec3(h->getPosition().x(), ((hudPosition--) * 25) + this->initial_Y_Position + 10, 0));
	
	return hud;
}
コード例 #8
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
void mav_pose_t_handler(const lcm_recv_buf_t *rbuf, const char* channel, const mav_pose_t *msg, void *user) {
    Hud *hud = (Hud*)user;

    hud->SetAltitude(msg->pos[2]);
    hud->SetOrientation(msg->orientation[0], msg->orientation[1], msg->orientation[2], msg->orientation[3]);
    hud->SetAcceleration(msg->accel[0], msg->accel[1], msg->accel[2]);
    hud->SetAirspeed(msg->vel[0]);

    hud->SetTimestamp(msg->utime);
}
コード例 #9
0
ファイル: main.cpp プロジェクト: joaoB/Pacman
void onDisplay(void) {
    // cams.projection(winW, winH);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    cams.look();
    lights.display(&pacman);

    //draw stuff
    maze.draw();
    if (!maze.getPacmanDeathTime()) { //pacman is alive
        pacman.draw();
    }
    else particles.draw();
    mazeFloor.draw();
    ghosts.draw();
    hud.draw(winW, winH, &maze);
    glFlush();
}
コード例 #10
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
int main(int argc, char *argv[])
{
    // get input arguments

    string configFile = "";
    string video_file_left = "", video_file_right = "", video_directory = "";
    int starting_frame_number = 0;
    bool enable_gamma = false;
    float random_results = -1.0;

    int last_frame_number = -1;

    int last_playback_frame_number = -2;

    ConciseArgs parser(argc, argv);
    parser.add(configFile, "c", "config", "Configuration file containing camera GUIDs, etc.", true);
    parser.add(show_display, "d", "show-dispaly", "Enable for visual debugging display. Will reduce framerate significantly.");
    parser.add(show_display_wait, "w", "show-display-wait", "Optional argument to decrease framerate for lower network traffic when forwarding the display.");
    parser.add(show_unrectified, "u", "show-unrectified", "When displaying images, do not apply rectification.");
    parser.add(disable_stereo, "s", "disable-stereo", "Disable online stereo processing.");
    parser.add(force_brightness, "b", "force-brightness", "Force a brightness setting.");
    parser.add(force_exposure, "e", "force-exposure", "Force an exposure setting.");
    parser.add(quiet_mode, "q", "quiet", "Reduce text output.");
    parser.add(video_file_left, "l", "video-file-left", "Do not use cameras, instead use this video file (also requires a right video file).");
    parser.add(video_file_right, "t", "video-file-right", "Right video file, only for use with the -l option.");
    parser.add(video_directory, "i", "video-directory", "Directory to search for videos in (for playback).");
    parser.add(starting_frame_number, "f", "starting-frame", "Frame to start at when playing back videos.");
    parser.add(display_hud, "v", "hud", "Overlay HUD on display images.");
    parser.add(record_hud, "x", "record-hud", "Record the HUD display.");
    parser.add(file_frame_skip, "p", "skip", "Number of frames skipped in recording (for playback).");
    parser.add(enable_gamma, "g", "enable-gamma", "Turn gamma on for both cameras.");
    parser.add(random_results, "R", "random-results", "Number of random points to produce per frame.  Can be a float in which case we'll take a random sample to decide if to produce the last one.  Disables real stereo processing.  Only for debugging / analysis!");
    parser.add(publish_all_images, "P", "publish-all-images", "Publish all images to LCM");
    parser.parse();

    // parse the config file
    if (ParseConfigFile(configFile, &stereoConfig) != true)
    {
        fprintf(stderr, "Failed to parse configuration file, quitting.\n");
        return -1;
    }

    if (video_file_left.length() > 0
        && video_file_right.length() <= 0) {

        fprintf(stderr, "Error: for playback you must specify both "
            "a right and left video file. (Only got a left one.)\n");

        return -1;
    }

     if (video_file_left.length() <= 0
        && video_file_right.length() > 0) {

        fprintf(stderr, "Error: for playback you must specify both "
            "a right and left video file. (Only got a right one.)\n");

        return -1;
    }

    recording_manager.Init(stereoConfig);

    // attempt to load video files / directories
    if (video_file_left.length() > 0) {
        if (recording_manager.LoadVideoFiles(video_file_left, video_file_right) != true) {
            // don't have videos, bail out.
            return -1;
        }
    }

    if (video_directory.length() > 0) {
        if (recording_manager.SetPlaybackVideoDirectory(video_directory) != true) {
            // bail
            return -1;
        }
    }

    recording_manager.SetQuietMode(quiet_mode);
    recording_manager.SetPlaybackFrameNumber(starting_frame_number);



    uint64 guid = stereoConfig.guidLeft;
    uint64 guid2 = stereoConfig.guidRight;

    // start up LCM
    lcm_t * lcm;
    lcm = lcm_create (stereoConfig.lcmUrl.c_str());


    unsigned long elapsed;

    Hud hud;


    // --- setup control-c handling ---
    struct sigaction sigIntHandler;

    sigIntHandler.sa_handler = control_c_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;

    sigaction(SIGINT, &sigIntHandler, NULL);
    // --- end ctrl-c handling code ---

    dc1394error_t   err;
    dc1394error_t   err2;


    // tell opencv to use only one core so that we can manage our
    // own threading without a fight
    setNumThreads(1);

    if (recording_manager.UsingLiveCameras()) {
        d = dc1394_new ();
        if (!d)
            cerr << "Could not create dc1394 context" << endl;

        d2 = dc1394_new ();
        if (!d2)
            cerr << "Could not create dc1394 context for camera 2" << endl;

        camera = dc1394_camera_new (d, guid);
        if (!camera)
        {
            cerr << "Could not create dc1394 camera... quitting." << endl;
            exit(1);
        }

        camera2 = dc1394_camera_new (d2, guid2);
        if (!camera2)
            cerr << "Could not create dc1394 camera for camera 2" << endl;
        // reset the bus
        dc1394_reset_bus(camera);
        dc1394_reset_bus(camera2);

        // setup
        err = setup_gray_capture(camera, DC1394_VIDEO_MODE_FORMAT7_1);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not setup camera");

        err2 = setup_gray_capture(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
        DC1394_ERR_CLN_RTN(err2, cleanup_and_exit(camera2), "Could not setup camera number 2");

        // enable camera
        err = dc1394_video_set_transmission(camera, DC1394_ON);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not start camera iso transmission");
        err2 = dc1394_video_set_transmission(camera2, DC1394_ON);
        DC1394_ERR_CLN_RTN(err2, cleanup_and_exit(camera2), "Could not start camera iso transmission for camera number 2");

        InitBrightnessSettings(camera, camera2, enable_gamma);
    }

    if (show_display) {

        namedWindow("Input", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Input2", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Stereo", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);

        namedWindow("Left Block", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Right Block", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);

        namedWindow("Debug 1", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Debug 2", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);



        setMouseCallback("Input", onMouse); // for drawing disparity lines
        setMouseCallback("Stereo", onMouseStereo, &hud); // for drawing disparity lines

        moveWindow("Input", stereoConfig.displayOffsetX + 100, stereoConfig.displayOffsetY + 100);
        moveWindow("Stereo", stereoConfig.displayOffsetX + 100, stereoConfig.displayOffsetY + 370);
        moveWindow("Input2", stereoConfig.displayOffsetX + 478, stereoConfig.displayOffsetY + 100);
        moveWindow("Left Block", stereoConfig.displayOffsetX + 900, stereoConfig.displayOffsetY + 100);
        moveWindow("Right Block", stereoConfig.displayOffsetX + 1400, stereoConfig.displayOffsetY + 100);

        moveWindow("Debug 1", stereoConfig.displayOffsetX + 900, stereoConfig.displayOffsetY + 670);
        moveWindow("Debug 2", stereoConfig.displayOffsetX + 1400, stereoConfig.displayOffsetY + 670);

    } // show display

    if (show_display || publish_all_images) {
        // if a channel exists, subscribe to it
        if (stereoConfig.stereo_replay_channel.length() > 0) {
            stereo_replay_sub = lcmt_stereo_subscribe(lcm, stereoConfig.stereo_replay_channel.c_str(), &stereo_replay_handler, &hud);
        }

        if (stereoConfig.pose_channel.length() > 0) {
            mav_pose_t_sub = mav_pose_t_subscribe(lcm, stereoConfig.pose_channel.c_str(), &mav_pose_t_handler, &hud);
        }

        if (stereoConfig.gps_channel.length() > 0) {
            mav_gps_data_t_sub = mav_gps_data_t_subscribe(lcm, stereoConfig.gps_channel.c_str(), &mav_gps_data_t_handler, &hud);
        }

        if (stereoConfig.baro_airspeed_channel.length() > 0) {
            baro_airspeed_sub = lcmt_baro_airspeed_subscribe(lcm, stereoConfig.baro_airspeed_channel.c_str(), &baro_airspeed_handler, &hud);
        }

        if (stereoConfig.servo_out_channel.length() > 0) {
            servo_out_sub = lcmt_deltawing_u_subscribe(lcm, stereoConfig.servo_out_channel.c_str(), &servo_out_handler, &hud);
        }

        if (stereoConfig.battery_status_channel.length() > 0) {
            battery_status_sub = lcmt_battery_status_subscribe(lcm, stereoConfig.battery_status_channel.c_str(), &battery_status_handler, &hud);
        }

        if (stereoConfig.cpu_info_channel1.length() > 0) {
            cpu_info_sub1 = lcmt_cpu_info_subscribe(lcm, stereoConfig.cpu_info_channel1.c_str(), &cpu_info_handler, &recording_manager);
            cpu_info_sub2 = lcmt_cpu_info_subscribe(lcm, stereoConfig.cpu_info_channel2.c_str(), &cpu_info_handler, &recording_manager);
            cpu_info_sub3 = lcmt_cpu_info_subscribe(lcm, stereoConfig.cpu_info_channel3.c_str(), &cpu_info_handler, &recording_manager);
        }

        if (stereoConfig.log_size_channel1.length() > 0) {
            log_size_sub1 = lcmt_log_size_subscribe(lcm, stereoConfig.log_size_channel1.c_str(), &log_size_handler, &hud);
            log_size_sub2 = lcmt_log_size_subscribe(lcm, stereoConfig.log_size_channel2.c_str(), &log_size_handler, &hud);
            log_size_sub3 = lcmt_log_size_subscribe(lcm, stereoConfig.log_size_channel3.c_str(), &log_size_handler, &hud);
        }

    } // end show_display || publish_all_images

    // load calibration
    OpenCvStereoCalibration stereoCalibration;

    if (LoadCalibration(stereoConfig.calibrationDir, &stereoCalibration) != true)
    {
        cerr << "Error: failed to read calibration files. Quitting." << endl;
        return -1;
    }

    int inf_disparity_tester, disparity_tester;
    disparity_tester = GetDisparityForDistance(10, stereoCalibration, &inf_disparity_tester);

    std::cout << "computed disparity is = " << disparity_tester << ", inf disparity = " << inf_disparity_tester << std::endl;

    // subscribe to the stereo control channel
    stereo_control_sub = lcmt_stereo_control_subscribe(lcm, stereoConfig.stereoControlChannel.c_str(), &lcm_stereo_control_handler, NULL);


    Mat imgDisp;
    Mat imgDisp2;

    // initilize default parameters
    //PushbroomStereoState state; // HACK

    state.disparity = stereoConfig.disparity;
    state.zero_dist_disparity = stereoConfig.infiniteDisparity;
    state.sobelLimit = stereoConfig.interestOperatorLimit;
    state.horizontalInvarianceMultiplier = stereoConfig.horizontalInvarianceMultiplier;
    state.blockSize = stereoConfig.blockSize;
    state.random_results = random_results;
    state.check_horizontal_invariance = true;

    if (state.blockSize > 10 || state.blockSize < 1)
    {
        fprintf(stderr, "Warning: block size is very large "
            "or small (%d).  Expect trouble.\n", state.blockSize);
    }

    state.sadThreshold = stereoConfig.sadThreshold;

    state.mapxL = stereoCalibration.mx1fp;
    state.mapxR = stereoCalibration.mx2fp;
    state.Q = stereoCalibration.qMat;
    state.show_display = show_display;

    state.lastValidPixelRow = stereoConfig.lastValidPixelRow;

    Mat matL, matR;
    bool quit = false;

    if (recording_manager.UsingLiveCameras()) {
        matL = GetFrameFormat7(camera);
        matR = GetFrameFormat7(camera2);

        if (recording_manager.InitRecording(matL, matR) != true) {
            // failed to init recording, things are going bad.  bail.
            return -1;
        }

        // before we start, turn the cameras on and set the brightness and exposure
        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);

        // grab a few frames and send them over LCM for the user
        // to verify that everything is working
        if (!show_display && !publish_all_images) {
            printf("Sending init images over LCM... ");
            fflush(stdout);

            for (int i = 0; i < 5; i++) {

                matL = GetFrameFormat7(camera);
                SendImageOverLcm(lcm, "stereo_image_left", matL, 50);

                matR = GetFrameFormat7(camera2);
                SendImageOverLcm(lcm, "stereo_image_right", matR, 50);

                // don't send these too fast, otherwise we'll flood the ethernet link
                // and not actually be helpful

                // wait one second
                printf(".");
                fflush(stdout);

                sleep(1);
            }
            printf(" done.\n");
        }

    } // recording_manager.UsingLiveCameras()

    // spool up worker threads
    PushbroomStereo pushbroom_stereo;

    // start the framerate clock
    struct timeval start, now;
    gettimeofday( &start, NULL );

    while (quit == false) {

        // get the frames from the camera
        if (recording_manager.UsingLiveCameras()) {
            // we would like to match brightness every frame
            // but that would really hurt our framerate
            // match brightness every 10 frames instead
            if (numFrames % MATCH_BRIGHTNESS_EVERY_N_FRAMES == 0)
            {
                MatchBrightnessSettings(camera, camera2);
            }

            // capture images from the cameras
            matL = GetFrameFormat7(camera);
            matR = GetFrameFormat7(camera2);

            // record video
            recording_manager.AddFrames(matL, matR);


        } else {
            // using a video file -- get the next frame
            recording_manager.GetFrames(matL, matR);
        }

        cv::vector<Point3f> pointVector3d;
        cv::vector<uchar> pointColors;
        cv::vector<Point3i> pointVector2d; // for display
        cv::vector<Point3i> pointVector2d_inf; // for display

        // do the main stereo processing
        if (disable_stereo != true) {

            gettimeofday( &now, NULL );
            double before = now.tv_usec + now.tv_sec * 1000 * 1000;

            pushbroom_stereo.ProcessImages(matL, matR, &pointVector3d, &pointColors, &pointVector2d, state);

            gettimeofday( &now, NULL );
            double after = now.tv_usec + now.tv_sec * 1000 * 1000;

            timer_sum += after-before;
            timer_count ++;

        }

        // build an LCM message for the stereo data
        lcmt_stereo msg;


        if (recording_manager.UsingLiveCameras() || stereo_lcm_msg == NULL) {
            msg.timestamp = getTimestampNow();
        } else {
            // if we are replaying videos, preserve the timestamp of the original video
            msg.timestamp = stereo_lcm_msg->timestamp;

        }


        msg.number_of_points = (int)pointVector3d.size();

        float x[msg.number_of_points];
        float y[msg.number_of_points];
        float z[msg.number_of_points];
        uchar grey[msg.number_of_points];

        for (unsigned int i=0;i<pointVector3d.size();i++) {

            x[i] = pointVector3d[i].x / stereoConfig.calibrationUnitConversion;
            y[i] = pointVector3d[i].y / stereoConfig.calibrationUnitConversion;
            z[i] = pointVector3d[i].z / stereoConfig.calibrationUnitConversion;
            grey[i] = pointColors[i];
        }

        msg.x = x;
        msg.y = y;
        msg.z = z;
        msg.grey = grey;
        msg.frame_number = recording_manager.GetFrameNumber();

        if (recording_manager.UsingLiveCameras()) {
            msg.frame_number = msg.frame_number - 1;  // minus one since recording manager has
                                                      // already recorded this frame (above in
                                                      // AddFrames) but we haven't made a message
                                                      // for it yet
        }


        msg.video_number = recording_manager.GetRecVideoNumber();

        // publish the LCM message
        if (last_frame_number != msg.frame_number) {
            lcmt_stereo_publish(lcm, "stereo", &msg);
            last_frame_number = msg.frame_number;
        }

        if (publish_all_images) {
            if (recording_manager.GetFrameNumber() != last_playback_frame_number) {
                SendImageOverLcm(lcm, "stereo_image_left", matL, 80);
                SendImageOverLcm(lcm, "stereo_image_right", matR, 80);

                last_playback_frame_number = recording_manager.GetFrameNumber();
            }

            //process LCM until there are no more messages
            // this allows us to drop frames if we are behind
            while (NonBlockingLcm(lcm)) {}
        }

        Mat matDisp, remapL, remapR;

        if (show_display) {
            // we remap again here because we're just in display
            Mat remapLtemp(matL.rows, matL.cols, matL.depth());
            Mat remapRtemp(matR.rows, matR.cols, matR.depth());

            remapL = remapLtemp;
            remapR = remapRtemp;

            remap(matL, remapL, stereoCalibration.mx1fp, Mat(), INTER_NEAREST);
            remap(matR, remapR, stereoCalibration.mx2fp, Mat(), INTER_NEAREST);

            remapL.copyTo(matDisp);

            //process LCM until there are no more messages
            // this allows us to drop frames if we are behind
            while (NonBlockingLcm(lcm)) {}
        } // end show_display


        if (show_display) {

            for (unsigned int i=0;i<pointVector2d.size();i++) {
                int x2 = pointVector2d[i].x;
                int y2 = pointVector2d[i].y;
                //int sad = pointVector2d[i].z;
                rectangle(matDisp, Point(x2,y2), Point(x2+state.blockSize, y2+state.blockSize), 0,  CV_FILLED);
                rectangle(matDisp, Point(x2+1,y2+1), Point(x2+state.blockSize-1, y2-1+state.blockSize), 255);

            }

            // draw pixel blocks
            if (lineLeftImgPosition >= 0 && lineLeftImgPositionY > 1) {
                DisplayPixelBlocks(remapL, remapR, lineLeftImgPosition - state.blockSize/2, lineLeftImgPositionY - state.blockSize/2, state, &pushbroom_stereo);
            }

            // draw a line for the user to show disparity
            DrawLines(remapL, remapR, matDisp, lineLeftImgPosition, lineLeftImgPositionY, state.disparity, state.zero_dist_disparity);


            if (visualize_stereo_hits == true && stereo_lcm_msg != NULL) {

                // transform the points from 3D space back onto the image's 2D space
                vector<Point3f> lcm_points;
                Get3DPointsFromStereoMsg(stereo_lcm_msg, &lcm_points);

                // draw the points on the unrectified image (to see these
                // you must pass the -u flag)
                Draw3DPointsOnImage(matL, &lcm_points, stereoCalibration.M1, stereoCalibration.D1, stereoCalibration.R1, 128);

            }

            if (show_unrectified == false) {

                imshow("Input", remapL);
                imshow("Input2", remapR);
            } else {
                imshow("Input", matL);
                imshow("Input2", matR);
            }


            if (display_hud) {
                Mat with_hud;

                recording_manager.SetHudNumbers(&hud);

                hud.DrawHud(matDisp, with_hud);

                if (record_hud) {
                    // put this frame into the HUD recording
                    recording_manager.RecFrameHud(with_hud);

                }

                imshow("Stereo", with_hud);
            } else {
                imshow("Stereo", matDisp);
            }


            char key = waitKey(show_display_wait);

            if (key != 255 && key != -1)
            {
                cout << endl << key << endl;
            }

            switch (key)
            {
                case 'T':
                    state.disparity --;
                    break;
                case 'R':
                    state.disparity ++;
                    break;

                case 'w':
                    state.sobelLimit += 10;
                    break;

                case 's':
                    state.sobelLimit -= 10;
                    break;

                case 'd':
                    state.horizontalInvarianceMultiplier -= 0.1;
                    break;

                case 'D':
                    state.horizontalInvarianceMultiplier += 0.1;
                    break;

                case 'g':
                    state.blockSize ++;
                    break;

                case 'b':
                    state.blockSize --;
                    if (state.blockSize < 1) {
                        state.blockSize = 1;
                    }
                    break;

                case 'Y':
                    state.sadThreshold += 50;
                    break;

                case 'y':
                    state.sadThreshold ++;
                    break;

                case 'h':
                    state.sadThreshold --;
                    break;

                case 'H':
                    state.sadThreshold -= 50;
                    break;

                case 'm':
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '1':
                    force_brightness --;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '2':
                    force_brightness ++;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '3':
                    force_exposure --;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '4':
                    force_exposure ++;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '5':
                    // to show SAD boxes
                    state.sobelLimit = 0;
                    state.sadThreshold = 255;
                    break;

                case 'I':
                    state.check_horizontal_invariance = !state.check_horizontal_invariance;
                    break;

                case '.':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() + 1);
                    break;

                case ',':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() - 1);
                    break;

                case '>':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() + 50);
                    break;

                case '<':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() - 50);
                    break;

                //case 'k':
                //    state.zero_dist_disparity ++;
                 //   break;

                case 'l':
                    state.zero_dist_disparity --;
                    break;

                case 'o':
                    inf_sad_add --;
                    break;

                case 'p':
                    inf_sad_add ++;
                    break;

                case '[':
                    y_offset --;
                    if (y_offset < 0) {
                        y_offset = 0;
                    }
                    break;

                case ']':
                    y_offset ++;
                    break;

                case 'v':
                    display_hud = !display_hud;
                    break;

                case 'c':
                    hud.SetClutterLevel(hud.GetClutterLevel() + 1);
                    break;

                case 'C':
                    hud.SetClutterLevel(hud.GetClutterLevel() - 1);
                    break;

                case '}':
                    hud.SetPitchRangeOfLens(hud.GetPitchRangeOfLens() + 1);
                    break;
                case '{':
                    hud.SetPitchRangeOfLens(hud.GetPitchRangeOfLens() - 1);
                    break;

                case 'S':
                    // take a screen cap of the left and right images
                    // useful for putting into a stereo tuner
                    printf("\nWriting left.ppm...");
                    imwrite("left.ppm", remapL);

                    printf("\nWriting right.ppm...");
                    imwrite("right.ppm", remapR);

                    printf("\ndone.");
                    break;

                case 'V':
                    // record the HUD
                    record_hud = true;
                    recording_manager.RestartRecHud();
                    break;

                    /*
                case 'j':
                    state.debugJ --;
                    break;

                case 'J':
                    state.debugJ ++;
                    break;

                case 'i':
                    state.debugI --;
                    break;

                case 'I':
                    state.debugI ++;
                    break;

                case 'k':
                    state.debugDisparity --;
                    break;

                case 'K':
                    state.debugDisparity ++;
                    break;

                    */

                case 'q':
                    quit = true;
                    break;
            }

            if (key != 255 && key != -1)
            {
                cout << "sadThreshold = " << state.sadThreshold << endl;
                cout << "sobelLimit = " << state.sobelLimit << endl;
                cout << "horizontalInvarianceMultiplier = " << state.horizontalInvarianceMultiplier << endl;
                cout << "brightness: " << force_brightness << endl;
                cout << "exposure: " << force_exposure << endl;
                cout << "disparity = " << state.disparity << endl;
                cout << "inf_disparity = " << state.zero_dist_disparity << endl;
                cout << "inf_sad_add = " << inf_sad_add << endl;
                cout << "blockSize = " << state.blockSize << endl;
                cout << "frame_number = " << recording_manager.GetFrameNumber() << endl;
                cout << "y offset = " << y_offset << endl;
                cout << "PitchRangeOfLens = " << hud.GetPitchRangeOfLens() << endl;
            }
        } // end show_display

        numFrames ++;

        // check for new LCM messages
        NonBlockingLcm(lcm);

        if (quiet_mode == false || numFrames % 100 == 0) {
            // compute framerate
            gettimeofday( &now, NULL );

            elapsed = (now.tv_usec / 1000 + now.tv_sec * 1000) -
            (start.tv_usec / 1000 + start.tv_sec * 1000);

            printf("\r%d frames (%lu ms) - %4.1f fps | %4.1f ms/frame, stereo: %f", numFrames, elapsed, (float)numFrames/elapsed * 1000, elapsed/(float)numFrames, timer_sum/(double)timer_count);
            fflush(stdout);
        }


    } // end main while loop

    printf("\n\n");

    destroyWindow("Input");
    destroyWindow("Input2");
    destroyWindow("Stereo");

    // close camera
    if (recording_manager.UsingLiveCameras()) {
        StopCapture(d, camera);
        StopCapture(d2, camera2);
    }

    return 0;
}
コード例 #11
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
void mav_gps_data_t_handler(const lcm_recv_buf_t *rbuf, const char* channel, const mav_gps_data_t *msg, void *user) {
    Hud *hud = (Hud*)user;

    hud->SetGpsSpeed(msg->speed);
    hud->SetGpsHeading(msg->heading);
}
コード例 #12
0
int IndieLib()
{
    // ----- IndieLib intialization -----

    CIndieLib *mI = CIndieLib::instance();
    if (!mI->init()) return 0;

    // ----- Get Window Dimensions

    int winWidth = mI->_window->getWidth();
    int winHeight = mI->_window->getHeight();

    srand(static_cast<unsigned int>(time(0)));

    // ----- Surface loading -----

    IND_Surface *mSurfaceBack = IND_Surface::newSurface();
    if (!mI->_surfaceManager->add(mSurfaceBack, "../SpaceGame/resources/Backgrounds/18.jpg", IND_OPAQUE, IND_32)) return 0;

    /*IND_Animation* mTestA = IND_Animation::newAnimation();
    if (!mI->_animationManager->addToSurface(mTestA, "resources/animations/dust.xml", IND_ALPHA, IND_32, 255, 0, 255)) return 0;
    mTestA->getActualFramePos(0);*/

    // Loading 2D Entities

    // Background
    IND_Entity2d* mBack = IND_Entity2d::newEntity2d();
    mI->_entity2dManager->add(mBack);
    mBack->setSurface(mSurfaceBack);
    mBack->setScale((float)winWidth / mSurfaceBack->getWidth(), (float)winHeight / mSurfaceBack->getHeight());

    Controls* controls = new Controls();
    controls->loadSettings();

    ErrorHandler* error = new ErrorHandler();
    error->initialize(mI);

    Hud* mHud = new Hud();
    mHud->createHud(mI);

    Menu* mMenu = new Menu();
    mMenu->createMenu(mI);

    Save* quickSave = new Save();

    if (!SoundEngine::initialize())
    {
        error->writeError(200, 100, "Error", "SoundEngine");
    }

    vector<Planet*> mPlanets;
    Ship* mShip = NULL;

    bool loadSave = false;
    float mDelta = 0.0f;

    IND_Timer* mTimer = new IND_Timer;
    mTimer->start();

    while (!mI->_input->onKeyPress(IND_ESCAPE) && !mI->_input->quit() && !mMenu->isExit())
    {
        // get delta time
        mDelta = mI->_render->getFrameTime() / 1000.0f;

        if (mI->_input->isKeyPressed(controls->getMenu()))
        {
            mMenu->show();
            SoundEngine::getSoundEngine()->setAllSoundsPaused(true);
        }
        if (!mMenu->isHidden())
        {
            mMenu->updateMenu(mHud, quickSave, mPlanets, mShip);
            loadSave = mHud->getLoadingText()->isShow();
        }
        else
        {
            if (loadSave)
            {
                mDelta = 0.0;
                loadSave = false;
                SoundEngine::getSoundEngine()->setAllSoundsPaused(true);
                mHud->getLoadingText()->setShow(false);
                quickSave->loadSave(mI, mShip, mPlanets);
                mHud->showHud();
            }

            if (mShip != NULL)
            {
                if (mI->_input->onKeyPress(controls->getQuickSave()))
                {
                    quickSave->makeSave(mI, mShip, mPlanets);
                }

                mHud->updateHud(mShip);

                if (mI->_input->onKeyPress(controls->getQuickLoad()))
                {
                    deleteObjects(mHud, mShip, mPlanets);
                    loadSave = true;
                }
                if (mShip->isDestroyed())
                {
                    SoundEngine::getSoundEngine()->setAllSoundsPaused(true);
                    mHud->updateGameOverText(mShip->getScore());
                    deleteObjects(mHud, mShip, mPlanets);
                    mHud->getLoadingText()->setShow(false);
                    mHud->getGameOverText()->setShow(true);
                    mMenu->show();
                }
                if(mShip!=NULL)
                {
                    //----- Collisions -----
                    checkShipPlanetsCollisions(mI, mPlanets, mShip);
                    checkBulletsPlanetsCollisions(mI, mPlanets, mShip);
                    checkBulletsShipCollisions(mI, mPlanets, mShip);

                    //----- Movement update -----
                    mShip->updateShip(controls, mDelta);
                    if ((mTimer->getTicks() / 1000.0f) >= 3.0f)
                    {
                        mTimer->start();
                        mPlanets.at(rand() % mPlanets.size())->addSatellite();
                    }
                    for (vector<Planet*>::iterator it = mPlanets.begin(); it != mPlanets.end(); ++it)
                    {
                        (*it)->updatePlanet(mDelta, (mShip->getPosX() + 0.25f * mShip->getHeight() * cos(mShip->getAngleZRadian())), (mShip->getPosY() - 0.25f * mShip->getHeight() * sin(mShip->getAngleZRadian())));
                    }
                }
            }
        }

        //mI->_render->showFpsInWindowTitle();
        mI->_input->update();
        mI->_render->beginScene();
        mI->_entity2dManager->renderEntities2d();
        mI->_render->endScene();
    }

    // ----- Free -----
    delete controls;
    delete error;
    delete mHud;
    delete mMenu;
    delete quickSave;
    mI->_surfaceManager->remove(mSurfaceBack);
    mI->_entity2dManager->remove(mBack);
    deleteObjects(mHud, mShip, mPlanets);
    mI->end();
    return 0;
}
コード例 #13
0
void Game::initializePopupHelpScreen() {
	
	if (popupHelpScreen)
		delete popupHelpScreen;
		
	this->popupHelpScreen = new HudsManager(this, this->configuration->getScreenHeight() / 2);
	
	Hud *titleHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *mouseHud;
	Hud *movementHud;
	
	if (this->configuration->isMouseControl())
		mouseHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	else
		movementHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	
	Hud *resetJoystickHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *zeroRotorSpeedHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *increase_decreaseRotorSpeedHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *neutralRotorModeHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *rotationHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *fireHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *increment_decrementInclinationAngleHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *increment_decrementMissileInitialSpeedHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *frictionEnable_DisableHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *startLoggingHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *stopLoggingHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *updateHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *showHelpHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	Hud *hideHelpHud = popupHelpScreen->createHud(HudAlignment::LEFT);
	
	titleHud->setText("Settings");
	
	if (this->configuration->isMouseControl())
		mouseHud->setText("Mouse contorl the joystick");
	else {
		movementHud->setText(
							 std::string(1, this->configuration->getKeySettings().movingForward) + ", " +
							 std::string(1, this->configuration->getKeySettings().movingRight) + ", " +
							 std::string(1, this->configuration->getKeySettings().movingLeft) + ", " +
							 std::string(1, this->configuration->getKeySettings().movingBackward) +
							 ": moving forward, left, right, backward"
							 );
	}
		
	
	resetJoystickHud->setText(
			std::string(1, this->configuration->getKeySettings().resetJoystick) + ": reset joystick");
	
	zeroRotorSpeedHud->setText(
			std::string(1, this->configuration->getKeySettings().zeroRotorSpeed) + ": zero rotor speed");
	
	increase_decreaseRotorSpeedHud->setText(
			std::string(1, this->configuration->getKeySettings().increaseRotorSpeed) + "/" +
			std::string(1, this->configuration->getKeySettings().decreaseRotorSpeed) + ": +/- rotor speed");
	
	neutralRotorModeHud->setText(
			std::string(1, this->configuration->getKeySettings().neutralRotorMode) + ": neutral rotor mode");
	
	rotationHud->setText(
			std::string(1, this->configuration->getKeySettings().rotateLeft) + "/" +
			std::string(1, this->configuration->getKeySettings().rotateRight) + ": rotate left/right");
	
	fireHud->setText(
			std::string(1, this->configuration->getKeySettings().fire) + ": fire");
	
	increment_decrementInclinationAngleHud->setText(
			std::string(1, this->configuration->getKeySettings().incrementInclinationAngle) + "/" +
			std::string(1, this->configuration->getKeySettings().decrementInclinationAngle) +
													": +/- inclination angle");
	
	increment_decrementMissileInitialSpeedHud->setText(
			std::string(1, this->configuration->getKeySettings().incrementMissileInitialSpeed) + "/" +
			std::string(1, this->configuration->getKeySettings().decrementMissileInitialSpeed) +
													   + ": +/- increment missile initial speed");
	
	frictionEnable_DisableHud->setText(
			std::string(1, this->configuration->getKeySettings().frictionEnable) + "/" +
			std::string(1, this->configuration->getKeySettings().frictionDisable) +
									   + ": enable/disable friction");
	
	startLoggingHud->setText(
					   std::string(1, this->configuration->getKeySettings().startLogging) + ": start logging");
	
	stopLoggingHud->setText(
					   std::string(1, this->configuration->getKeySettings().stopLogging) + ": stop logging");
	
	updateHud->setText(
			std::string(1, this->configuration->getKeySettings().updateKeySettings) + ": updste key settings");
	
	showHelpHud->setText(
			std::string(1, this->configuration->getKeySettings().showPopupHelpScreen) + ": show help screen");
	
	hideHelpHud->setText(
			std::string(1, this->configuration->getKeySettings().hidePopupHelpScreen) + ": hide help screen");
}
コード例 #14
0
	void ScreenOverlay::Register(Hud& _hud)
	{
		_hud.RegisterElement(*this);
	}
コード例 #15
0
ファイル: level.cpp プロジェクト: cthielen/epsilonfighter
Level::Level( int which ) {
	Starfield starfield( 350 );
	Hud hud;
	Timer *timer = Timer::Instance();
	Video *video = Video::Instance();
	SpriteList *spriteList = SpriteList::Instance();
	Ship *player = new Ship(); // the player sprite
	bool quit = false;
	SDL_Event event;

	camera = Camera::Instance();

	camera->Follow( player );

	player->UseAI( false );
	player->IsPlayer( true );

	player->SetThrust( 5. );
	
	// add player
	spriteList->Add( player );

	Ship *test = new Ship( 15, 15 );
	
	spriteList->Add( test );

	if( SDL_Init( SDL_INIT_JOYSTICK ) != 0 )
		cout << "massive joystick error" << endl; // move to an input class

	timer->Reset();
	
	hud.Message( HUD_MSG_COMMAND, "Good morning, pilot." );
	
	while( !quit ) {
		// erase
		video->Blank();

		// update
		// get user input
		while( SDL_PollEvent( &event ) ) {
			switch( event.type ) {
				case SDL_QUIT:
					quit = true;
					break;
				case SDL_JOYAXISMOTION:
					cout << "joystick motion!" << endl;
					if(event.jaxis.which == 0)
						player->Turn( (float)-20 * 0.15f );
					break;
				case SDL_KEYDOWN:
					switch( event.key.keysym.sym ) {
						case SDLK_ESCAPE:
							quit = true;
							break;
						case SDLK_w:
							player->ThrottleUp();
							break;
						case SDLK_s:
							player->ThrottleDown();
							break;
						default:
							break;
					}
					break;
				case SDL_MOUSEMOTION:
					if(( event.motion.xrel ) && ( event.motion.xrel != 160 )) {
						if( abs(event.motion.xrel) > 20 )
							if(event.motion.xrel < 0)
								player->Turn( (float)-20 * 0.15f );
							else
								player->Turn( (float)20 * 0.15f );
						else
							player->Turn( (float)event.motion.xrel * 0.15f );
					}
					break;
				case SDL_MOUSEBUTTONDOWN:
					if( event.button.button == 1) player->Fire();
					if( event.button.button == 4) player->ThrottleUp();
					if( event.button.button == 5) player->ThrottleDown();
					break;
				default:
					break;
			}
		}

		for( int n = timer->GetLoops(); n ; --n ) {
			// update various systems
			camera->Update();
			starfield.Update();
			spriteList->Update();
			hud.Update();
		}

		// draw
		starfield.Draw();
		spriteList->Draw();
		hud.Draw();

		video->Update();

		timer->Delay();
	}
}
コード例 #16
0
int main(int argc, char ** argv)
{
  SDL_Surface * psdlsScreen     = NULL;
  SDL_Surface * psdlsWMIcon     = NULL;
  int           nVideoMode      = MODE_WINDOWED;
  bool          bDone           = false;
  char          szFilename[512] = {"default.lvl\0"};
  
  Level         level("fuckyou");
  Cursor        cursor(0, 0);
  Hud           hud;


  // deal with command line shit
  if(argc > 2)
  {
    ShowUsage();
    exit(1);
  }
  if(argc == 2)
  {
    if(!strcmp("--help", argv[1]) || !strcmp("-h", argv[1]) || !strcmp("-help", argv[1]))
    {
      ShowUsage();
      exit(0);
    }
    sprintf(szFilename, "%s", argv[1]);
    if(!level.ReadFromFile(szFilename))
      fprintf(stderr, "Couldn't read level from: %s, assuming file doesn't exist yet\n", szFilename);
    else
      fprintf(stderr, "Level read successfully from: %s\n", szFilename);
  }
  else
    fprintf(stderr, "No file name specified, using: %s\n", szFilename);
  
  InitSDL();
//  SetVideoMode(psdlsScreen, nVideoMode);

  fprintf(stderr, "Setting window icon... ");
  psdlsWMIcon = SDL_LoadBMP(LoadResource("bomn32.bmp", RESOURCE_GRAPHIC));
  if(psdlsWMIcon)
  {
    Uint32 colorkey;
    colorkey = SDL_MapRGB(psdlsWMIcon->format, 0, 0, 0);
    SDL_SetColorKey(psdlsWMIcon, SDL_SRCCOLORKEY, colorkey);
    SDL_WM_SetIcon(psdlsWMIcon, NULL);
    fprintf(stderr, "Success!\n");
  }
  else
    fprintf(stderr, "AW JUNK! Something fishy happened...\n");
  
  // can't f*****g use SetVideoMode here, for SOME REASON
  fprintf(stderr, "Setting video mode to 800x600 %s mode... ", (nVideoMode == MODE_WINDOWED ? "windowed" : "fullscreen"));
  SDL_WM_SetCaption("Bomns for Linux Level Editor", "Bomns for Linux Level Editor");
  if(nVideoMode == MODE_WINDOWED)
    psdlsScreen = SDL_SetVideoMode(800, 600, 0, SDL_HWSURFACE | SDL_DOUBLEBUF); 
  else if(nVideoMode == MODE_FULLSCREEN)
    psdlsScreen = SDL_SetVideoMode(800, 600, 0, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
  else
    QuitWithError("Que?\n");
  if(!psdlsScreen)
    QuitWithError("Error setting GODDAM VIDEO MODE... for some f*****g reason!\n");
  else
    fprintf(stderr, "Success!\n");
  SDL_ShowCursor(false);

  // do this here so the surfaces can read the display format
  cursor.CreateSurfaces();
  hud.CreateSurfaces();
  level.CreateSurfaces();
  
  // main input loop
  while(!bDone)
  {
    SDL_Event sdleEvent;
    Uint8 *   anKeyState  = NULL;
    Uint8     nMouseState = 0;

    while(SDL_PollEvent(&sdleEvent))
    {
      if(sdleEvent.type == SDL_QUIT)
        bDone = true;

      // TODO: use relative mouse motion so it doesn't jump around
      if(sdleEvent.type == SDL_MOUSEMOTION)
        cursor.SetPosition(sdleEvent.motion.x / 10, sdleEvent.motion.y / 10);

      // process mouse input
      nMouseState = SDL_GetMouseState(NULL, NULL);
      if(nMouseState & SDL_BUTTON_LMASK)
        cursor.StampCurrentObject(&level);
      if(nMouseState & SDL_BUTTON_RMASK)
        cursor.DeleteUnderCursor(&level);

      if(sdleEvent.type == SDL_MOUSEBUTTONDOWN)
      {
        switch(sdleEvent.button.button)
        {
          case SDL_BUTTON_WHEELUP:
            cursor.ForwardObject();
            break;
          case SDL_BUTTON_WHEELDOWN:
            cursor.BackwardObject();
            break;
        }
      }
      
      // process keyboard state data
      anKeyState = SDL_GetKeyState(NULL);
      
      if(anKeyState[SDLK_UP])
        cursor.MoveUp();
      if(anKeyState[SDLK_DOWN])
        cursor.MoveDown();
      if(anKeyState[SDLK_LEFT])
        cursor.MoveLeft();
      if(anKeyState[SDLK_RIGHT])
        cursor.MoveRight();

      if(anKeyState[SDLK_SPACE] || anKeyState[SDLK_RETURN] || anKeyState[SDLK_s])
        cursor.StampCurrentObject(&level);
      if(anKeyState[SDLK_DELETE] || anKeyState[SDLK_d])
        cursor.DeleteUnderCursor(&level);

      if(anKeyState[SDLK_PAGEUP])
        cursor.ForwardObject();
      if(anKeyState[SDLK_PAGEDOWN])
        cursor.BackwardObject();

      // 1 - 9 keys select object
      if(anKeyState[SDLK_1])
        cursor.SelectObject(0);
      if(anKeyState[SDLK_2])
        cursor.SelectObject(1);
      if(anKeyState[SDLK_3])
        cursor.SelectObject(2);
      if(anKeyState[SDLK_4])
        cursor.SelectObject(3);
      if(anKeyState[SDLK_5])
        cursor.SelectObject(4);
      if(anKeyState[SDLK_6])
        cursor.SelectObject(5);
      if(anKeyState[SDLK_7])
        cursor.SelectObject(6);
      if(anKeyState[SDLK_8])
        cursor.SelectObject(7);
      if(anKeyState[SDLK_9])
        cursor.SelectObject(8);

      // buttons that should only be pressed, never held down (keyboard event data)
      if(sdleEvent.key.state == SDL_PRESSED)
      {
        switch(sdleEvent.key.keysym.sym)
        {
          case SDLK_ESCAPE:
            bDone = true;
            break;

          case SDLK_f:
            nVideoMode = !nVideoMode;
            SetVideoMode(psdlsScreen, nVideoMode);
            break;

          case SDLK_l:
            char szTmp[520];
            sprintf(szTmp, "bomns %s", szFilename);
            if(!level.WriteToFile(szFilename))
              fprintf(stderr, "Error writing level to: %s\n", szFilename);
            else
              fprintf(stderr, "Level written successfully to: %s\n", szFilename);

            // can't do this while editor is in fullscreen without a pretty big crash
            if(nVideoMode == MODE_FULLSCREEN) // not changing the nVideoMode variable so down there...
              SetVideoMode(psdlsScreen, MODE_WINDOWED);
            
            fprintf(stderr, "Launching level in bomns...\n");
            system(szTmp);
            fprintf(stderr, "Back to editing!\n");
            
            if(nVideoMode == MODE_FULLSCREEN)  // ...we can just read it again and change accordingly
              SetVideoMode(psdlsScreen, nVideoMode);
            break;

          case SDLK_F2:
            if(!level.WriteToFile(szFilename))
              fprintf(stderr, "Error writing level to: %s\n", szFilename);
            else
              fprintf(stderr, "Level successfully written to: %s\n", szFilename);
            break;

          case SDLK_F12: // clear the level... F12 is hard to hit by mistake, right?
            level.DeleteLevel();
            break;

          default:
            break;
        }
      }
    } // SDL_PollEvent

    ClearSurface(psdlsScreen);

    if(!level.DrawLevel(psdlsScreen))
      QuitWithError("Error drawing level to screen!\n");

    if(!hud.DrawHUD(psdlsScreen, 0, 580))
      QuitWithError("Error drawing HUD to screen!\n");

    if(!cursor.DrawCursor(psdlsScreen))
      QuitWithError("Error drawing cursor to screen!\n");

    SDL_Flip(psdlsScreen);

  } // while(!bDone)
  
  ShutDown();

  return 0;
}
コード例 #17
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
void baro_airspeed_handler(const lcm_recv_buf_t *rbuf, const char* channel, const lcmt_baro_airspeed *msg, void *user) {
    Hud *hud = (Hud*)user;

    hud->SetAirspeed(msg->airspeed);
}
コード例 #18
0
ファイル: main.cpp プロジェクト: caspark/sdl-pong
int main(int argc, char **argv) {
	srand(static_cast<unsigned int>(time(nullptr))); //seed random number generator with the current time

	if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
		logSDLError("SDL_Init");
	}

	if ((IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG) {
		logSDLError("IMG_Init");
	}

	if (TTF_Init() == -1) {
		logSDLError("TTF_Init");
	}

	SDL_Window *window = SDL_CreateWindow("Pong", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
			SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (window == nullptr) {
		logSDLError("CreateWindow");
	}
	//SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
	if (renderer == nullptr) {
		logSDLError("CreateRenderer");
	}

	FpsTracker fpsTracker(100);

	WorldState currentWorldState;
	World *world = new World(renderer, SCREEN_WIDTH, SCREEN_HEIGHT, currentWorldState);
	world->startRound(currentWorldState);
	WorldState previousWorldState=currentWorldState;

	Hud *hud = new Hud(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
	drawUI(hud, currentWorldState);

	float dt = PHYSICS_TIMESTEP;

	Uint64 currentTime = SDL_GetPerformanceCounter();
	float accumulator = 0;

	bool quit = false;
	SDL_Event event;
	while (!quit) {
		const Uint64 newTime = SDL_GetPerformanceCounter();
		float deltaTime = static_cast<float>(newTime - currentTime) / SDL_GetPerformanceFrequency(); //aka time for this frame
		currentTime = newTime;

		if (deltaTime > 0.25f) {
			std::cout << "limiting delta time to 0.25f" << std::endl;
			deltaTime = 0.25f; // anti "spiral of death" / breakpoints
		}

		accumulator += deltaTime;

		int simCount = 0;
		while (accumulator >= dt) {
			accumulator -= dt;
			previousWorldState = currentWorldState;
			world->update(currentWorldState, dt); //aka integrate
			if (currentWorldState.humanScore != previousWorldState.humanScore
				|| currentWorldState.opponentScore != previousWorldState.opponentScore) {
					drawUI(hud, currentWorldState);
			}
			++simCount;
		}
		if (simCount > 1) {
			std::cout << "Simulated multiple steps:" << simCount << std::endl;
		}

		WorldState lerped = WorldState::lerpBetween(previousWorldState, currentWorldState, accumulator/dt);

		drawFps(hud, static_cast<int>(1 / fpsTracker.calculateAverageFrameTime(deltaTime)));

		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
		SDL_RenderClear(renderer);
		world->render(lerped);
		hud->render();
		SDL_RenderPresent(renderer);

		//TODO figure out where user input handling should go. @see http://gamedev.stackexchange.com/questions/8623/a-good-way-to-build-a-game-loop-in-opengl
		while (SDL_PollEvent(&event)) {
			switch(event.type) {
			case SDL_QUIT:
				quit = true;
				break;
			case SDL_KEYDOWN:
				switch(event.key.keysym.scancode) {
				case SDL_SCANCODE_ESCAPE:
					quit = true;
					break;
				}
				break;
			}
		}
	}

	std::cout << "Quitting" << std::endl;

	//cleanup
	delete hud;
	delete world;
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);

	TTF_Quit();
	IMG_Quit();
	SDL_Quit();

	return 0;
}
コード例 #19
0
ファイル: pushbroom-stereo-main.cpp プロジェクト: 1ee7/flight
void battery_status_handler(const lcm_recv_buf_t *rbuf, const char* channel, const lcmt_battery_status *msg, void *user) {
    Hud *hud = (Hud*)user;

    hud->SetBatteryVoltage(msg->voltage);
}
コード例 #20
0
ファイル: font.cpp プロジェクト: Jojendersie/Monolith
// ***************************************************** //
void TextRender::Register(Hud& _hud)
{
    _hud.AddTextRender(this);
}
コード例 #21
0
ファイル: main.cpp プロジェクト: TaintedGear/Fishy-Rescue
int main(int argc, char* args[])
{

	enum {MENU, RUNNING, GAMEOVER, END};
	int state = MENU;

	int score = 0;
	int deaths = 0;

	//Holds all game objects vectors
	vector<Net *> nets;
	vector<Coral *> corals;
	vector<School *> schools;
	vector<SceneryFish *> sceneryFish;
	vector<GobblerFish *> gobblerFish;

	//back buffer || bit messy can clean up
	System system("Fishy Game", false, 640, 480, 32, 60);
	if (!system.Setup())
	{
		MessageBox(NULL, "SDL DID NOT INITIALISE PROPERLY", NULL, MB_OK);
		return -1;
	}
	SDL_Surface* buffer = system.GetBuffer();

	Timer timer;
	Timer delta;
	Camera camera(640, 480);

	Level level;
	Menu menu;
	Hud hud;
	
	School* school;
	Net* net = NULL;
	Coral* coral = NULL;

	Mix_Music *music = NULL;
	Fish fish("Sprites/Player_Spritesheet.bmp", 64, 64, 0, 0, 200, 200);
	level.LoadLevel(fish, corals, nets, sceneryFish, gobblerFish);
	music = Mix_LoadMUS( "Sounds/DST-Aethereal.wav" );

	delta.Start();

	while(!system.Done())
	{
		srand(time(NULL));

		if(Mix_PlayingMusic () == 0)
		{
			Mix_PlayMusic(music, -1);
		}

		switch(state)
		{
		case MENU:

			state = (menu.Update( delta, system.GetEvent()));
			menu.Draw(buffer, camera);

			break;
		case RUNNING:


		hud.Update(score, deaths );

		//update
		fish.Update( delta.GetTicks() );

		for( int c = 0; c < corals.size(); c++)
		{
			corals[c]->Update(delta.GetTicks());
		}

		for( int i = 0; i < schools.size(); i++)
		{
			schools[i]->Update( delta.GetTicks(), fish, corals);
			for(int j = 0; j < 3; j++)
			{
				if(schools[i]->GetFish(j)->GetEaten()
					&& (!schools[i]->GetFish(j)->GetScored())) 
				{ 
						deaths += 1;
						schools[i]->GetFish(j)->SetScored(true);
				}
				if(schools[i]->GetFish(j)->GetSaved()
					&& (!schools[i]->GetFish(j)->GetScored()))
				{ 
					score += 10; 
					schools[i]->GetFish(j)->SetScored(true);
				}
			}
		}

		for( int g = 0; g < gobblerFish.size(); g++)
		{
			gobblerFish[g]->Update(delta.GetTicks(), schools);
		}

		for( int i = 0; i < nets.size(); i++)
		{
			nets[i]->Update(delta.GetTicks(), fish);

			if(nets[i]->GetReleased())
			{
				school = NULL;
				school = new School("Sprites/Player_SpriteSheet.bmp", 
					nets[i]->GetOffsetX(), nets[i]->GetOffsetY());
				schools.push_back(school);
			}

		}

		for( int f = 0; f < sceneryFish.size(); f++)
		{
			sceneryFish[f]->Update(delta.GetTicks(), fish);
		}

		camera.Update(fish.GetPosX(), fish.GetPosY(), fish.GetWidth(), fish.GetHeight());

		//Draw background first
		level.DrawBackdrop( buffer, camera );

		for( int f = 0; f < sceneryFish.size(); f++)
		{
			sceneryFish[f]->Draw( buffer, camera);
		}

		for(int s = 0; s < schools.size(); s++)
		{
			schools[s]->Draw( buffer, camera );
		}

		level.DrawBackground( buffer, camera );

		for(int i = 0; i < nets.size(); i++)
		{
			nets[i]->Draw( buffer, camera );
		}

		fish.Draw( buffer, camera );

		for(int g = 0; g < gobblerFish.size(); g++)
		{
			gobblerFish[g]->Draw( buffer, camera );
		}

		for(int c = 0; c < corals.size(); c++)
		{
			corals[c]->Draw( buffer, camera );
		}

		level.DrawForeground( buffer, camera );

		hud.Draw( buffer );

		if(hud.GetTime() <= 0)
		{
			state = GAMEOVER;
		}

			break;
		case GAMEOVER:

			if(!timer.GetStarted())
			{
				timer.Start();
			}

			menu.DrawGameOver( buffer, hud.GetScore(), hud.GetDeaths());

			if(timer.GetTicks() >= 5000)
			{
				state = MENU;

				for(int i = 0; i < schools.size(); i++)
				{
					delete schools[i];
				}


				schools.clear();
				score = 0;
				deaths = 0;
				hud.Reset();
				level.ResetLevel(fish, corals, nets, sceneryFish, gobblerFish);
				timer.Stop();
			}

			break;
		case END:
			Mix_FreeMusic(music);
			delete net;
			delete coral;
			system.CleanUp(buffer);
			return 0;
			break;
		}

		delta.Start();

		SDL_Flip( buffer );
		SDL_FillRect(buffer, NULL, SDL_MapRGB(buffer->format, 0, 0, 0));
	}

	if(net != NULL)
	{
		delete net;
	}
	if(coral != NULL)
	{
		delete coral;
	}
	system.CleanUp(buffer);

	return 0;
}