<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#pragma once

#include <stdint.h>

namespace px4
{

class WorkQueue; // forward declaration

struct wq_config_t {
	const char *name;
	uint16_t stacksize;
	int8_t relative_priority; // relative to max
};

namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1920, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t ctrl_alloc{"wq:ctrl_alloc", 9500, 0}; // PX4 control allocation, same priority as rate_ctrl

static constexpr wq_config_t SPI0{"wq:SPI0", 2336, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 2336, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 2336, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 2336, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 2336, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 2336, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 2336, -7};

static constexpr wq_config_t I2C0{"wq:I2C0", 2336, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 2336, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 2336, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 2336, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 2336, -12};

// PX4 att/pos controllers, highest priority after sensors.
static constexpr wq_config_t nav_and_controllers{"wq:nav_and_controllers", 2164, -13};

static constexpr wq_config_t INS0{"wq:INS0", 6000, -14};
static constexpr wq_config_t INS1{"wq:INS1", 6000, -15};
static constexpr wq_config_t INS2{"wq:INS2", 6000, -16};
static constexpr wq_config_t INS3{"wq:INS3", 6000, -17};

static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -18};

static constexpr wq_config_t uavcan{"wq:uavcan", 3624, -19};

static constexpr wq_config_t UART0{"wq:UART0", 1400, -21};
static constexpr wq_config_t UART1{"wq:UART1", 1400, -22};
static constexpr wq_config_t UART2{"wq:UART2", 1400, -23};
static constexpr wq_config_t UART3{"wq:UART3", 1400, -24};
static constexpr wq_config_t UART4{"wq:UART4", 1400, -25};
static constexpr wq_config_t UART5{"wq:UART5", 1400, -26};
static constexpr wq_config_t UART6{"wq:UART6", 1400, -27};
static constexpr wq_config_t UART7{"wq:UART7", 1400, -28};
static constexpr wq_config_t UART8{"wq:UART8", 1400, -29};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1400, -30};

static constexpr wq_config_t lp_default{"wq:lp_default", 1920, -50};

static constexpr wq_config_t test1{"wq:test1", 2000, 0};
static constexpr wq_config_t test2{"wq:test2", 2000, 0};

} // namespace wq_configurations

/**
 * Start the work queue manager task.
 */
int WorkQueueManagerStart();

/**
 * Stop the work queue manager task.
 */
int WorkQueueManagerStop();

/**
 * Work queue manager status.
 */
int WorkQueueManagerStatus();

/**
 * Create (or find) a work queue with a particular configuration.
 *
 * @param new_wq		The work queue configuration (see WorkQueueManager.hpp).
 * @return		A pointer to the WorkQueue, or nullptr on failure.
 */
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);

/**
 * Map a PX4 driver device id to a work queue (by sensor bus).
 *
 * @param device_id		The PX4 driver's device id.
 * @return		A work queue configuration.
 */
const wq_config_t &device_bus_to_wq(uint32_t device_id);

/**
 * Map a serial device path (eg /dev/ttyS1) to a work queue.
 *
 * @param device_id		The device path.
 * @return		A work queue configuration.
 */
const wq_config_t &serial_port_to_wq(const char *serial);

const wq_config_t &ins_instance_to_wq(uint8_t instance);

} // namespace px4
<commit_msg>px4_work_queue: increasae UART stack<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2019-2020 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#pragma once

#include <stdint.h>

namespace px4
{

class WorkQueue; // forward declaration

struct wq_config_t {
	const char *name;
	uint16_t stacksize;
	int8_t relative_priority; // relative to max
};

namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1920, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t ctrl_alloc{"wq:ctrl_alloc", 9500, 0}; // PX4 control allocation, same priority as rate_ctrl

static constexpr wq_config_t SPI0{"wq:SPI0", 2336, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 2336, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 2336, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 2336, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 2336, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 2336, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 2336, -7};

static constexpr wq_config_t I2C0{"wq:I2C0", 2336, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 2336, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 2336, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 2336, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 2336, -12};

// PX4 att/pos controllers, highest priority after sensors.
static constexpr wq_config_t nav_and_controllers{"wq:nav_and_controllers", 2164, -13};

static constexpr wq_config_t INS0{"wq:INS0", 6000, -14};
static constexpr wq_config_t INS1{"wq:INS1", 6000, -15};
static constexpr wq_config_t INS2{"wq:INS2", 6000, -16};
static constexpr wq_config_t INS3{"wq:INS3", 6000, -17};

static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -18};

static constexpr wq_config_t uavcan{"wq:uavcan", 3624, -19};

static constexpr wq_config_t UART0{"wq:UART0", 1504, -21};
static constexpr wq_config_t UART1{"wq:UART1", 1504, -22};
static constexpr wq_config_t UART2{"wq:UART2", 1504, -23};
static constexpr wq_config_t UART3{"wq:UART3", 1504, -24};
static constexpr wq_config_t UART4{"wq:UART4", 1504, -25};
static constexpr wq_config_t UART5{"wq:UART5", 1504, -26};
static constexpr wq_config_t UART6{"wq:UART6", 1504, -27};
static constexpr wq_config_t UART7{"wq:UART7", 1504, -28};
static constexpr wq_config_t UART8{"wq:UART8", 1504, -29};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1504, -30};

static constexpr wq_config_t lp_default{"wq:lp_default", 1920, -50};

static constexpr wq_config_t test1{"wq:test1", 2000, 0};
static constexpr wq_config_t test2{"wq:test2", 2000, 0};

} // namespace wq_configurations

/**
 * Start the work queue manager task.
 */
int WorkQueueManagerStart();

/**
 * Stop the work queue manager task.
 */
int WorkQueueManagerStop();

/**
 * Work queue manager status.
 */
int WorkQueueManagerStatus();

/**
 * Create (or find) a work queue with a particular configuration.
 *
 * @param new_wq		The work queue configuration (see WorkQueueManager.hpp).
 * @return		A pointer to the WorkQueue, or nullptr on failure.
 */
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);

/**
 * Map a PX4 driver device id to a work queue (by sensor bus).
 *
 * @param device_id		The PX4 driver's device id.
 * @return		A work queue configuration.
 */
const wq_config_t &device_bus_to_wq(uint32_t device_id);

/**
 * Map a serial device path (eg /dev/ttyS1) to a work queue.
 *
 * @param device_id		The device path.
 * @return		A work queue configuration.
 */
const wq_config_t &serial_port_to_wq(const char *serial);

const wq_config_t &ins_instance_to_wq(uint8_t instance);

} // namespace px4
<|endoftext|>


<commit_before>// The "Square Detector" program.
// It loads several images sequentially and tries to find squares in
// each image

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <math.h>
#include <string.h>
#include <stdio.h>

#include <ros/ros.h>
#include <osuar_vision/windowCoordinates.h>

using namespace cv;

int thresh = 50, N = 11;

// Threshold for maximum cosine between angles (x100).
int maxCosineThresh = 25;

// Threshold for ratio of shortest side / longest side (x100).
int sideRatioThresh = 75;

// Find colors of any hue...
int wallHueLow  = 0;
int wallHueHigh = 179;

// ...of low saturation...
int wallSatLow  = 0;
int wallSatHigh = 40;

// ...ranging down to gray, but not completely dark. That is to say, white.
int wallValLow  = 50;
int wallValHigh = 255;

ros::Publisher visPub;
osuar_vision::windowCoordinates winCoords;

// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
static double angle( Point pt1, Point pt2, Point pt0 )
{
    double dx1 = pt1.x - pt0.x;
    double dy1 = pt1.y - pt0.y;
    double dx2 = pt2.x - pt0.x;
    double dy2 = pt2.y - pt0.y;
    return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
static void findSquares( const Mat& image, vector<vector<Point> >& squares )
{
    squares.clear();

    Mat pyr, timg, gray0(image.size(), CV_8U), gray;

    // down-scale and upscale the image to filter out the noise
    pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
    pyrUp(pyr, timg, image.size());
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    //for( int c = 0; c < 3; c++ )
    //{
        //int ch[] = {c, 0};
        //mixChannels(&timg, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        for( int l = 0; l < N; l++ )
        {
            // hack: use Canny instead of zero threshold level.
            // Canny helps to catch squares with gradient shading
            if( l == 0 )
            {
                // apply Canny. Take the upper threshold from slider
                // and set the lower to 0 (which forces edges merging)
                Canny(image, gray, 0, thresh, 5);
                // dilate canny output to remove potential
                // holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                // apply threshold if l!=0:
                //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
                gray = image >= (l+1)*255/N;
            }

            // find contours and store them all as a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            vector<Point> approx;

            // test each contour
            for( size_t i = 0; i < contours.size(); i++ )
            {
                // approximate contour with accuracy proportional
                // to the contour perimeter
                approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                // square contours should have 4 vertices after approximation
                // relatively large area (to filter out noisy contours)
                // and be convex.
                // Note: absolute value of an area is used because
                // area may be positive or negative - in accordance with the
                // contour orientation
                if( approx.size() == 4 &&
                    fabs(contourArea(Mat(approx))) > 1000 &&
                    isContourConvex(Mat(approx)) )
                {
                    double maxCosine = 0;
                    double minSideLen = 100000;
                    double maxSideLen = 0;
                    double sideRatio = 0;

                    for( int j = 2; j < 5; j++ )
                    {
                        // find the maximum cosine of the angle between joint edges
                        double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                        maxCosine = MAX(maxCosine, cosine);

                        // Find the maximum difference in length of adjacent
                        // sides
                        double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2));
                        minSideLen = MIN(minSideLen, sideLen);
                        maxSideLen = MAX(maxSideLen, sideLen);
                    }

                    sideRatio = minSideLen / maxSideLen;

                    std::cout << minSideLen << "  " << maxSideLen << "\n";

                    // if cosines of all angles are small
                    // (all angles are ~90 degree) then write quandrange
                    // vertices to resultant sequence
                    if( maxCosine < ((double) maxCosineThresh)/100 && sideRatio >= (double) sideRatioThresh/100 )
                        squares.push_back(approx);
                }
            }
        }
    //}
}

// the function draws all the squares in the image
static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
    for( size_t i = 0; i < squares.size(); i++ )
    {
        const Point* p = &squares[i][0];
        int n = (int)squares[i].size();
        polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);

        std::cout << "x: " << squares[i][0].x << "  y: " << squares[i][0].y << "\n";

        // Only publish coordinates for one of the squares. Coordinates are
        // shifted over by half the camera resolution (which itself is scaled
        // down by a factor of two!) on each axis. The y coordinate is inverted
        // so up is positive.
        if (i == 0) {
            winCoords.x =   (squares[0][0].x + squares[0][2].x)/2 - 180;
            winCoords.y = -((squares[0][0].y + squares[0][2].y)/2 - 120);
            visPub.publish(winCoords);
        }
    }
}

int main(int argc, char** argv) {
    ros::init(argc, argv, "vision");
    ros::NodeHandle nh;
    visPub = nh.advertise<osuar_vision::windowCoordinates>("window_coordinates", 1);

    // Instantiate VideoCapture object. See here for details:
    // http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html
    VideoCapture cap(1);

    // Configure video. Our camera NEEDS the frame width to be set to 720
    // pixels.
    cap.set(CV_CAP_PROP_FRAME_WIDTH, 720);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
    //cap.set(CV_CAP_PROP_FPS, 20);

    // Instantiate a Mat in which to store each video frame.
    Mat origFrame;
    Mat resizedFrame;   // Scaled-down from origFrame by factor of 2.
    Mat hsvFrame;   // Converted to HSV space from resizedFrame.
    Mat bwFrame;   // Black/white image after thresholding hsvFrame.

    namedWindow("origImage", 1);
    namedWindow("hsvImage", 1);
    namedWindow("bwImage", 1);
    cvNamedWindow("control panel");
    cvCreateTrackbar("threshold",   "control panel", &thresh,      300, NULL);
    cvCreateTrackbar("maxCosineThresh (x100)", "control panel", &maxCosineThresh, 100, NULL);
    cvCreateTrackbar("sideRatioThresh (x100)", "control panel", &sideRatioThresh, 100, NULL);
    cvCreateTrackbar("wallHueLow",  "control panel", &wallHueLow,  179, NULL);
    cvCreateTrackbar("wallHueHigh", "control panel", &wallHueHigh, 179, NULL);
    cvCreateTrackbar("wallSatLow",  "control panel", &wallSatLow,  255, NULL);
    cvCreateTrackbar("wallSatHigh", "control panel", &wallSatHigh, 255, NULL);
    cvCreateTrackbar("wallValLow",  "control panel", &wallValLow,  255, NULL);
    cvCreateTrackbar("wallValHigh", "control panel", &wallValHigh, 255, NULL);
    vector<vector<Point> > squares;

    while (true) {
        // Capture image.
        cap >> origFrame;

        // Resize the image to increase processing rate. See here for details:
        // http://opencv.willowgarage.com/documentation/cpp/image_filtering.html
        pyrDown(origFrame, resizedFrame, Size(origFrame.cols/2, origFrame.rows/2));

        // Convert the frame to HSV. TODO: combine this with more filtering and
        // turn into function.
        cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV);

        // Threshold hsvFrame for color of maze walls.
        inRange(hsvFrame, Scalar(wallHueLow,  wallSatLow,  wallValLow),
                          Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame);

        // Find and draw squares.
        findSquares(bwFrame, squares);
        drawSquares(resizedFrame, squares);

        // Show the image, with the squares overlaid.
        imshow("origImage", resizedFrame);
        imshow("hsvImage", hsvFrame);
        imshow("bwImage", bwFrame);

        // Wait 5 milliseconds for a keypress.
        int c = waitKey(5);
        // Exit if the spacebar is pressed. NOTE: killing the program with
        // Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel
        // panic! If you really like Ctrl+C, do so at your own risk!
        if ((char) c == 32) {
            return 0;
        }
    }

    return 0;
}
<commit_msg>Label the four corners of each recognized square.<commit_after>// The "Square Detector" program.
// It loads several images sequentially and tries to find squares in
// each image

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <iostream>
#include <math.h>
#include <string.h>
#include <stdio.h>

#include <ros/ros.h>
#include <osuar_vision/windowCoordinates.h>

using namespace cv;

int thresh = 50, N = 11;

// Threshold for maximum cosine between angles (x100).
int maxCosineThresh = 25;

// Threshold for ratio of shortest side / longest side (x100).
int sideRatioThresh = 75;

// Find colors of any hue...
int wallHueLow  = 0;
int wallHueHigh = 179;

// ...of low saturation...
int wallSatLow  = 0;
int wallSatHigh = 40;

// ...ranging down to gray, but not completely dark. That is to say, white.
int wallValLow  = 50;
int wallValHigh = 255;

ros::Publisher visPub;
osuar_vision::windowCoordinates winCoords;

// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
static double angle( Point pt1, Point pt2, Point pt0 )
{
    double dx1 = pt1.x - pt0.x;
    double dy1 = pt1.y - pt0.y;
    double dx2 = pt2.x - pt0.x;
    double dy2 = pt2.y - pt0.y;
    return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
static void findSquares( const Mat& image, vector<vector<Point> >& squares )
{
    squares.clear();

    Mat pyr, timg, gray0(image.size(), CV_8U), gray;

    // down-scale and upscale the image to filter out the noise
    pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
    pyrUp(pyr, timg, image.size());
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    //for( int c = 0; c < 3; c++ )
    //{
        //int ch[] = {c, 0};
        //mixChannels(&timg, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        for( int l = 0; l < N; l++ )
        {
            // hack: use Canny instead of zero threshold level.
            // Canny helps to catch squares with gradient shading
            if( l == 0 )
            {
                // apply Canny. Take the upper threshold from slider
                // and set the lower to 0 (which forces edges merging)
                Canny(image, gray, 0, thresh, 5);
                // dilate canny output to remove potential
                // holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                // apply threshold if l!=0:
                //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
                gray = image >= (l+1)*255/N;
            }

            // find contours and store them all as a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            vector<Point> approx;

            // test each contour
            for( size_t i = 0; i < contours.size(); i++ )
            {
                // approximate contour with accuracy proportional
                // to the contour perimeter
                approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                // square contours should have 4 vertices after approximation
                // relatively large area (to filter out noisy contours)
                // and be convex.
                // Note: absolute value of an area is used because
                // area may be positive or negative - in accordance with the
                // contour orientation
                if( approx.size() == 4 &&
                    fabs(contourArea(Mat(approx))) > 1000 &&
                    isContourConvex(Mat(approx)) )
                {
                    double maxCosine = 0;
                    double minSideLen = 100000;
                    double maxSideLen = 0;
                    double sideRatio = 0;

                    for( int j = 2; j < 5; j++ )
                    {
                        // find the maximum cosine of the angle between joint edges
                        double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                        maxCosine = MAX(maxCosine, cosine);

                        // Find the maximum difference in length of adjacent
                        // sides
                        double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2));
                        minSideLen = MIN(minSideLen, sideLen);
                        maxSideLen = MAX(maxSideLen, sideLen);
                    }

                    sideRatio = minSideLen / maxSideLen;

                    std::cout << minSideLen << "  " << maxSideLen << "\n";

                    // if cosines of all angles are small
                    // (all angles are ~90 degree) then write quandrange
                    // vertices to resultant sequence
                    if( maxCosine < ((double) maxCosineThresh)/100 && sideRatio >= (double) sideRatioThresh/100 )
                        squares.push_back(approx);
                }
            }
        }
    //}
}

// the function draws all the squares in the image
static void drawSquares( Mat& image, const vector<vector<Point> >& squares )
{
    for( size_t i = 0; i < squares.size(); i++ )
    {
        const Point* p = &squares[i][0];
        int n = (int)squares[i].size();
        polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);

        std::cout << "x: " << squares[i][0].x << "  y: " << squares[i][0].y << "\n";

        // Only publish coordinates for one of the squares. Coordinates are
        // shifted over by half the camera resolution (which itself is scaled
        // down by a factor of two!) on each axis. The y coordinate is inverted
        // so up is positive.
        if (i == 0) {
            putText(image, "0", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));
            putText(image, "1", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));
            putText(image, "2", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));
            putText(image, "3", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));
            winCoords.x =   (squares[0][0].x + squares[0][2].x)/2 - 180;
            winCoords.y = -((squares[0][0].y + squares[0][2].y)/2 - 120);
            visPub.publish(winCoords);
        }
    }
}

int main(int argc, char** argv) {
    ros::init(argc, argv, "vision");
    ros::NodeHandle nh;
    visPub = nh.advertise<osuar_vision::windowCoordinates>("window_coordinates", 1);

    // Instantiate VideoCapture object. See here for details:
    // http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html
    VideoCapture cap(1);

    // Configure video. Our camera NEEDS the frame width to be set to 720
    // pixels.
    cap.set(CV_CAP_PROP_FRAME_WIDTH, 720);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
    //cap.set(CV_CAP_PROP_FPS, 20);

    // Instantiate a Mat in which to store each video frame.
    Mat origFrame;
    Mat resizedFrame;   // Scaled-down from origFrame by factor of 2.
    Mat hsvFrame;   // Converted to HSV space from resizedFrame.
    Mat bwFrame;   // Black/white image after thresholding hsvFrame.

    namedWindow("origImage", 1);
    namedWindow("hsvImage", 1);
    namedWindow("bwImage", 1);
    cvNamedWindow("control panel");
    cvCreateTrackbar("threshold",   "control panel", &thresh,      300, NULL);
    cvCreateTrackbar("maxCosineThresh (x100)", "control panel", &maxCosineThresh, 100, NULL);
    cvCreateTrackbar("sideRatioThresh (x100)", "control panel", &sideRatioThresh, 100, NULL);
    cvCreateTrackbar("wallHueLow",  "control panel", &wallHueLow,  179, NULL);
    cvCreateTrackbar("wallHueHigh", "control panel", &wallHueHigh, 179, NULL);
    cvCreateTrackbar("wallSatLow",  "control panel", &wallSatLow,  255, NULL);
    cvCreateTrackbar("wallSatHigh", "control panel", &wallSatHigh, 255, NULL);
    cvCreateTrackbar("wallValLow",  "control panel", &wallValLow,  255, NULL);
    cvCreateTrackbar("wallValHigh", "control panel", &wallValHigh, 255, NULL);
    vector<vector<Point> > squares;

    while (true) {
        // Capture image.
        cap >> origFrame;

        // Resize the image to increase processing rate. See here for details:
        // http://opencv.willowgarage.com/documentation/cpp/image_filtering.html
        pyrDown(origFrame, resizedFrame, Size(origFrame.cols/2, origFrame.rows/2));

        // Convert the frame to HSV. TODO: combine this with more filtering and
        // turn into function.
        cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV);

        // Threshold hsvFrame for color of maze walls.
        inRange(hsvFrame, Scalar(wallHueLow,  wallSatLow,  wallValLow),
                          Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame);

        // Find and draw squares.
        findSquares(bwFrame, squares);
        drawSquares(resizedFrame, squares);

        // Show the image, with the squares overlaid.
        imshow("origImage", resizedFrame);
        imshow("hsvImage", hsvFrame);
        imshow("bwImage", bwFrame);

        // Wait 5 milliseconds for a keypress.
        int c = waitKey(5);
        // Exit if the spacebar is pressed. NOTE: killing the program with
        // Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel
        // panic! If you really like Ctrl+C, do so at your own risk!
        if ((char) c == 32) {
            return 0;
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef DLG_NEWPART_H
#define DLG_NEWPART_H

#include "../Partmod/disk.h"

//(*Headers(DlgNewPart)
#include <wx/stattext.h>
#include <wx/spinctrl.h>
#include <wx/choice.h>
#include <wx/button.h>
#include <wx/dialog.h>
//*)

class DlgNewPart: public wxDialog
{
	public:

		DlgNewPart(wxWindow* parent);
		virtual ~DlgNewPart();

		int ShowModal(Disk *disk, int);

		//(*Declarations(DlgNewPart)
		wxStaticText* StaticText2;
		wxChoice* ChoicePartitionType;
		wxButton* ButtonOK;
		wxStaticText* StaticText1;
		wxChoice* ChoiceFsType;
		wxButton* ButtonCancel;
		wxChoice* ChoiceSizeMul;
		wxSpinCtrl* SpinCtrlPartitionSize;
		//*)

	protected:

		//(*Identifiers(DlgNewPart)
		static const long IDA_HSHDGSDHUF;
		static const long ID_SIZE_MULTIPLIER;
		static const long ID_STATICTEXT1;
		static const long ID_OK;
		static const long ID_CHOICE1;
		static const long ID_STATICTEXT2;
		static const long ID_CHOICE2;
		//*)

	private:
        int selected_frs;
        Disk *disk;

		//(*Handlers(DlgNewPart)
		void OnButtonOKClick(wxCommandEvent& event);
		void OnButtonCancelClick(wxCommandEvent& event);
		void OnChoicePartitionTypeSelect(wxCommandEvent& event);
		//*)

		DECLARE_EVENT_TABLE()
};

#endif
<commit_msg>git-svn-id: svn://svn.code.sf.net/p/partmodproject/code/trunk@21 3d63fe75-a90b-4577-b595-b0b07fb0d485<commit_after>#ifndef DLG_NEWPART_H
#define DLG_NEWPART_H

#include "../Partmod/disk.h"

//(*Headers(DlgNewPart)
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/spinctrl.h>
#include <wx/choice.h>
#include <wx/dialog.h>
//*)

class DlgNewPart: public wxDialog
{
	public:

		DlgNewPart(wxWindow* parent);
		virtual ~DlgNewPart();

		int ShowModal(Disk *disk, int);

		//(*Declarations(DlgNewPart)
		wxStaticText* StaticText2;
		wxChoice* ChoicePartitionType;
		wxStaticText* StaticText1;
		wxChoice* ChoiceFsType;
		wxChoice* ChoiceSizeMul;
		wxSpinCtrl* SpinCtrlPartitionSize;
		//*)

	protected:

		//(*Identifiers(DlgNewPart)
		static const long ID_SPINCTRL1;
		static const long ID_CHOICE1;
		static const long ID_STATICTEXT1;
		static const long ID_CHOICE2;
		static const long ID_STATICTEXT2;
		static const long ID_CHOICE3;
		//*)

	private:
        int selected_frs;
        Disk *disk;

		//(*Handlers(DlgNewPart)
		void OnButtonOKClick(wxCommandEvent& event);
		void OnButtonCancelClick(wxCommandEvent& event);
		void OnChoicePartitionTypeSelect(wxCommandEvent& event);
		void OnChoice2Select(wxCommandEvent& event);
		//*)

		DECLARE_EVENT_TABLE()
};

#endif
<|endoftext|>


<commit_before>enum TagType
{
    TAG_UI_CONTAINER =0,
    TAG_BUTTON,
    TAG_LISTBOX,//No extra details
    TAG_TEXTFIELD,
    TAG_SCROLLBAR,
    TAG_LABEL,
    TAG_DYNAMIC_IMAGE,
    TAG_LABEL_FONT,
    TAG_IMAGE = 12//No extra details
};

#define TAUI_ATTRIBUTE_SCROLLBAR_HORIZONTAL 1
#define TAUI_ATTRIBUTE_SCROLLBAR_VERTICAL 2

const int FILE_UI_MAX_STRING_LENGTH  = 32;

struct TAUIElement
{
    char * Name;
    TagType ElementType;
    int Association,X,Y,Width,Height,ColorFore,ColorBack,TextureNumber,FontNumber;
    int Attributes, CommonAttributes;
    char * Help;
    uint8_t Visible;//Pulls from active
    void * Details;
};

struct TAUIContainer
{
    Texture * Background;//Name is in Panel
    TAUIElement * DefaultFocus;
    int NumberOfElements;
    TAUIElement * Elements;
    TextureContainer * Textures;
};

struct TAUIButton
{
    int StartingFrame;//pulls from status
    int Stages;
    char * Text;// | seperator for multistage buttons, center aligned for simple (single stage) buttons, right aligned otherwise
    uint8_t Disabled;//pulls from grayedout
};

struct TAUITextBox
{
    int MaximumCharacters;
};

struct TAUIScrollbar
{
    int Maximum;
    int Position;
    int KnobSize;
};

struct TAUILabel
{
    char * Text;
    TAUIButton * Link;
};

struct TAUIDynamicImage
{
    uint8_t DisaplySelectionRectangle;//Puller from hotornot
};

struct TAULabelFont
{
    FNTFont * Font;//from filename
};

struct FILE_UINameValue
{
    char Name[FILE_UI_MAX_STRING_LENGTH];
    char Value[FILE_UI_MAX_STRING_LENGTH];
    FILE_UINameValue * Next;
};

struct FILE_UIElement
{
    FILE_UIElement * Next;
    FILE_UIElement * Child;
    FILE_UINameValue * Value;
    char Name[FILE_UI_MAX_STRING_LENGTH];
};

char * GetStringValue(FILE_UIElement * Element, const char * Name)
{
    FILE_UINameValue * NameValue = Element->Value;
    while(NameValue)
    {
	if(CaseInsensitiveMatch(Name, NameValue->Name))
	    return NameValue->Value;
	NameValue = NameValue->Next;
    }
    return 0;
}

int GetIntValue(FILE_UIElement * Element, const char * Name)
{
    char * Value=GetStringValue(Element,Name);
    if(Value)
	return atoi(Value);
    return -1;
}

float GetFloat(FILE_UIElement * Element, const char * Name)
{
    char * Value= GetStringValue(Element,Name);
    if(Value)
	return (float)atof(Value);
    return -1;
}

FILE_UIElement * GetSubElement(FILE_UIElement * Root, const char * Name)
{
    FILE_UIElement * element = Root->Child;
    while(element)
    {
	if(CaseInsensitiveMatch(Name, element->Name))
	    return element;
	element=element->Next;
    }
    return 0;
}

FILE_UIElement * GetNthElement(FILE_UIElement * Start, int N)
{
    if(N ==0 || !Start)
	return Start;
    return GetNthElement(Start, N-1);
}

int CountElements(FILE_UIElement * First)
{
    int count = 0;
    while(First)
    {
	First = First->Next;
	count++;
    }
    return count;
}

FILE_UINameValue * LoadUINameValueFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)
{
    char * Buffer = *InBuffer;
    char * Start=Buffer;
    while(*Buffer != '=' && *Buffer != ' ' && *Buffer != '\t' && *Buffer != '\r' && *Buffer!='\n' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    char sep = *Buffer;
    *Buffer =0;
    FILE_UINameValue * Result = PushStruct(Arena, FILE_UINameValue);
    *Result={};
    strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);
    Buffer++;
    if(sep != '=')
    {
	while((*Buffer == '=' || *Buffer != ' ' || *Buffer != '\t' || *Buffer != '\r' || *Buffer!='\n')
	      && Buffer <=End) {  Buffer++;  }
	if(Buffer >= End){	return 0; }
    }
    Start = Buffer;
    while(*Buffer != ';' && Buffer <=End) {  Buffer++;  }
    if(Buffer >= End){	return 0; }
    *Buffer =0;
    strncpy(Result->Value, Start, FILE_UI_MAX_STRING_LENGTH);
    Buffer++;

    *InBuffer = Buffer;
    return Result;
}

FILE_UIElement * LoadUIElementFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)
{
    char * Buffer = *InBuffer;
    while(*Buffer != '[' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    char * Start = Buffer+1;
    while(*Buffer != ']' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    *Buffer =0;

    FILE_UIElement * Result = PushStruct(Arena, FILE_UIElement);
    *Result={};
    strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);
    while(*Buffer != '{' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    Buffer++;

    while(Buffer<=End)
    {
	while((*Buffer == ' ' || *Buffer == '\t' || *Buffer =='\r' || *Buffer == '\n' )&& Buffer <=End) {  Buffer++;  }
	if(Buffer == End){	return 0; }
	if(*Buffer =='}')
	{
	    Buffer++;
	    *InBuffer = Buffer;
	    return Result;
	}
	else if(*Buffer == '[')
	{
	    if(Result->Child)
	    {
		FILE_UIElement * Child = Result->Child;
		while(Child->Next)
		{
		    Child=Child->Next;
		}
		Child->Next=LoadUIElementFromBuffer(&Buffer,End, Arena);
	    }
	    else
	    {
		Result->Child = LoadUIElementFromBuffer(&Buffer, End, Arena);
	    }
	}
	else
	{
	    if(Result->Value)
	    {
		FILE_UINameValue * Value = Result->Value;
		while(Value->Next)
		{
		    Value=Value->Next;
		}
		Value->Next = LoadUINameValueFromBuffer(&Buffer, End, Arena);
	    }
	    else
	    {
		Result->Value=LoadUINameValueFromBuffer(&Buffer, End, Arena);
	    }
	}

    }
    *InBuffer = Buffer;
    return 0;
}

FILE_UIElement * LoadUIElementsFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)
{
    FILE_UIElement * First = LoadUIElementFromBuffer(InBuffer, End, Arena);
    FILE_UIElement * Last = First;
    while(*InBuffer <End)
    {
	Last->Next = LoadUIElementFromBuffer(InBuffer, End, Arena);
	if(Last->Next)
	{
	    Last = Last->Next;
	}
    }
    return First;
}

void LoadElementFromTree(TAUIElement * Element, FILE_UIElement * Tree, MemoryArena * Arena, TextureContainer * Textures, GameState * CurrentGameState)
{
    FILE_UIElement * Common = GetSubElement(Tree,"common");
    Element->ElementType = (TagType)GetIntValue(Common, "ID");

    Element->Association = GetIntValue(Common, "assoc");
    Element->X = GetIntValue(Common, "xpos");
    Element->Y = GetIntValue(Common, "ypos");
    Element->Width = GetIntValue(Common, "width");
    Element->Height = GetIntValue(Common, "height");
    Element->Attributes = GetIntValue(Common, "attribs");
    Element->ColorFore = GetIntValue(Common, "colorf");
    Element->ColorBack = GetIntValue(Common, "colorb");
    Element->TextureNumber = GetIntValue(Common, "texturenumber");
    Element->FontNumber = GetIntValue(Common, "fontnumber");
    Element->CommonAttributes = GetIntValue(Common, "commonattribs");
    Element->Visible = GetIntValue(Common, "active");

    char * Name = GetStringValue(Common, "name");
    int len = strlen(Name);
    Element->Name = PushArray(Arena, len+1, char);
    if(Element->Name)
    {
	memcpy(Element->Name, Name, len);
	Element->Name[len]=0;
    }

    char * Help = GetStringValue(Common, "help");

    len = strlen(Help);
    Element->Help = PushArray(Arena, len+1, char);
    if(Element->Help)
    {
	memcpy(Element->Help, Help, len);
	Element->Help[len]=0;
    }

    switch(Element->ElementType)
    {
    case TAG_UI_CONTAINER:
    {
	TAUIContainer * Container = PushStruct(Arena, TAUIContainer);
	Element->Details = Container;
	if(CaseInsensitiveMatch(Name, "Mainmenu.gui"))
	{
	    Container->Background = AddPCXToTextureContainer(Textures,"bitmaps/FrontEndX.pcx", CurrentGameState);
	}
	else
	{
	    Container->Background = GetTexture(Name, Textures);
	}
    }
	break;

    }

}

TAUIElement * LoadGUIFromBuffer(char * Buffer, char * End, MemoryArena * Arena, MemoryArena * TempArena, char * FileName, GameState * CurrentGameState)
{
    TextureContainer * Textures =PushStruct(Arena, TextureContainer);
    SetupTextureContainer(Textures, 1024,1024, 40, Arena);

    int len=snprintf(0,0,"anims/%s",FileName)+1;
    STACK_ARRAY(GafFileName,len,char);
    snprintf(GafFileName,len,"anims/%s",FileName);
    GafFileName[len-4]='g';
    GafFileName[len-3]='a';
    GafFileName[len-2]='f';

    HPIEntry UITextures = FindEntryInAllFiles(GafFileName, CurrentGameState);
    if(UITextures.IsDirectory)
    {
	LogError("Unexpectedly found a directory while trying to load %s", GafFileName);
    }
    else if(!UITextures.Name)
    {
	LogError("Failed to load %s", GafFileName);
    }
    else
    {
	LoadAllTexturesFromHPIEntry(&UITextures, Textures, TempArena, CurrentGameState->PaletteData);
    }
    MemoryArena * UIElementsArena = PushSubArena(TempArena, 16 * 1024);
    FILE_UIElement * First = LoadUIElementsFromBuffer(&Buffer, End, UIElementsArena);

    if(GetIntValue(GetSubElement(First,"common"),"ID") != 0)
    {
	LogError("First UI element is not a container (%d)!",GetIntValue(GetSubElement(First,"common"),"ID"));
	return 0;
    }

    TAUIElement * Container = PushStruct(Arena, TAUIElement);
    LoadElementFromTree(Container, First, Arena, Textures, CurrentGameState);

    TAUIContainer * ContainerDetails = (TAUIContainer *)Container->Details;
    ContainerDetails->NumberOfElements = CountElements(First)-1;
    ContainerDetails->Elements = PushArray(Arena, ContainerDetails->NumberOfElements, TAUIElement);
    ContainerDetails->Textures = Textures;

    for(int i=0;i<ContainerDetails->NumberOfElements;i++)
    {
	LoadElementFromTree(&ContainerDetails->Elements[i], GetNthElement(First, i+1), Arena, Textures, CurrentGameState);
    }

    PopSubArena(TempArena, UIElementsArena);
    return Container;
}

void LoadCommonUITextures(GameState * CurrentGameState)
{
    SetupTextureContainer(CurrentGameState->CommonGUITextures, COMMONUI_TEXTURE_WIDTH, COMMONUI_TEXTURE_HEIGHT, COMMONUI_MAX_TEXTURES, &CurrentGameState->GameArena);
    if(!CurrentGameState->PaletteLoaded)
    {
	LoadPalette(CurrentGameState);
    }
    HPIEntry CommonUI = FindEntryInAllFiles("anims/commonGUI.GAF", CurrentGameState);
    if(CommonUI.IsDirectory)
    {
	LogError("Unexpectedly found a directory while trying to load hatfont12.gaf");
    }
    else if(!CommonUI.Name)
    {
	LogError("Failed to get commonGUI.gaf");
    }
    else
    {
	LoadAllTexturesFromHPIEntry(&CommonUI, CurrentGameState->CommonGUITextures, &CurrentGameState->TempArena, CurrentGameState->PaletteData);
    }

}
<commit_msg>Load more types of UI elements from GUI files.<commit_after>enum TagType
{
    TAG_UI_CONTAINER =0,
    TAG_BUTTON,
    TAG_LISTBOX,//No extra details
    TAG_TEXTFIELD,
    TAG_SCROLLBAR,
    TAG_LABEL,
    TAG_DYNAMIC_IMAGE,
    TAG_LABEL_FONT,
    TAG_IMAGE = 12//No extra details
};

#define TAUI_ATTRIBUTE_SCROLLBAR_HORIZONTAL 1
#define TAUI_ATTRIBUTE_SCROLLBAR_VERTICAL 2

const int FILE_UI_MAX_STRING_LENGTH  = 32;

struct TAUIElement
{
    char * Name;
    TagType ElementType;
    int Association,X,Y,Width,Height,ColorFore,ColorBack,TextureNumber,FontNumber;
    int Attributes, CommonAttributes;
    char * Help;
    uint8_t Visible;//Pulls from active
    void * Details;
};

struct TAUIContainer
{
    Texture * Background;//Name is in Panel
    TAUIElement * DefaultFocus;
    int NumberOfElements;
    TAUIElement * Elements;
    TextureContainer * Textures;
};

struct TAUIButton
{
    int StartingFrame;//pulls from status
    int Stages;
    char * Text;// | seperator for multistage buttons, center aligned for simple (single stage) buttons, right aligned otherwise
    uint8_t Disabled;//pulls from grayedout
};

struct TAUITextBox
{
    int MaximumCharacters;
};

struct TAUIScrollbar
{
    int Maximum;
    int Position;
    int KnobSize;
};

struct TAUILabel
{
    char * Text;
    TAUIButton * Link;
};

struct TAUIDynamicImage
{
    uint8_t DisaplySelectionRectangle;//Puller from hotornot
};

struct TAULabelFont
{
    FNTFont * Font;//from filename
};

struct FILE_UINameValue
{
    char Name[FILE_UI_MAX_STRING_LENGTH];
    char Value[FILE_UI_MAX_STRING_LENGTH];
    FILE_UINameValue * Next;
};

struct FILE_UIElement
{
    FILE_UIElement * Next;
    FILE_UIElement * Child;
    FILE_UINameValue * Value;
    char Name[FILE_UI_MAX_STRING_LENGTH];
};

char * GetStringValue(FILE_UIElement * Element, const char * Name)
{
    FILE_UINameValue * NameValue = Element->Value;
    while(NameValue)
    {
	if(CaseInsensitiveMatch(Name, NameValue->Name))
	    return NameValue->Value;
	NameValue = NameValue->Next;
    }
    return 0;
}

int GetIntValue(FILE_UIElement * Element, const char * Name)
{
    char * Value=GetStringValue(Element,Name);
    if(Value)
	return atoi(Value);
    return -1;
}

float GetFloat(FILE_UIElement * Element, const char * Name)
{
    char * Value= GetStringValue(Element,Name);
    if(Value)
	return (float)atof(Value);
    return -1;
}

FILE_UIElement * GetSubElement(FILE_UIElement * Root, const char * Name)
{
    FILE_UIElement * element = Root->Child;
    while(element)
    {
	if(CaseInsensitiveMatch(Name, element->Name))
	    return element;
	element=element->Next;
    }
    return 0;
}

FILE_UIElement * GetNthElement(FILE_UIElement * Start, int N)
{
    if(N ==0 || !Start)
	return Start;
    return GetNthElement(Start, N-1);
}

int CountElements(FILE_UIElement * First)
{
    int count = 0;
    while(First)
    {
	First = First->Next;
	count++;
    }
    return count;
}

FILE_UINameValue * LoadUINameValueFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)
{
    char * Buffer = *InBuffer;
    char * Start=Buffer;
    while(*Buffer != '=' && *Buffer != ' ' && *Buffer != '\t' && *Buffer != '\r' && *Buffer!='\n' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    char sep = *Buffer;
    *Buffer =0;
    FILE_UINameValue * Result = PushStruct(Arena, FILE_UINameValue);
    *Result={};
    strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);
    Buffer++;
    if(sep != '=')
    {
	while((*Buffer == '=' || *Buffer != ' ' || *Buffer != '\t' || *Buffer != '\r' || *Buffer!='\n')
	      && Buffer <=End) {  Buffer++;  }
	if(Buffer >= End){	return 0; }
    }
    Start = Buffer;
    while(*Buffer != ';' && Buffer <=End) {  Buffer++;  }
    if(Buffer >= End){	return 0; }
    *Buffer =0;
    strncpy(Result->Value, Start, FILE_UI_MAX_STRING_LENGTH);
    Buffer++;

    *InBuffer = Buffer;
    return Result;
}

FILE_UIElement * LoadUIElementFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)
{
    char * Buffer = *InBuffer;
    while(*Buffer != '[' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    char * Start = Buffer+1;
    while(*Buffer != ']' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    *Buffer =0;

    FILE_UIElement * Result = PushStruct(Arena, FILE_UIElement);
    *Result={};
    strncpy(Result->Name, Start, FILE_UI_MAX_STRING_LENGTH);
    while(*Buffer != '{' && Buffer <=End) {  Buffer++;  }
    if(Buffer == End){	return 0; }
    Buffer++;

    while(Buffer<=End)
    {
	while((*Buffer == ' ' || *Buffer == '\t' || *Buffer =='\r' || *Buffer == '\n' )&& Buffer <=End) {  Buffer++;  }
	if(Buffer == End){	return 0; }
	if(*Buffer =='}')
	{
	    Buffer++;
	    *InBuffer = Buffer;
	    return Result;
	}
	else if(*Buffer == '[')
	{
	    if(Result->Child)
	    {
		FILE_UIElement * Child = Result->Child;
		while(Child->Next)
		{
		    Child=Child->Next;
		}
		Child->Next=LoadUIElementFromBuffer(&Buffer,End, Arena);
	    }
	    else
	    {
		Result->Child = LoadUIElementFromBuffer(&Buffer, End, Arena);
	    }
	}
	else
	{
	    if(Result->Value)
	    {
		FILE_UINameValue * Value = Result->Value;
		while(Value->Next)
		{
		    Value=Value->Next;
		}
		Value->Next = LoadUINameValueFromBuffer(&Buffer, End, Arena);
	    }
	    else
	    {
		Result->Value=LoadUINameValueFromBuffer(&Buffer, End, Arena);
	    }
	}

    }
    *InBuffer = Buffer;
    return 0;
}

FILE_UIElement * LoadUIElementsFromBuffer(char ** InBuffer, char * End, MemoryArena * Arena)
{
    FILE_UIElement * First = LoadUIElementFromBuffer(InBuffer, End, Arena);
    FILE_UIElement * Last = First;
    while(*InBuffer <End)
    {
	Last->Next = LoadUIElementFromBuffer(InBuffer, End, Arena);
	if(Last->Next)
	{
	    Last = Last->Next;
	}
    }
    return First;
}

void LoadElementFromTree(TAUIElement * Element, FILE_UIElement * Tree, MemoryArena * Arena, TextureContainer * Textures, GameState * CurrentGameState)
{
    FILE_UIElement * Common = GetSubElement(Tree,"common");
    Element->ElementType = (TagType)GetIntValue(Common, "ID");

    Element->Association = GetIntValue(Common, "assoc");
    Element->X = GetIntValue(Common, "xpos");
    Element->Y = GetIntValue(Common, "ypos");
    Element->Width = GetIntValue(Common, "width");
    Element->Height = GetIntValue(Common, "height");
    Element->Attributes = GetIntValue(Common, "attribs");
    Element->ColorFore = GetIntValue(Common, "colorf");
    Element->ColorBack = GetIntValue(Common, "colorb");
    Element->TextureNumber = GetIntValue(Common, "texturenumber");
    Element->FontNumber = GetIntValue(Common, "fontnumber");
    Element->CommonAttributes = GetIntValue(Common, "commonattribs");
    Element->Visible = GetIntValue(Common, "active");

    char * Name = GetStringValue(Common, "name");
    int len = strlen(Name);
    Element->Name = PushArray(Arena, len+1, char);
    if(Element->Name)
    {
	memcpy(Element->Name, Name, len);
	Element->Name[len]=0;
    }

    char * Help = GetStringValue(Common, "help");

    len = strlen(Help);
    Element->Help = PushArray(Arena, len+1, char);
    if(Element->Help)
    {
	memcpy(Element->Help, Help, len);
	Element->Help[len]=0;
    }

    switch(Element->ElementType)
    {
    case TAG_UI_CONTAINER:
    {
	TAUIContainer * Container = PushStruct(Arena, TAUIContainer);
	Element->Details = Container;
	if(CaseInsensitiveMatch(Name, "Mainmenu.gui"))
	{
	    Container->Background = AddPCXToTextureContainer(Textures,"bitmaps/FrontEndX.pcx", CurrentGameState);
	}
	else
	{
	    Container->Background = GetTexture(Name, Textures);
	}
    }
    break;
    case TAG_BUTTON:
    {
	TAUIButton * Button = PushStruct(Arena, TAUIButton);
	Element->Details = Button;
	Button->StartingFrame = GetIntValue(Tree, "status");
	Button->Stages = GetIntValue(Tree, "Stages");
	char * Text = GetStringValue(Tree, "text");
	int len = strlen(Text);
	Button->Text = PushArray(Arena, len+1, char);
	if(Button->Text)
	{
	    memcpy(Button->Text, Text, len);
	    Button->Text[len]=0;
	}

	Button->Disabled = GetIntValue(Tree, "grayedout");
    }
    break;
    case TAG_TEXTFIELD:
    {
	TAUITextBox * TextBox = PushStruct(Arena,TAUITextBox);
	Element->Details = TextBox;
	TextBox->MaximumCharacters = GetIntValue(Tree, "maxchars");
    }
    break;
    case TAG_SCROLLBAR:
    {
	TAUIScrollbar * ScrollBar = PushStruct(Arena, TAUIScrollbar);
	Element->Details = ScrollBar;
	ScrollBar->Maximum = GetIntValue(Tree, "range");
	ScrollBar->Position = GetIntValue(Tree, "knobpos");
	ScrollBar->KnobSize = GetIntValue(Tree, "knobsize");
    }
    break;
    //TODO(Christof): handle all UI elements
    }

}

TAUIElement * LoadGUIFromBuffer(char * Buffer, char * End, MemoryArena * Arena, MemoryArena * TempArena, char * FileName, GameState * CurrentGameState)
{
    TextureContainer * Textures =PushStruct(Arena, TextureContainer);
    SetupTextureContainer(Textures, 1024,1024, 40, Arena);

    int len=snprintf(0,0,"anims/%s",FileName)+1;
    STACK_ARRAY(GafFileName,len,char);
    snprintf(GafFileName,len,"anims/%s",FileName);
    GafFileName[len-4]='g';
    GafFileName[len-3]='a';
    GafFileName[len-2]='f';

    HPIEntry UITextures = FindEntryInAllFiles(GafFileName, CurrentGameState);
    if(UITextures.IsDirectory)
    {
	LogError("Unexpectedly found a directory while trying to load %s", GafFileName);
    }
    else if(!UITextures.Name)
    {
	LogError("Failed to load %s", GafFileName);
    }
    else
    {
	LoadAllTexturesFromHPIEntry(&UITextures, Textures, TempArena, CurrentGameState->PaletteData);
    }
    MemoryArena * UIElementsArena = PushSubArena(TempArena, 16 * 1024);
    FILE_UIElement * First = LoadUIElementsFromBuffer(&Buffer, End, UIElementsArena);

    if(GetIntValue(GetSubElement(First,"common"),"ID") != 0)
    {
	LogError("First UI element is not a container (%d)!",GetIntValue(GetSubElement(First,"common"),"ID"));
	return 0;
    }

    TAUIElement * Container = PushStruct(Arena, TAUIElement);
    LoadElementFromTree(Container, First, Arena, Textures, CurrentGameState);

    TAUIContainer * ContainerDetails = (TAUIContainer *)Container->Details;
    ContainerDetails->NumberOfElements = CountElements(First)-1;
    ContainerDetails->Elements = PushArray(Arena, ContainerDetails->NumberOfElements, TAUIElement);
    ContainerDetails->Textures = Textures;

    for(int i=0;i<ContainerDetails->NumberOfElements;i++)
    {
	LoadElementFromTree(&ContainerDetails->Elements[i], GetNthElement(First, i+1), Arena, Textures, CurrentGameState);
    }

    PopSubArena(TempArena, UIElementsArena);
    return Container;
}

void LoadCommonUITextures(GameState * CurrentGameState)
{
    SetupTextureContainer(CurrentGameState->CommonGUITextures, COMMONUI_TEXTURE_WIDTH, COMMONUI_TEXTURE_HEIGHT, COMMONUI_MAX_TEXTURES, &CurrentGameState->GameArena);
    if(!CurrentGameState->PaletteLoaded)
    {
	LoadPalette(CurrentGameState);
    }
    HPIEntry CommonUI = FindEntryInAllFiles("anims/commonGUI.GAF", CurrentGameState);
    if(CommonUI.IsDirectory)
    {
	LogError("Unexpectedly found a directory while trying to load hatfont12.gaf");
    }
    else if(!CommonUI.Name)
    {
	LogError("Failed to get commonGUI.gaf");
    }
    else
    {
	LoadAllTexturesFromHPIEntry(&CommonUI, CurrentGameState->CommonGUITextures, &CurrentGameState->TempArena, CurrentGameState->PaletteData);
    }

}
<|endoftext|>


<commit_before>
// Qt includes
#include <QApplication>
#include <QTimer>
#include <QDebug>

// Visomics includes
#include <voDelimitedTextImportDialog.h>

// STD includes
#include <cstdlib>

//-----------------------------------------------------------------------------
int voDelimitedTextImportDialogTest(int argc, char * argv [])
{
  QApplication app(argc, argv);

  Q_INIT_RESOURCE(VisomicsApp);

  // Read file
  QString filename("/home/jchris/Projects/Bioinformatics/Data/UNC/All_conc_kitware_transposed.csv");

  voDelimitedTextImportDialog dialog;
  dialog.setFileName(filename);

  dialog.show();

  QTimer autoExit;
  if (argc < 2 || QString(argv[1]) != "-I")
    {
    QObject::connect(&autoExit, SIGNAL(timeout()), &dialog, SLOT(accept()));
    autoExit.start(1000);
    }

  return dialog.exec();
}

<commit_msg>Fix voDelimitedTextImportDialogTest<commit_after>
// Qt includes
#include <QApplication>
#include <QTimer>
#include <QDebug>

// Visomics includes
#include <voDelimitedTextImportDialog.h>

// STD includes
#include <cstdlib>

//-----------------------------------------------------------------------------
int voDelimitedTextImportDialogTest(int argc, char * argv [])
{
  QApplication app(argc, argv);

  Q_INIT_RESOURCE(VisomicsApp);

  // Read file
  QString filename("/home/jchris/Projects/Bioinformatics/Data/UNC/All_conc_kitware_transposed.csv");

  voDelimitedTextImportDialog dialog;
  dialog.setFileName(filename);

  dialog.show();

  QTimer autoExit;
  if (argc < 2 || QString(argv[1]) != "-I")
    {
    QObject::connect(&autoExit, SIGNAL(timeout()), &dialog, SLOT(accept()));
    autoExit.start(1000);
    }

  int status = dialog.exec();
  if (status != QDialog::Accepted)
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#ifndef MAIN_HPP
#define MAIN_HPP

#include"bev_thrust.hpp"
#include"cuda_error_check.hpp"
#include"preprocess.hpp"
#include"rgb2gray.hpp"

#endif
<commit_msg>Updated Header<commit_after>#ifndef MAIN_HPP
#define MAIN_HPP

#include"bev_thrust.hpp"
#include"cuda_error_check.hpp"
#include"preprocess.hpp"
#include"rgb2gray.hpp"
#include"hough.hpp"

#endif
<|endoftext|>


<commit_before>#include "Task.hpp"
#include <iostream>

std::string Task::getName() {
	return name;
}

std::string Task::getDescription() {
	return description;
}

std::string Task::getAssignee() {
	return assignee;
}

int Task::getdueDate() {
	return dueDate;
}<commit_msg>TaskyClassy<commit_after>#include "Task.hpp"
#include <iostream>

std::string Task::getName() {
	return name;
}

std::string Task::getDescription() {
	return description;
}

std::string Task::getAssignee() {
	return assignee;
}

int Task::getdueDate() {
	return dueDate;
}

int Task::getDate() {
	return getDate;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_ISATRAITS_HH__
#define __ARCH_X86_ISATRAITS_HH__

#include "arch/x86/intregs.hh"
#include "arch/x86/types.hh"
#include "arch/x86/x86_traits.hh"

class StaticInstPtr;

namespace LittleEndianGuest {}

namespace X86ISA
{
    //This makes sure the little endian version of certain functions
    //are used.
    using namespace LittleEndianGuest;

    // X86 does not have a delay slot
#define ISA_HAS_DELAY_SLOT 0

    // X86 NOP (XCHG rAX, rAX)
    //XXX This needs to be set to an intermediate instruction struct
    //which encodes this instruction

    // These enumerate all the registers for dependence tracking.
    enum DependenceTags {
        //There are 16 microcode registers at the moment
        FP_Base_DepTag = 32,
        Ctrl_Base_DepTag =
            FP_Base_DepTag +
            //mmx/x87 registers
            8 +
            //xmm registers
            16
    };

    // semantically meaningful register indices
    //There is no such register in X86
    const int ZeroReg = NUM_INTREGS;
    const int StackPointerReg = INTREG_RSP;
    //X86 doesn't seem to have a link register
    const int ReturnAddressReg = 0;
    const int ReturnValueReg = INTREG_RAX;
    const int FramePointerReg = INTREG_RBP;
    const int ArgumentReg[] = {
        INTREG_RDI,
        INTREG_RSI,
        INTREG_RDX,
        //This argument register is r10 for syscalls and rcx for C.
        INTREG_R10W,
        //INTREG_RCX,
        INTREG_R8W,
        INTREG_R9W
    };
    const int NumArgumentRegs = sizeof(ArgumentReg) / sizeof(const int);

    // Some OS syscalls use a second register (rdx) to return a second
    // value
    const int SyscallPseudoReturnReg = INTREG_RDX;

    //XXX These numbers are bogus
    const int MaxInstSrcRegs = 10;
    const int MaxInstDestRegs = 10;

    //4k. This value is not constant on x86.
    const int LogVMPageSize = 12;
    const int VMPageSize = (1 << LogVMPageSize);

    const int PageShift = 13;
    const int PageBytes = 1ULL << PageShift;

    const int BranchPredAddrShiftAmt = 0;

    StaticInstPtr decodeInst(ExtMachInst);
};

#endif // __ARCH_X86_ISATRAITS_HH__
<commit_msg>X86: Make sure FP_Base_DepTag is big enough to avoid trouble.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_ISATRAITS_HH__
#define __ARCH_X86_ISATRAITS_HH__

#include "arch/x86/intregs.hh"
#include "arch/x86/types.hh"
#include "arch/x86/x86_traits.hh"

class StaticInstPtr;

namespace LittleEndianGuest {}

namespace X86ISA
{
    //This makes sure the little endian version of certain functions
    //are used.
    using namespace LittleEndianGuest;

    // X86 does not have a delay slot
#define ISA_HAS_DELAY_SLOT 0

    // X86 NOP (XCHG rAX, rAX)
    //XXX This needs to be set to an intermediate instruction struct
    //which encodes this instruction

    // These enumerate all the registers for dependence tracking.
    enum DependenceTags {
        //There are 16 microcode registers at the moment
        FP_Base_DepTag = 1 << 7,
        Ctrl_Base_DepTag =
            FP_Base_DepTag +
            //mmx/x87 registers
            8 +
            //xmm registers
            16
    };

    // semantically meaningful register indices
    //There is no such register in X86
    const int ZeroReg = NUM_INTREGS;
    const int StackPointerReg = INTREG_RSP;
    //X86 doesn't seem to have a link register
    const int ReturnAddressReg = 0;
    const int ReturnValueReg = INTREG_RAX;
    const int FramePointerReg = INTREG_RBP;
    const int ArgumentReg[] = {
        INTREG_RDI,
        INTREG_RSI,
        INTREG_RDX,
        //This argument register is r10 for syscalls and rcx for C.
        INTREG_R10W,
        //INTREG_RCX,
        INTREG_R8W,
        INTREG_R9W
    };
    const int NumArgumentRegs = sizeof(ArgumentReg) / sizeof(const int);

    // Some OS syscalls use a second register (rdx) to return a second
    // value
    const int SyscallPseudoReturnReg = INTREG_RDX;

    //XXX These numbers are bogus
    const int MaxInstSrcRegs = 10;
    const int MaxInstDestRegs = 10;

    //4k. This value is not constant on x86.
    const int LogVMPageSize = 12;
    const int VMPageSize = (1 << LogVMPageSize);

    const int PageShift = 13;
    const int PageBytes = 1ULL << PageShift;

    const int BranchPredAddrShiftAmt = 0;

    StaticInstPtr decodeInst(ExtMachInst);
};

#endif // __ARCH_X86_ISATRAITS_HH__
<|endoftext|>


<commit_before>#include "include/Node.hpp"
#include "include/Tree.hpp"
#include <cstddef>
#include <iostream>

int main() {
    Node< std::string >* node = new Node< std::string >( 1, "Lorhan", nullptr, nullptr );
    std::cout << node->getValue() << std::endl;
    std::cout << node->left << std::endl;
    std::cout << node->right << std::endl;
    delete node;

    Tree< std::string > tree = Tree< std::string >();
    tree.insert( 10, "!" );
    tree.insert( 1, "Lorhan" );
    tree.insert( 2, "Sohaky" );
    tree.insert( 3, "top" );
    tree.insert( 4, "da" );
    tree.insert( 5, "balada" );
    std::cout << tree << std::endl;

    std::cout << tree.searchByValue( "top" ) << std::endl;
    std::cout << tree.searchByKey( 3 ) << std::endl;

    return 0;
}
<commit_msg>Adicionado mais um teste<commit_after>#include "include/Node.hpp"
#include "include/Tree.hpp"
#include <cstddef>
#include <iostream>

int main() {
    Node< std::string >* node = new Node< std::string >( 1, "Lorhan", nullptr, nullptr );
    std::cout << node->getValue() << std::endl;
    std::cout << node->left << std::endl;
    std::cout << node->right << std::endl;
    delete node;

    Tree< std::string > tree = Tree< std::string >();
    tree.insert( 10, "!" );
    tree.insert( 1, "Lorhan" );
    tree.insert( 2, "Sohaky" );
    tree.insert( 3, "top" );
    tree.insert( 4, "da" );
    tree.insert( 5, "balada" );
    std::cout << tree << std::endl;

    std::cout << tree.searchByValue( "top" ) << std::endl;
    std::cout << tree.searchByKey( 3 ) << std::endl;

    std::cout << "\n\n";
    Tree< char > tree2 = Tree< char >();

    tree2.insert( 2, '2' );
    tree2.insert( 1, '1' );
    tree2.insert( 4, '4' );
    tree2.insert( 3, '3' );
    tree2.insert( 5, '5' );
    std::cout << tree2 << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>#include "behaviour_xsensfollowing.h"
#include <QtGui>
#include <Behaviour_XsensFollowing/xsensfollowingform.h>
#include <Framework/Angles.h>

Behaviour_XsensFollowing::Behaviour_XsensFollowing(QString id, Module_ThrusterControlLoop *tcl, Module_XsensMTi *xsens)
    : RobotBehaviour(id)
{
    this->xsens = xsens;
    this->tcl = tcl;
    turnTimer.moveToThread(this);
    timer.moveToThread(this);

    this->setDefaultValue("timer",30);
    this->setDefaultValue("driveTime",10000);
    this->setDefaultValue("ffSpeed",0.3);
    this->setDefaultValue("kp",0.3);
    this->setDefaultValue("delta",0.3);
}

bool Behaviour_XsensFollowing::isActive()
{
    return isEnabled();
}

void Behaviour_XsensFollowing::init()
{
    logger->info("Xsens Following init");
    setEnabled(false);
    connect(this,SIGNAL(newAngularSpeed(float)),tcl,SLOT(setAngularSpeed(float)));
    connect(this,SIGNAL(newForwardSpeed(float)),tcl,SLOT(setForwardSpeed(float)));
    connect(&timer,SIGNAL(timeout()),this,SLOT(controlLoop()));
    connect(&turnTimer,SIGNAL(timeout()),this,SLOT(turnNinety()));
    connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));
}

void Behaviour_XsensFollowing::startBehaviour()
{
    if (this->isEnabled() == true){
        logger->info("Already enabled/started!");
        return;
    }
    logger->info("Starting Xsens Following");
    this->setEnabled(true);

    initialHeading = xsens->getHeading();
    ctrAngle = initialHeading;

    emit dataChanged(this);

    timer.start(getSettingsValue("timer").toInt());
    turnTimer.start(getSettingsValue("driveTime").toInt());
}

void Behaviour_XsensFollowing::stop()
{
    if(timer.isActive()){
        timer.stop();
    }
    if(turnTimer.isActive()){
        turnTimer.stop();
    }

    if (!isEnabled()) {
        return;
    }

    logger->info("Xsens follow stop");
    this->setEnabled(false);
    setEnabled(false);
    emit newAngularSpeed(0.0);
    emit newForwardSpeed(0.0);
    logger->info("Stop Xsens Following");
    emit finished(this,true);
}

void Behaviour_XsensFollowing::reset()
{
    logger->info("Xsens follow reset");
    if (this->isEnabled() == false){
        logger->info("Not enabled!");
        return;
    }
    timer.stop();
    turnTimer.stop();
    emit newAngularSpeed(0.0);
    emit newForwardSpeed(0.0);
    RobotModule::reset();
    if(xsens->isEnabled()){
        if(xsens->getHealthStatus().isHealthOk()){
            initialHeading = xsens->getHeading();
            ctrAngle = initialHeading;
            emit dataChanged(this);
            this->setHealthToOk();
            timer.start(getSettingsValue("timer").toInt());
            turnTimer.start(getSettingsValue("driveTime").toInt());
        }else{
            this->stopOnXsensError();
        }
    }else{
        this->stop();
    }
}

void Behaviour_XsensFollowing::controlLoop()
{
    if (this->isEnabled() == false){
        logger->info("not enabled - controlloop");
        this->stop();
        return;
    }

    if(!xsens->isEnabled() || !xsens->getHealthStatus().isHealthOk())
    {
        this->stopOnXsensError();
        return;
    }
    float curHeading = xsens->getHeading();
    float curDelta = Angles::deg2deg(ctrAngle - curHeading);
    float ctrAngleSpeed = 0.0;
    float faktor = 1.0;
    if(ctrAngle-curHeading < 0)
        faktor = -1.0;
    if(curDelta > getSettingsValue("delta").toFloat() || curDelta < getSettingsValue("delta").toFloat())
    {
        ctrAngleSpeed = getSettingsValue("kp").toFloat()* faktor * curHeading / ctrAngle;
    }
    addData("angularSpeed",ctrAngleSpeed);
    addData("curDelta", curDelta);
    addData("current heading",curHeading);
    addData("ctrAngle", ctrAngle);
    emit dataChanged(this);
    emit newAngularSpeed(ctrAngleSpeed);
    emit newForwardSpeed(getSettingsValue("ffSpeed").toFloat());
}

void Behaviour_XsensFollowing::turnNinety()
{
    if (this->isEnabled() == false){
        logger->info("not enabled - 90");
        this->stop();
        return;
    }
    logger->info("Turn 90");
    logger->info("ctrAngle %f", ctrAngle);
    if(getSettingsValue("enableTurn").toBool() == true){
        float newHeading = ctrAngle;

        if(getSettingsValue("turnClockwise").toBool() == true){
            newHeading = newHeading + 90.0;
            ctrAngle = Angles::deg2deg(newHeading);
        } else {
            newHeading = newHeading - 90.0;
            ctrAngle = Angles::deg2deg(newHeading);
        }
    }
    logger->info("ctrAngle new %f", ctrAngle);
}

void Behaviour_XsensFollowing::refreshHeading()
{
    //logger->debug("Xsens follow refresh heading");
    if (this->isEnabled() == false){
        logger->info("Not enabled!");
        return;
    }
    if(xsens->isEnabled()){

        this->dataLockerMutex.lock();

        initialHeading = this->xsens->getHeading();

        logger->debug( "initial heading set to %f ", initialHeading );
        addData("initial_heading", initialHeading);
        dataChanged( this );
        this->dataLockerMutex.unlock();

    }
}

void Behaviour_XsensFollowing::stopOnXsensError()
{
    if (!isEnabled()) {
        return;
    }

    logger->info("Xsens follow stop error");
    this->setEnabled(false);
    timer.stop();
    turnTimer.stop();
    setHealthToSick("xsens error");
    setEnabled(false);
    emit newAngularSpeed(0.0);
    emit newForwardSpeed(0.0);
    emit finished(this,false);
}

QList<RobotModule*> Behaviour_XsensFollowing::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(tcl);
    ret.append(xsens);
    return ret;
}

QWidget* Behaviour_XsensFollowing::createView(QWidget* parent)
{
    return new XsensFollowingForm(parent, this);
}

void Behaviour_XsensFollowing::controlEnabledChanged(bool b){
    if(b == false){
        logger->info("No longer enabled!");
        QTimer::singleShot(0, this, SLOT(stop()));
    }
}
<commit_msg><commit_after>#include "behaviour_xsensfollowing.h"
#include <QtGui>
#include <Behaviour_XsensFollowing/xsensfollowingform.h>
#include <Framework/Angles.h>

Behaviour_XsensFollowing::Behaviour_XsensFollowing(QString id, Module_ThrusterControlLoop *tcl, Module_XsensMTi *xsens)
    : RobotBehaviour(id)
{
    this->xsens = xsens;
    this->tcl = tcl;
    turnTimer.moveToThread(this);
    timer.moveToThread(this);

    this->setDefaultValue("timer",30);
    this->setDefaultValue("driveTime",10000);
    this->setDefaultValue("ffSpeed",0.3);
    this->setDefaultValue("kp",0.3);
    this->setDefaultValue("delta",0.3);
}

bool Behaviour_XsensFollowing::isActive()
{
    return isEnabled();
}

void Behaviour_XsensFollowing::init()
{
    logger->info("Xsens Following init");
    setEnabled(false);
    connect(this,SIGNAL(newAngularSpeed(float)),tcl,SLOT(setAngularSpeed(float)));
    connect(this,SIGNAL(newForwardSpeed(float)),tcl,SLOT(setForwardSpeed(float)));
    connect(&timer,SIGNAL(timeout()),this,SLOT(controlLoop()));
    connect(&turnTimer,SIGNAL(timeout()),this,SLOT(turnNinety()));
    connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));
}

void Behaviour_XsensFollowing::startBehaviour()
{
    if (this->isEnabled() == true){
        logger->info("Already enabled/started!");
        return;
    }
    logger->info("Starting Xsens Following");
    this->setEnabled(true);

    initialHeading = xsens->getHeading();
    ctrAngle = initialHeading;

    emit dataChanged(this);

    timer.start(getSettingsValue("timer").toInt());
    turnTimer.start(getSettingsValue("driveTime").toInt());
}

void Behaviour_XsensFollowing::stop()
{
    if(timer.isActive()){
        timer.stop();
    }
    if(turnTimer.isActive()){
        turnTimer.stop();
    }

    if (!isEnabled()) {
        return;
    }

    logger->info("Xsens follow stop");
    this->setEnabled(false);
    setEnabled(false);
    emit newAngularSpeed(0.0);
    emit newForwardSpeed(0.0);
    logger->info("Stop Xsens Following");
    emit finished(this,true);
}

void Behaviour_XsensFollowing::reset()
{
    logger->info("Xsens follow reset");
    if (this->isEnabled() == false){
        logger->info("Not enabled!");
        return;
    }
    timer.stop();
    turnTimer.stop();
    emit newAngularSpeed(0.0);
    emit newForwardSpeed(0.0);
    RobotModule::reset();
    if(xsens->isEnabled()){
        if(xsens->getHealthStatus().isHealthOk()){
            initialHeading = xsens->getHeading();
            ctrAngle = initialHeading;
            emit dataChanged(this);
            this->setHealthToOk();
            timer.start(getSettingsValue("timer").toInt());
            turnTimer.start(getSettingsValue("driveTime").toInt());
        }else{
            this->stopOnXsensError();
        }
    }else{
        this->stop();
    }
}

void Behaviour_XsensFollowing::controlLoop()
{
    if (this->isEnabled() == false){
        logger->info("not enabled - controlloop");
        this->stop();
        return;
    }

    if(!xsens->isEnabled() || !xsens->getHealthStatus().isHealthOk())
    {
        this->stopOnXsensError();
        return;
    }
    float curHeading = xsens->getHeading();
    float curDelta = Angles::deg2deg(ctrAngle - curHeading);
    float ctrAngleSpeed = 0.0;
    float faktor = 1.0;
    if(ctrAngle-curHeading < 0)
        faktor = -1.0;
    if(curDelta > getSettingsValue("delta").toFloat() || curDelta < getSettingsValue("delta").toFloat())
    {
        ctrAngleSpeed = getSettingsValue("kp").toFloat()* faktor * curHeading / ctrAngle;
    }
    addData("angularSpeed",ctrAngleSpeed);
    addData("curDelta", curDelta);
    addData("current heading",curHeading);
    addData("ctrAngle", ctrAngle);
    emit dataChanged(this);
    emit newAngularSpeed(ctrAngleSpeed);
    emit newForwardSpeed(getSettingsValue("ffSpeed").toFloat());
}

void Behaviour_XsensFollowing::turnNinety()
{
    if (this->isEnabled() == false){
        logger->info("not enabled - 90");
        this->stop();
        return;
    }
    logger->info("Turn 90");
    logger->info("ctrAngle", ctrAngle);
    if(getSettingsValue("enableTurn").toBool() == true){
        float newHeading = ctrAngle;

        if(getSettingsValue("turnClockwise").toBool() == true){
            newHeading = newHeading + 90.0;
            ctrAngle = Angles::deg2deg(newHeading);
        } else {
            newHeading = newHeading - 90.0;
            ctrAngle = Angles::deg2deg(newHeading);
        }
    }
    logger->info("ctrAngle new", ctrAngle);
}

void Behaviour_XsensFollowing::refreshHeading()
{
    //logger->debug("Xsens follow refresh heading");
    if (this->isEnabled() == false){
        logger->info("Not enabled!");
        return;
    }
    if(xsens->isEnabled()){

        this->dataLockerMutex.lock();

        initialHeading = this->xsens->getHeading();

        logger->debug( "initial heading set to", initialHeading );
        addData("initial_heading", initialHeading);
        dataChanged( this );
        this->dataLockerMutex.unlock();

    }
}

void Behaviour_XsensFollowing::stopOnXsensError()
{
    if (!isEnabled()) {
        return;
    }

    logger->info("Xsens follow stop error");
    this->setEnabled(false);
    timer.stop();
    turnTimer.stop();
    setHealthToSick("xsens error");
    setEnabled(false);
    emit newAngularSpeed(0.0);
    emit newForwardSpeed(0.0);
    emit finished(this,false);
}

QList<RobotModule*> Behaviour_XsensFollowing::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(tcl);
    ret.append(xsens);
    return ret;
}

QWidget* Behaviour_XsensFollowing::createView(QWidget* parent)
{
    return new XsensFollowingForm(parent, this);
}

void Behaviour_XsensFollowing::controlEnabledChanged(bool b){
    if(b == false){
        logger->info("No longer enabled!");
        QTimer::singleShot(0, this, SLOT(stop()));
    }
}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "opt_status.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "kernel/celltypes.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <set>

using RTLIL::id2cstr;

static CellTypes ct;

static void rmunused_module_cells(RTLIL::Module *module)
{
	SigMap assign_map(module);
	std::set<RTLIL::Cell*> queue, unused;

	SigSet<RTLIL::Cell*> wire2driver;
	for (auto &it : module->cells) {
		RTLIL::Cell *cell = it.second;
		for (auto &it2 : cell->connections) {
			if (!ct.cell_input(cell->type, it2.first)) {
				RTLIL::SigSpec sig = it2.second;
				assign_map.apply(sig);
				wire2driver.insert(sig, cell);
			}
		}
		if (cell->type == "$memwr")
			queue.insert(cell);
		unused.insert(cell);
	}

	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		if (wire->port_output) {
			std::set<RTLIL::Cell*> cell_list;
			RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
			assign_map.apply(sig);
			wire2driver.find(sig, cell_list);
			for (auto cell : cell_list)
				queue.insert(cell);
		}
	}

	while (queue.size() > 0)
	{
		std::set<RTLIL::Cell*> new_queue;
		for (auto cell : queue)
			unused.erase(cell);
		for (auto cell : queue) {
			for (auto &it : cell->connections) {
				if (!ct.cell_output(cell->type, it.first)) {
					std::set<RTLIL::Cell*> cell_list;
					RTLIL::SigSpec sig = it.second;
					assign_map.apply(sig);
					wire2driver.find(sig, cell_list);
					for (auto cell : cell_list) {
						if (unused.count(cell) > 0)
							new_queue.insert(cell);
					}
				}
			}
		}
		queue.swap(new_queue);
	}

	for (auto cell : unused) {
		log("  removing unused `%s' cell `%s'.\n", cell->type.c_str(), cell->name.c_str());
		OPT_DID_SOMETHING = true;
		module->cells.erase(cell->name);
		delete cell;
	}
}

static bool compare_signals(RTLIL::SigSpec &s1, RTLIL::SigSpec &s2)
{
	assert(s1.width == 1);
	assert(s2.width == 1);
	assert(s1.chunks.size() == 1);
	assert(s2.chunks.size() == 1);

	RTLIL::Wire *w1 = s1.chunks[0].wire;
	RTLIL::Wire *w2 = s2.chunks[0].wire;

	if (w1 == NULL || w2 == NULL)
		return w2 == NULL;

	if (w1->port_input != w2->port_input)
		return w2->port_input;

	if (w1->name[0] != w2->name[0])
		return w2->name[0] == '\\';

	if (w1->attributes.size() != w2->attributes.size())
		return w2->attributes.size() > w1->attributes.size();

	return w2->name < w1->name;
}

static bool check_public_name(RTLIL::IdString id)
{
	if (id[0] == '$')
		return false;
#if 0
	if (id.find(".$") == std::string::npos)
		return true;
#endif
	return false;
}

static void rmunused_module_signals(RTLIL::Module *module)
{
	SigMap assign_map(module);
	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		for (int i = 0; i < wire->width; i++) {
			RTLIL::SigSpec s1 = RTLIL::SigSpec(wire, 1, i), s2 = assign_map(s1);
			if (!compare_signals(s1, s2))
				assign_map.add(s1);
		}
	}

	module->connections.clear();

	SigPool used_signals;
	SigPool used_signals_nodrivers;
	for (auto &it : module->cells) {
		RTLIL::Cell *cell = it.second;
		for (auto &it2 : cell->connections) {
			assign_map.apply(it2.second);
			used_signals.add(it2.second);
			if (!ct.cell_output(cell->type, it2.first))
				used_signals_nodrivers.add(it2.second);
		}
	}
	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		if (wire->port_id > 0) {
			RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
			assign_map.apply(sig);
			used_signals.add(sig);
			if (!wire->port_input)
				used_signals_nodrivers.add(sig);
		}
	}

	std::vector<RTLIL::Wire*> del_wires;
	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		if (check_public_name(wire->name)) {
			RTLIL::SigSpec s1 = RTLIL::SigSpec(wire), s2 = s1;
			assign_map.apply(s2);
			if (!used_signals.check_any(s2) && wire->port_id == 0) {
				log("  removing unused non-port wire %s.\n", wire->name.c_str());
				del_wires.push_back(wire);
			} else {
				s1.expand();
				s2.expand();
				assert(s1.chunks.size() == s2.chunks.size());
				RTLIL::SigSig new_conn;
				for (size_t i = 0; i < s1.chunks.size(); i++)
					if (s1.chunks[i] != s2.chunks[i]) {
						new_conn.first.append(s1.chunks[i]);
						new_conn.second.append(s2.chunks[i]);
					}
				if (new_conn.first.width > 0) {
					new_conn.first.optimize();
					new_conn.second.optimize();
					module->connections.push_back(new_conn);
				}
			}
		} else {
			if (!used_signals.check_any(RTLIL::SigSpec(wire)))
				del_wires.push_back(wire);
		}
		RTLIL::SigSpec sig = assign_map(RTLIL::SigSpec(wire));
		if (!used_signals_nodrivers.check_any(sig)) {
			std::string unused_bits;
			sig.expand();
			for (size_t i = 0; i < sig.chunks.size(); i++) {
				if (sig.chunks[i].wire == NULL)
					continue;
				if (!used_signals_nodrivers.check_any(sig)) {
					if (!unused_bits.empty())
						unused_bits += " ";
					unused_bits += stringf("%zd", i);
				}
			}
			if (unused_bits.empty() || wire->port_id != 0)
				wire->attributes.erase("\\unused_bits");
			else
				wire->attributes["\\unused_bits"] = RTLIL::Const(unused_bits);
		} else {
			wire->attributes.erase("\\unused_bits");
		}
	}

	for (auto wire : del_wires) {
		module->wires.erase(wire->name);
		delete wire;
	}

	if (del_wires.size() > 0)
		log("  removed %zd unused temporary wires.\n", del_wires.size());
}

static void rmunused_module(RTLIL::Module *module)
{
	log("Finding unused cells or wires in module %s..\n", module->name.c_str());

	rmunused_module_cells(module);
	rmunused_module_signals(module);
}

struct OptRmUnusedPass : public Pass {
	OptRmUnusedPass() : Pass("opt_rmunused", "remove unused cells and wires") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    opt_rmunused [selection]\n");
		log("\n");
		log("This pass identifies wires and cells that are unused and removes them. Other\n");
		log("often remove cells but leave the wires in the design or reconnect the wires\n");
		log("but leave the old cells in the design. This pass can be used to clean up after\n");
		log("the passes that do the actual work.\n");
		log("\n");
		log("This pass only operates on completely selected modules without processes.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		log_header("Executing OPT_RMUNUSED pass (remove unused cells and wires).\n");
		log_push();

		extra_args(args, 1, design);

		ct.setup_internals();
		ct.setup_internals_mem();
		ct.setup_stdcells();
		ct.setup_stdcells_mem();

		for (auto &mod_it : design->modules) {
			if (!design->selected_whole_module(mod_it.first)) {
				if (design->selected(mod_it.second))
					log("Skipping module %s as it is only partially selected.\n", id2cstr(mod_it.second->name));
				continue;
			}
			if (mod_it.second->processes.size() > 0) {
				log("Skipping module %s as it contains processes.\n", mod_it.second->name.c_str());
			} else {
				rmunused_module(mod_it.second);
			}
		}

		ct.clear();
		log_pop();
	}
} OptRmUnusedPass;

<commit_msg>Fixed detection of public wires in opt_rmunused<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "opt_status.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "kernel/celltypes.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <set>

using RTLIL::id2cstr;

static CellTypes ct;

static void rmunused_module_cells(RTLIL::Module *module)
{
	SigMap assign_map(module);
	std::set<RTLIL::Cell*> queue, unused;

	SigSet<RTLIL::Cell*> wire2driver;
	for (auto &it : module->cells) {
		RTLIL::Cell *cell = it.second;
		for (auto &it2 : cell->connections) {
			if (!ct.cell_input(cell->type, it2.first)) {
				RTLIL::SigSpec sig = it2.second;
				assign_map.apply(sig);
				wire2driver.insert(sig, cell);
			}
		}
		if (cell->type == "$memwr")
			queue.insert(cell);
		unused.insert(cell);
	}

	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		if (wire->port_output) {
			std::set<RTLIL::Cell*> cell_list;
			RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
			assign_map.apply(sig);
			wire2driver.find(sig, cell_list);
			for (auto cell : cell_list)
				queue.insert(cell);
		}
	}

	while (queue.size() > 0)
	{
		std::set<RTLIL::Cell*> new_queue;
		for (auto cell : queue)
			unused.erase(cell);
		for (auto cell : queue) {
			for (auto &it : cell->connections) {
				if (!ct.cell_output(cell->type, it.first)) {
					std::set<RTLIL::Cell*> cell_list;
					RTLIL::SigSpec sig = it.second;
					assign_map.apply(sig);
					wire2driver.find(sig, cell_list);
					for (auto cell : cell_list) {
						if (unused.count(cell) > 0)
							new_queue.insert(cell);
					}
				}
			}
		}
		queue.swap(new_queue);
	}

	for (auto cell : unused) {
		log("  removing unused `%s' cell `%s'.\n", cell->type.c_str(), cell->name.c_str());
		OPT_DID_SOMETHING = true;
		module->cells.erase(cell->name);
		delete cell;
	}
}

static bool compare_signals(RTLIL::SigSpec &s1, RTLIL::SigSpec &s2)
{
	assert(s1.width == 1);
	assert(s2.width == 1);
	assert(s1.chunks.size() == 1);
	assert(s2.chunks.size() == 1);

	RTLIL::Wire *w1 = s1.chunks[0].wire;
	RTLIL::Wire *w2 = s2.chunks[0].wire;

	if (w1 == NULL || w2 == NULL)
		return w2 == NULL;

	if (w1->port_input != w2->port_input)
		return w2->port_input;

	if (w1->name[0] != w2->name[0])
		return w2->name[0] == '\\';

	if (w1->attributes.size() != w2->attributes.size())
		return w2->attributes.size() > w1->attributes.size();

	return w2->name < w1->name;
}

static bool check_public_name(RTLIL::IdString id)
{
	if (id[0] == '$')
		return false;
#if 0
	if (id.find(".$") != std::string::npos)
		return false;
#endif
	return true;
}

static void rmunused_module_signals(RTLIL::Module *module)
{
	SigMap assign_map(module);
	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		for (int i = 0; i < wire->width; i++) {
			RTLIL::SigSpec s1 = RTLIL::SigSpec(wire, 1, i), s2 = assign_map(s1);
			if (!compare_signals(s1, s2))
				assign_map.add(s1);
		}
	}

	module->connections.clear();

	SigPool used_signals;
	SigPool used_signals_nodrivers;
	for (auto &it : module->cells) {
		RTLIL::Cell *cell = it.second;
		for (auto &it2 : cell->connections) {
			assign_map.apply(it2.second);
			used_signals.add(it2.second);
			if (!ct.cell_output(cell->type, it2.first))
				used_signals_nodrivers.add(it2.second);
		}
	}
	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		if (wire->port_id > 0) {
			RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
			assign_map.apply(sig);
			used_signals.add(sig);
			if (!wire->port_input)
				used_signals_nodrivers.add(sig);
		}
	}

	std::vector<RTLIL::Wire*> del_wires;
	for (auto &it : module->wires) {
		RTLIL::Wire *wire = it.second;
		if (check_public_name(wire->name)) {
			RTLIL::SigSpec s1 = RTLIL::SigSpec(wire), s2 = s1;
			assign_map.apply(s2);
			if (!used_signals.check_any(s2) && wire->port_id == 0) {
				log("  removing unused non-port wire %s.\n", wire->name.c_str());
				del_wires.push_back(wire);
			} else {
				s1.expand();
				s2.expand();
				assert(s1.chunks.size() == s2.chunks.size());
				RTLIL::SigSig new_conn;
				for (size_t i = 0; i < s1.chunks.size(); i++)
					if (s1.chunks[i] != s2.chunks[i]) {
						new_conn.first.append(s1.chunks[i]);
						new_conn.second.append(s2.chunks[i]);
					}
				if (new_conn.first.width > 0) {
					new_conn.first.optimize();
					new_conn.second.optimize();
					module->connections.push_back(new_conn);
				}
			}
		} else {
			if (!used_signals.check_any(RTLIL::SigSpec(wire)))
				del_wires.push_back(wire);
		}
		RTLIL::SigSpec sig = assign_map(RTLIL::SigSpec(wire));
		if (!used_signals_nodrivers.check_any(sig)) {
			std::string unused_bits;
			sig.expand();
			for (size_t i = 0; i < sig.chunks.size(); i++) {
				if (sig.chunks[i].wire == NULL)
					continue;
				if (!used_signals_nodrivers.check_any(sig)) {
					if (!unused_bits.empty())
						unused_bits += " ";
					unused_bits += stringf("%zd", i);
				}
			}
			if (unused_bits.empty() || wire->port_id != 0)
				wire->attributes.erase("\\unused_bits");
			else
				wire->attributes["\\unused_bits"] = RTLIL::Const(unused_bits);
		} else {
			wire->attributes.erase("\\unused_bits");
		}
	}

	for (auto wire : del_wires) {
		module->wires.erase(wire->name);
		delete wire;
	}

	if (del_wires.size() > 0)
		log("  removed %zd unused temporary wires.\n", del_wires.size());
}

static void rmunused_module(RTLIL::Module *module)
{
	log("Finding unused cells or wires in module %s..\n", module->name.c_str());

	rmunused_module_cells(module);
	rmunused_module_signals(module);
}

struct OptRmUnusedPass : public Pass {
	OptRmUnusedPass() : Pass("opt_rmunused", "remove unused cells and wires") { }
	virtual void help()
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    opt_rmunused [selection]\n");
		log("\n");
		log("This pass identifies wires and cells that are unused and removes them. Other\n");
		log("often remove cells but leave the wires in the design or reconnect the wires\n");
		log("but leave the old cells in the design. This pass can be used to clean up after\n");
		log("the passes that do the actual work.\n");
		log("\n");
		log("This pass only operates on completely selected modules without processes.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		log_header("Executing OPT_RMUNUSED pass (remove unused cells and wires).\n");
		log_push();

		extra_args(args, 1, design);

		ct.setup_internals();
		ct.setup_internals_mem();
		ct.setup_stdcells();
		ct.setup_stdcells_mem();

		for (auto &mod_it : design->modules) {
			if (!design->selected_whole_module(mod_it.first)) {
				if (design->selected(mod_it.second))
					log("Skipping module %s as it is only partially selected.\n", id2cstr(mod_it.second->name));
				continue;
			}
			if (mod_it.second->processes.size() > 0) {
				log("Skipping module %s as it contains processes.\n", mod_it.second->name.c_str());
			} else {
				rmunused_module(mod_it.second);
			}
		}

		ct.clear();
		log_pop();
	}
} OptRmUnusedPass;

<|endoftext|>