Exemple #1
0
/*
 * Decodes map data from a <data> node
 */
static void decode_layer_data(xmlNode *data_node, ALLEGRO_MAP_LAYER *layer)
{
	char *str = g_strstrip((char *)data_node->children->content);
	int datalen = layer->width * layer->height;
	layer->data = (char *)calloc(datalen, sizeof(char));

	char *encoding = get_xml_attribute(data_node, "encoding");
	if (!encoding) {
		int i = 0;
		GSList *tiles = get_children_for_name(data_node, "tile");
		GSList *tile_item = tiles;
		while (tile_item) {
			xmlNode *tile_node = (xmlNode*)tile_item->data;
			tile_item = g_slist_next(tile_item);
			char *gid = get_xml_attribute(tile_node, "gid");
			layer->data[i] = atoi(gid);
			i++;
		}

		g_slist_free(tiles);
	}
	else if (!strcmp(encoding, "base64")) {
		// decompress
		gsize rawlen;
		unsigned char *rawdata = g_base64_decode(str, &rawlen);

		// check the compression
		char *compression = get_xml_attribute(data_node, "compression");
		if (compression != NULL) {
			if (strcmp(compression, "zlib") && strcmp(compression, "gzip")) {
				fprintf(stderr, "Error: unknown compression format '%s'\n", compression);
				return;
			}

			// set up files used by zlib to decompress the data
			ALLEGRO_PATH *srcpath;
			ALLEGRO_FILE *datasrc = al_make_temp_file("XXXXXX", &srcpath);
			al_fwrite(datasrc, rawdata, rawlen);
			al_fseek(datasrc, 0, ALLEGRO_SEEK_SET);
			//al_fclose(datasrc);
			//datasrc = al_fopen(al_path_cstr(srcpath, ALLEGRO_NATIVE_PATH_SEP), "rb");
			ALLEGRO_FILE *datadest = al_make_temp_file("XXXXXX", NULL);

			// decompress and print an error if it failed
			int status = inf(datasrc, datadest);
			if (status)
				zerr(status);

			// flush data and get the file length
			al_fflush(datadest);
			int len = al_fsize(datadest);

			// read in the file
			al_fseek(datadest, 0, ALLEGRO_SEEK_SET);
			char *data = (char *)calloc(len, sizeof(char));
			if (al_fread(datadest, data, len) != len) {
				fprintf(stderr, "Error: failed to read in map data\n");
				return;
			}

			// every tile id takes 4 bytes
			int i;
			for (i = 0; i<len; i += 4) {
				int tileid = 0;
				tileid |= data[i];
				tileid |= data[i+1] << 8;
				tileid |= data[i+2] << 16;
				tileid |= data[i+3] << 24;

				layer->data[i/4] = tileid;
			}
			/*	printf("layer dimensions: %dx%d, data length = %d\n",
						layer->width, layer->height, len); */

			al_destroy_path(srcpath);
			al_fclose(datasrc);
			al_fclose(datadest);
			al_free(data);
		}
		else {
			// TODO: verify that this still works
			int i;
			for (i = 0; i<rawlen; i += 4) {
				int tileid = 0;
				tileid |= rawdata[i];
				tileid |= rawdata[i+1] << 8;
				tileid |= rawdata[i+2] << 16;
				tileid |= rawdata[i+3] << 24;

				layer->data[i/4] = tileid;
			}
		}

		g_free(rawdata);
	}
	else if (!strcmp(encoding, "csv")) {
		int i;
		for (i = 0; i<datalen; i++) {
			char *id = strtok((i == 0 ? str : NULL), ",");
			layer->data[i] = atoi(id);
		}
	}
	else {
		fprintf(stderr, "Error: unknown encoding format '%s'\n", encoding);
	}
}
Exemple #2
0
/* cover all inflate() header and trailer cases and code after inflate() */
local void cover_wrap(void)
{
    int ret;
    z_stream strm, copy;
    unsigned char dict[257];

    ret = inflate(Z_NULL, 0);                   assert(ret == Z_STREAM_ERROR);
    ret = inflateEnd(Z_NULL);                   assert(ret == Z_STREAM_ERROR);
    ret = inflateCopy(Z_NULL, Z_NULL);          assert(ret == Z_STREAM_ERROR);
    fputs("inflate bad parameters\n", stderr);

    inf("1f 8b 0 0", "bad gzip method", 0, 31, 0, Z_DATA_ERROR);
    inf("1f 8b 8 80", "bad gzip flags", 0, 31, 0, Z_DATA_ERROR);
    inf("77 85", "bad zlib method", 0, 15, 0, Z_DATA_ERROR);
    inf("8 99", "set window size from header", 0, 0, 0, Z_OK);
    inf("78 9c", "bad zlib window size", 0, 8, 0, Z_DATA_ERROR);
    inf("78 9c 63 0 0 0 1 0 1", "check adler32", 0, 15, 1, Z_STREAM_END);
    inf("1f 8b 8 1e 0 0 0 0 0 0 1 0 0 0 0 0 0", "bad header crc", 0, 47, 1,
        Z_DATA_ERROR);
    inf("1f 8b 8 2 0 0 0 0 0 0 1d 26 3 0 0 0 0 0 0 0 0 0", "check gzip length",
        0, 47, 0, Z_STREAM_END);
    inf("78 90", "bad zlib header check", 0, 47, 0, Z_DATA_ERROR);
    inf("8 b8 0 0 0 1", "need dictionary", 0, 8, 0, Z_NEED_DICT);
    inf("78 9c 63 0", "compute adler32", 0, 15, 1, Z_OK);

    mem_setup(&strm);
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    ret = inflateInit2(&strm, -8);
    strm.avail_in = 2;
    strm.next_in = (void *)"\x63";
    strm.avail_out = 1;
    strm.next_out = (void *)&ret;
    mem_limit(&strm, 1);
    ret = inflate(&strm, Z_NO_FLUSH);           assert(ret == Z_MEM_ERROR);
    ret = inflate(&strm, Z_NO_FLUSH);           assert(ret == Z_MEM_ERROR);
    mem_limit(&strm, 0);
    memset(dict, 0, 257);
    ret = inflateSetDictionary(&strm, dict, 257);
                                                assert(ret == Z_OK);
    mem_limit(&strm, (sizeof(struct inflate_state) << 1) + 256);
    ret = inflatePrime(&strm, 16, 0);           assert(ret == Z_OK);
    strm.avail_in = 2;
    strm.next_in = (void *)"\x80";
    ret = inflateSync(&strm);                   assert(ret == Z_DATA_ERROR);
    ret = inflate(&strm, Z_NO_FLUSH);           assert(ret == Z_STREAM_ERROR);
    strm.avail_in = 4;
    strm.next_in = (void *)"\0\0\xff\xff";
    ret = inflateSync(&strm);                   assert(ret == Z_OK);
    (void)inflateSyncPoint(&strm);
    ret = inflateCopy(&copy, &strm);            assert(ret == Z_MEM_ERROR);
    mem_limit(&strm, 0);
    ret = inflateUndermine(&strm, 1);           assert(ret == Z_DATA_ERROR);
    (void)inflateMark(&strm);
    ret = inflateEnd(&strm);                    assert(ret == Z_OK);
    mem_done(&strm, "miscellaneous, force memory errors");
}
Exemple #3
0
void FMPanel::openSelected()
{
    switch( tab->currentIndex() )
    {
    case 0://this is the directory list
        {
        QStringList list = dirList->selectedFiles();
        // for some reason the first .. are never returned in the list
        // TODO: fix this
        if( list.count() == 0 )
        {
            QDir dir(currentDir);
            dir.cdUp();
            currentFile.clear();
            currentDir.clear();
            currentDir.append( dir.absolutePath() );
            dirList->setRootPath( currentDir );
            return;
        }
        if( list.at(0).isEmpty() || list.at(0).at(0)=='/' )
        {
            return;
        }
        if( list.at(0).at(0)=='.' && list.at(0).at(1)=='.' )
        {
            QDir dir(currentDir);
            dir.cdUp();
            currentFile.clear();
            currentDir.clear();
            currentDir.append( dir.absolutePath() );
            dirList->setRootPath( currentDir );
            return;
        }
        QString selectedFile( currentDir );
        selectedFile.append("/");
        selectedFile.append( list.at(0) );
        QFileInfo inf( selectedFile ) ;
        //isAbsolute()
        //isBundle()
        if( inf.isDir() )
        {
            //mainW->startAnimation();
            currentFile.clear();
            //TODO check the size
            currentDir.clear();
            currentDir.append( inf.absoluteFilePath() );
            dirList->setRootPath( currentDir );
            return;
        }
        if( inf.isExecutable() )
        {
            QProcess::startDetached( inf.absoluteFilePath() );
        }
        if( inf.isFile() )
        {
            QString url("file:///");
            url.append( inf.filePath() );
            //qDebug()<<url;
            QDesktopServices::openUrl( url );
        }
        currentDir.clear();
        currentDir.append( inf.absolutePath() );
        dirList->setRootPath( currentDir );
        break;
        }
    case 1://bookmark tab
        {
        break;
        }
    case 2://found tab
        {
        break;
        }
    default:
        {
        }
    }
}
Exemple #4
0
/* Return 0 if the target directory is suitable.  */
static int
check_target_dir (int force)
{
  int count = 0;

#if _WIN32
  {
    char *fname;
    HANDLE hd = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAA fi;

    fname = xmalloc (strlen (target_dir) + 2 + 2 + 1);
    if (!strcmp (target_dir, "/"))
      strcpy (fname, "/*"); /* Trailing slash is not allowed.  */
    else if (!strcmp (target_dir, "."))
      strcpy (fname, "*");
    else if (*target_dir && target_dir[strlen (target_dir)-1] == '/')
      {
        strcpy (fname, target_dir);
        strcat (fname, "*");
      }
    else if (*target_dir && target_dir[strlen (target_dir)-1] != '*')
      {
        strcpy (fname, target_dir);
        strcat (fname, "/*");
      }
    else
      strcpy (fname, target_dir);

    inf ("finding files in '%s'", fname);

    unfix_backslashes (fname);
    hd = FindFirstFileA (fname, &fi);
    if (hd == INVALID_HANDLE_VALUE)
      {
        err ("error reading target directory '%s': %s",
             target_dir, w32_strerror (-1));
        free (fname);
        return 1;
      }
    do
      {
        if (!strcmp (fi.cFileName, "." ) || !strcmp (fi.cFileName, ".."))
          ;
        else
          count++;
      }
    while (FindNextFileA (hd, &fi));
    FindClose (hd);
    free (fname);
  }
#else /*!_WIN32*/
  {
    DIR *dir;
    struct dirent *de;

    dir = opendir (target_dir);
    if (!dir)
      {
        err ("error reading read target directory '%s': %s",
             target_dir, strerror (errno));
        return 1;
      }
    while ((de = readdir (dir)))
      {
        if (!strcmp (de->d_name, "." ) || !strcmp (de->d_name, ".."))
          continue; /* Skip self and parent dir entry.  */
        count++;
      }
    closedir (dir);
  }
#endif /*!_WIN32*/

  if (count)
    inf ("number of files in target directory: %d", count);
  if (count)
    {
      err ("target directory '%s' is not empty%s",
           target_dir, force? " - continuing anyway":"");
      if (!force)
        return 1;
    }

  return 0;
}
Exemple #5
0
/* Copy files which contain one '*' wildcard. */
static int
wildcard_copy_file (const char *name)
{
  int res = 0;
  char *fname;
  size_t srcpos;

  if (verbose > 1)
    inf ("globing '%s'", name);

  fname = make_sourcename (name);
  srcpos = strlen (fname) - strlen (name);

#if _WIN32
  {
    HANDLE hd = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATAA fi;
    char *p, *tail;
    char *buffer = NULL;

    p = strchr (fname, '*');
    assert (p);
    tail = strchr (p, '/');
    if (tail)
      *tail++ = 0;

    unfix_backslashes (fname);
    hd = FindFirstFileA (fname, &fi);
    fix_backslashes (fname);

    p = strrchr (fname, '/');
    if (p)
      *p = 0;

    if (hd != INVALID_HANDLE_VALUE)
      {
        do
          {
            if (!strcmp (fi.cFileName, "." ) || !strcmp (fi.cFileName, ".."))
              ;
            else
              {
                free (buffer);
                buffer = xmalloc (strlen (fname) + 1
                                  + strlen (fi.cFileName) + 1
                                  + (tail? strlen (tail):0) + 1);
                strcpy (buffer, fname);
                strcat (buffer, "/");
                strcat (buffer, fi.cFileName);
                if (tail)
                  {
                    strcat (buffer, "/");
                    strcat (buffer, tail);
                  }
                if (!access (buffer, F_OK))
                  if (copy_file (buffer + srcpos, NULL))
                    {
                      res = 1;
                      goto leave;
                    }

              }
        }
        while (FindNextFileA (hd, &fi));
      leave:
        free (buffer);
        FindClose (hd);
      }
  }
#endif /*_WIN32*/

  free (fname);
  return res;
}
Exemple #6
0
void ObjectBase::onSimulation(float timeStep) {
    Point2 delta = m_velocityRelativeToParent * timeStep;

    if (! m_collidesWithCells || (delta.squaredLength() < 1e-6f)) {
        // Case without collisions
        m_frameRelativeToJoint.translation += delta;

    } else {
        if (! isRoot()) {
            report(format("ObjectBase::collidesWithCells must be false for non-root objects. (%d)", m_id.c_str()), ReportLevel::ERROR);
            m_frameRelativeToJoint.translation += delta;
            return;
        }
        // Collision case

        const float speed = m_velocityRelativeToParent.length();

        // Algorithm: Find all tiles within the maximum extent of the object's
        // movement (i.e., ignoring direction) plus its radius. Reduce to
        // the edges (line segments) of non-traversable tiles.

        // A static object with default radius can hit four tiles;
        // one that is moving might typically hit nine, and there is no
        // upper bound.
        Map::SmallEdgeArray edgesInDisk;

        const Frame2D& frame = this->frame();
        m_world.map->getEdgesInDisk(frame.translation, delta.length() + m_collisionRadius, m_elevation, LayerIndex(1), edgesInDisk);

        // Transform the edges into the parent's object space
        const Frame2D& parentFrame = (isRoot() ? Frame2D() : m_world.objectTable.valueFromKey(m_parent)->frame());
        for (int e = 0; e < edgesInDisk.size(); ++e) {
            LineSegment2D& edge = edgesInDisk[e];
            debugDrawEdgeArray.append(edge); // TODO: Remove
            edge = parentFrame.bringFromParentSpace(edge);
        }

        const int maxIterations = 20;

        // Check for collisions with the map edges, adjusting velocity into the unblocked direction each time
        int iterations;
        for (iterations = 0; (iterations < maxIterations) && (timeStep > 1e-6); ++iterations) {

            // Find the first collision
            float firstCollisionTime = finf();
            Point2 firstCollisionLocation;
            for (int e = 0; e < edgesInDisk.size(); ++e) {
                const LineSegment2D& edge = edgesInDisk[e];

                // Recall that everything is in body space, now
                Point2 collisionLocation;
                const float collisionTime = movingDiskFixedLineSegmentCollisionTime(m_frameRelativeToJoint.translation, m_collisionRadius, m_velocityRelativeToParent, edge, collisionLocation);

                if (collisionTime < inf()) {
                    debugDrawPointArray.append(collisionLocation);
                }

                if (collisionTime < firstCollisionTime) {
                    firstCollisionTime     = collisionTime;
                    firstCollisionLocation = collisionLocation;
                }
            }

            // Resolve the collision if it happens before the end of the time step
            if (firstCollisionTime < timeStep) {
                // Advance to just before the collision
                firstCollisionTime =  max(firstCollisionTime - 1e-5f, 0.0f);
                m_frameRelativeToJoint.translation += m_velocityRelativeToParent * firstCollisionTime;
                timeStep -= firstCollisionTime;

                const Vector2 normal = (m_frameRelativeToJoint.translation - firstCollisionLocation).directionOrZero();

                // Alter velocity at the collision by removing the component of the velocity along the collision normal
                m_velocityRelativeToParent -= normal * min(normal.dot(m_velocityRelativeToParent), 0.0f);

                // Restore full speed, deflecting movement
                m_velocityRelativeToParent = m_velocityRelativeToParent.directionOrZero() * speed;

                if (m_velocityRelativeToParent.squaredLength() < 1e-6f) {
                    // Unable to proceed with movement because there is no velocity left
                    timeStep = 0;
                }
            } else {
                // Go to the end of the time step
                firstCollisionTime = timeStep;
                m_frameRelativeToJoint.translation += m_velocityRelativeToParent * timeStep;
                timeStep = 0;
            }
        }

        if (iterations == maxIterations) {
            report("Hit maximum number of iterations in ObjectBase::onSimulation collision resolution.", ReportLevel::WARNING);
        }
    }
}
ControlDevice GetFileControlDevice(const char* filename, const std::string& name) {
  std::ifstream *inf(new std::ifstream(filename));
  REQUIRE_ALWAYS(inf->is_open(), "could not open file \"" << filename << "\"!",1);
  boost::shared_ptr<std::istream> infile(inf);
  return ControlDevice(boost::shared_ptr<control_device_impl>(new istream_control_device_impl(infile, name)));
}
bool CompressFileToBlob(const char* infile, const char* outfile, u32 sub_type,
						int block_size, CompressCB callback, void* arg)
{
	bool scrubbing = false;

	if (IsCompressedBlob(infile))
	{
		PanicAlertT("%s is already compressed! Cannot compress it further.", infile);
		return false;
	}

	if (sub_type == 1)
	{
		if (!DiscScrubber::SetupScrub(infile, block_size))
		{
			PanicAlertT("%s failed to be scrubbed. Probably the image is corrupt.", infile);
			return false;
		}

		scrubbing = true;
	}

	File::IOFile inf(infile, "rb");
	File::IOFile f(outfile, "wb");

	if (!f || !inf)
		return false;

	callback("Files opened, ready to compress.", 0, arg);

	CompressedBlobHeader header;
	header.magic_cookie = kBlobCookie;
	header.sub_type   = sub_type;
	header.block_size = block_size;
	header.data_size  = File::GetSize(infile);

	// round upwards!
	header.num_blocks = (u32)((header.data_size + (block_size - 1)) / block_size);

	u64* offsets = new u64[header.num_blocks];
	u32* hashes = new u32[header.num_blocks];
	u8* out_buf = new u8[block_size];
	u8* in_buf = new u8[block_size];

	// seek past the header (we will write it at the end)
	f.Seek(sizeof(CompressedBlobHeader), SEEK_CUR);
	// seek past the offset and hash tables (we will write them at the end)
	f.Seek((sizeof(u64) + sizeof(u32)) * header.num_blocks, SEEK_CUR);

	// Now we are ready to write compressed data!
	u64 position = 0;
	int num_compressed = 0;
	int num_stored = 0;
	int progress_monitor = max<int>(1, header.num_blocks / 1000);

	for (u32 i = 0; i < header.num_blocks; i++)
	{
		if (i % progress_monitor == 0)
		{
			const u64 inpos = inf.Tell();
			int ratio = 0;
			if (inpos != 0)
				ratio = (int)(100 * position / inpos);
			char temp[512];
			sprintf(temp, "%i of %i blocks. Compression ratio %i%%", i, header.num_blocks, ratio);
			callback(temp, (float)i / (float)header.num_blocks, arg);
		}

		offsets[i] = position;
		// u64 start = i * header.block_size;
		// u64 size = header.block_size;
		std::fill(in_buf, in_buf + header.block_size, 0);
		if (scrubbing)
			DiscScrubber::GetNextBlock(inf.GetHandle(), in_buf);
		else
			inf.ReadBytes(in_buf, header.block_size);
		z_stream z;
		memset(&z, 0, sizeof(z));
		z.zalloc = Z_NULL;
		z.zfree  = Z_NULL;
		z.opaque = Z_NULL;
		z.next_in   = in_buf;
		z.avail_in  = header.block_size;
		z.next_out  = out_buf;
		z.avail_out = block_size;
		int retval = deflateInit(&z, 9);

		if (retval != Z_OK)
		{
			ERROR_LOG(DISCIO, "Deflate failed");
			goto cleanup;
		}

		int status = deflate(&z, Z_FINISH);
		int comp_size = block_size - z.avail_out;
		if ((status != Z_STREAM_END) || (z.avail_out < 10))
		{
			//PanicAlert("%i %i Store %i", i*block_size, position, comp_size);
			// let's store uncompressed
			offsets[i] |= 0x8000000000000000ULL;
			f.WriteBytes(in_buf, block_size);
			hashes[i] = HashAdler32(in_buf, block_size);
			position += block_size;
			num_stored++;
		}
		else
		{
			// let's store compressed
			//PanicAlert("Comp %i to %i", block_size, comp_size);
			f.WriteBytes(out_buf, comp_size);
			hashes[i] = HashAdler32(out_buf, comp_size);
			position += comp_size;
			num_compressed++;
		}

		deflateEnd(&z);
	}

	header.compressed_data_size = position;

	// Okay, go back and fill in headers
	f.Seek(0, SEEK_SET);
	f.WriteArray(&header, 1);
	f.WriteArray(offsets, header.num_blocks);
	f.WriteArray(hashes, header.num_blocks);

cleanup:
	// Cleanup
	delete[] in_buf;
	delete[] out_buf;
	delete[] offsets;
	delete[] hashes;

	DiscScrubber::Cleanup();
	callback("Done compressing disc image.", 1.0f, arg);
	return true;
}
Exemple #9
0
int main(int argc, char ** argv)
{

  if (argc != 3) {
    std::cout << "Usage: " << argv[0] << " <no. of cones> <input filename>" << std::endl;
    return 1;
  }
  unsigned int k = atoi(argv[1]);
  if (k<2) {
    std::cout << "The number of cones should be larger than 1!" << std::endl;
    return 1;
  }
  // open the file containing the vertex list
  std::ifstream inf(argv[2]);
  if (!inf) {
    std::cout << "Cannot open file " << argv[1] << "!" << std::endl;
    return 1;
  }

  // iterators for reading the vertex list file
  std::istream_iterator< Point_2 > input_begin( inf );
  std::istream_iterator< Point_2 > input_end;

  // initialize the functor
  // If the initial direction is omitted, the x-axis will be used
  CGAL::Construct_theta_graph_2<Kernel, Graph> theta(k);
  // create an adjacency_list object
  Graph g;
  // construct the theta graph on the vertex list
  theta(input_begin, input_end, g);

  // select a source vertex for dijkstra's algorithm
  boost::graph_traits<Graph>::vertex_descriptor v0;
  v0 = vertex(0, g);
  std::cout << "The source vertex is: " << g[v0] << std::endl;

  std::cout << "The index of source vertex is: " << v0 << std::endl;

  // calculating edge length in Euclidean distance and store them in the edge property
  boost::graph_traits<Graph>::edge_iterator ei, ei_end;
  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
    boost::graph_traits<Graph>::edge_descriptor e = *ei;
    boost::graph_traits<Graph>::vertex_descriptor  u = source(e, g);
    boost::graph_traits<Graph>::vertex_descriptor  v = target(e, g);
    const Point_2& pu = g[u];
    const Point_2& pv = g[v];

    double dist = CGAL::sqrt( CGAL::to_double(CGAL::squared_distance(pu,pv)) );
    g[e].euclidean_length = dist;
    std::cout << "Edge (" << g[u] << ", " << g[v] << "): " << dist << std::endl;
  }

  // calculating the distances from v0 to other vertices
  boost::graph_traits<Graph>::vertices_size_type n = num_vertices(g);
  // vector for storing the results
  std::vector<double> distances(n);
  // Calling the Dijkstra's algorithm implementation from boost.
  boost::dijkstra_shortest_paths(g,
                                 v0,
                                 boost::weight_map(get(&Edge_property::euclidean_length, g)).
                                 distance_map(CGAL::make_property_map(distances)) );

  std::cout << "distances are:" << std::endl;
  for (unsigned int i=0; i < n; ++i) {
    std::cout << "distances[" << i << "] = " << distances[i] << ", (x,y)=" << g[vertex(i, g)];
    std::cout << " at Vertex " << i << std::endl;
  }

  return 0;
}
Exemple #10
0
/* compress or decompress from stdin to stdout */
int main(int argc, char **argv)
{
    int ret;
    unsigned char *filename;
    unsigned char out_filename[255];
    FILE *in,*devnull,*out;
    struct stat s;
    unsigned long f_size;
    unsigned long offset=0;

    // check args
    if (argc!=2)
    {
        printf("invalid arguments\n");
        printf(" ./ruf_extract <filename.RUF>\n\n");
        return(-1);
    }
    else
    {
        filename=argv[1];
    }


    header();

    /* check size of firmware file */
    if (stat(filename, &s) == -1)
    {
        printf(" error opening file: %s\n\n",filename);
        return(-1);
    }

    f_size=s.st_size;
    printf(" Firmware size: %ld bytes\n\n",f_size);

    /* open firmware file */
    in=fopen(filename, "r");
    /* open /dev/null file */
    devnull=fopen("/dev/null", "w");

    /* avoid end-of-line conversions */
    SET_BINARY_MODE(in);
    SET_BINARY_MODE(stdout);


    printf(" Scanning for inflated data ...\n\n");
    for (offset=0; offset<f_size; offset++)
    {
        fseek(in, offset, SEEK_SET);
        ret = inf(in, devnull);
        if (ret == Z_OK)
        {
            printf(" Found data at offset: %X\n",offset);
            /* now do it once more, but this time we redirect it to a real file */
            sprintf(out_filename,"chunk_%X.dat",offset);
            out=fopen(out_filename,"wb");
            if (!out)
            {
                printf("\n Error: unable to open %s for writing\n\n",out_filename);
            }
            else
            {
                printf("   > inflating chunk to: %s ",out_filename);
                fseek(in, offset, SEEK_SET);
                ret=inf(in, out);
                if (ret == Z_OK)
                    printf(" [OK]\n");
                else
                    printf(" [ERR %d]\n",ret);

                fclose(out);
            }
        }
    }
    fclose(devnull);
    fclose(in);
    printf("\n");
}
Exemple #11
0
    RealTime SubModel::getIntersectionTime(const Ray& pRay, bool pExitAtFirst, float pMaxDist) const
    {
        TriangleBox const *firstObject;
        double  firstDistance = inf();

        #ifdef _DEBUG_VMAPS
        int debugCount =0;
        #endif
        Ray relativeRay = Ray::fromOriginAndDirection(pRay.origin - getBasePosition(), pRay.direction);

        const IT end = endRayIntersection();
        IT obj = beginRayIntersection(relativeRay,pMaxDist,false);

        Triangle testT;
        for ( ;obj != end; ++obj)                           // (preincrement is *much* faster than postincrement!)
        {
            /*
            Call your accurate intersection test here.  It is guaranteed
            that the ray hits the bounding box of obj.  (*obj) has type T,
            so you can call methods directly using the "->" operator.
            */
            const TriangleBox *tri = &(*obj);

            testT = Triangle(tri->vertex(0).getVector3(),tri->vertex(1).getVector3(),tri->vertex(2).getVector3());
            double t = testIntersectionWithTriangle(obj,testT, relativeRay);
            #ifdef _DEBUG_VMAPS
            if(debugCount == 5)
            {
                firstObject = tri;
                firstDistance = 1;
            }
            ++debugCount;
            #endif
            if(t != inf())
            {
                /*
                Tell the iterator that we've found at least one
                intersection.  It will finish looking at all
                objects in this node and then terminate.
                */
                obj.markBreakNode();
                if(firstDistance > t && pMaxDist >= t)
                {
                    firstDistance = t;
                    firstObject   = tri;
                    if(pExitAtFirst) break;
                }
            }
            else
            {
                // This might the wrong side of the triangle... Turn it and test again
                testT = Triangle(tri->vertex(2).getVector3(),tri->vertex(1).getVector3(),tri->vertex(0).getVector3());
                t = testIntersectionWithTriangle(obj, testT,relativeRay);
                if(t != inf())
                {
                    obj.markBreakNode();
                    if(firstDistance > t && pMaxDist >= t)
                    {
                        firstDistance = t;
                        firstObject   = tri;
                        if(pExitAtFirst) break;
                    }
                }
            }
        }
        #ifdef _DEBUG_VMAPS
        if(firstDistance < inf())
        {
            myfound = true;
            p1 = firstObject->vertex(0).getVector3()+ getBasePosition();
            p2 = firstObject->vertex(1).getVector3()+ getBasePosition();
            p3 = firstObject->vertex(2).getVector3()+ getBasePosition();
            p4 = relativeRay.origin + getBasePosition();
            p5 =  relativeRay.intersection(testT.plane()) + getBasePosition();
            float dist1 = (p5-p4).magnitude();
            double dist2 = relativeRay.intersectionTime(testT);
            float dist3 = relativeRay.direction.magnitude();
            double dist4 = relativeRay.intersectionTime(testT);
        }
        #endif

        return(firstDistance);
    }
Exemple #12
0
SAVESTATE_t* ReadSave(FILE *ifile) {
	int i;
	int compressed = FALSE;
	int chunk_offset,chunk_count;
	char string[128];
	TCHAR tmpfn[L_tmpnam];
	TCHAR temp_save[MAX_PATH];
	SAVESTATE_t *save;
	CHUNK_t *chunk;
	FILE *tmpfile;

	fread(string, 1, 8, ifile);
	string[8] = 0;
	if (strncmp(DETECT_CMP_STR, string, 8) == 0) {
		i = fgetc(ifile);
#ifdef WINVER
		_ttmpnam_s(tmpfn);
		GetAppDataString(temp_save, sizeof(temp_save));
		StringCbCat(temp_save, sizeof(temp_save), tmpfn);
		_tfopen_s(&tmpfile, temp_save, _T("wb"));
#else
		tmpnam(tmpfn);
		strcpy(temp_save, getenv("appdata"));
		strcat(temp_save, tmpfn);
		tmpfile = fopen(temp_save,"wb");
#endif
		if (!tmpfile) {
			return NULL;
		}
		//int error;
		switch(i) {
#ifdef ZLIB_WINAPI
			case ZLIB_CMP:
				{
					int error = inf(ifile,tmpfile);
					break;
				}
#endif
			default:
				fclose(tmpfile);
#ifdef _WINDOWS
				_tremove(tmpfn);
#else
				remove(tmpfn);
#endif
				return NULL;
		}
		
		fclose(tmpfile);
#ifdef WINVER
		_tfopen_s(&ifile, temp_save, _T("rb"));	//this is not a leak, file gets closed
											// outside of this routine.
#else
		ifile = fopen(temp_save,"rb");	//this is not a leak, file gets closed
										// outside of this routine.
#endif
		if (!ifile) {
			return NULL;
		}
		compressed = TRUE;
		fread(string, 1, 8, ifile);
	}
		
	if (strncmp(DETECT_STR, string, 8) != 0){

		if (compressed == TRUE) fclose(ifile);
		return NULL;
	}		
	
	save = (SAVESTATE_t *) malloc(sizeof(SAVESTATE_t));
	if (!save) {
		if (compressed == TRUE) fclose(ifile);
		return NULL;
	}

	chunk_offset = fgeti(ifile);
	
	save->version_major = fgeti(ifile);
	save->version_minor = fgeti(ifile);
	save->version_build = fgeti(ifile);


	if (save->version_major != CUR_MAJOR) {
		fclose(ifile);
		free(save);
		return NULL;
	}

	save->model = fgeti(ifile);

	chunk_count = fgeti(ifile);
	fread(save->author,1,32,ifile);
	fread(save->comment,1,64,ifile);

	fseek(ifile, chunk_offset + 8 + 4, SEEK_SET);
	
	for(i = 0; i < 512; i++) {
		save->chunks[i] = NULL;
	}
	save->chunk_count = 0;
	for(i = 0; i < chunk_count; i++) {
		string[0]	= fgetc(ifile);
		string[1]	= fgetc(ifile);
		string[2]	= fgetc(ifile);
		string[3]	= fgetc(ifile);
		string[4]	= 0;
		chunk		= NewChunk(save,string);
		chunk->size	= fgeti(ifile);
		chunk->data	= (unsigned char *) malloc(chunk->size);
		fread(chunk->data,1,chunk->size,ifile);
	}
	if (compressed == TRUE) {
		fclose(ifile);
#ifdef _WINDOWS
		_tremove(temp_save);
#else
		remove(temp_save);
#endif
	}
/* check for read errors... */
	return save;
}
RayGridIterator::RayGridIterator
(Ray                    ray, 
 const Vector3int32&    numCells, 
 const Vector3&         cellSize,
 const Point3&          gridOrigin,
 const Point3int32&     gridOriginIndex) :
    m_numCells(numCells),
    m_enterDistance(0.0f),
    m_ray(ray), 
    m_cellSize(cellSize),
    m_insideGrid(true) {
    
    if (gridOrigin.nonZero()) {
        // Change to the grid's reference frame
        ray = Ray::fromOriginAndDirection(ray.origin() - gridOrigin, ray.direction());
    }

    //////////////////////////////////////////////////////////////////////
    // See if the ray begins inside the box
    const AABox gridBounds(Vector3::zero(), Vector3(numCells) * cellSize);

    bool startsOutside = false;
    bool inside = false;
    Point3 startLocation = ray.origin();

    const bool passesThroughGrid =
        CollisionDetection::rayAABox
        (ray, Vector3(1,1,1) / ray.direction(),
         gridBounds, gridBounds.center(),
         square(gridBounds.extent().length() * 0.5f),
         startLocation,
         inside);

    if (! inside) {
        if (passesThroughGrid) {
            // Back up slightly so that we immediately hit the
            // start location.  The precision here is tricky--if
            // the ray strikes at a very glancing angle, we need
            // to move a large distance along the ray to enter the
            // grid.  If the ray strikes head on, we only need to
            // move a small distance.
            m_enterDistance = (ray.origin() - startLocation).length() - 0.0001f;
            startLocation = ray.origin() + ray.direction() * m_enterDistance;
            startsOutside = true;
        } else {
            // The ray never hits the grid
            m_insideGrid = false;
        }
    }

    //////////////////////////////////////////////////////////////////////
    // Find the per-iteration variables
    for (int a = 0; a < 3; ++a) {
        m_index[a]  = floor(startLocation[a] / cellSize[a]);
        m_tDelta[a] = cellSize[a] / abs(ray.direction()[a]);

        m_step[a]   = sign(ray.direction()[a]);

        // Distance to the edge fo the cell along the ray direction
        float d = startLocation[a] - m_index[a] * cellSize[a];
        if (m_step[a] > 0) {
            // Measure from the other edge
            d = cellSize[a] - d;

            // Exit on the high side
            m_boundaryIndex[a] = m_numCells[a];
        } else {
            // Exit on the low side (or never)
            m_boundaryIndex[a] = -1;
        }
        debugAssert(d >= 0 && d <= cellSize[a]);

        if (ray.direction()[a] != 0) {
            m_exitDistance[a] = d / abs(ray.direction()[a]) + m_enterDistance;
        } else {
            // Ray is parallel to this partition axis.
            // Avoid dividing by zero, which could be NaN if d == 0
            m_exitDistance[a] = inf();
        }
    }

    if (gridOriginIndex.nonZero()) {
        // Offset the grid coordinates
        m_boundaryIndex += gridOriginIndex;
        m_index += gridOriginIndex;
    }


    if (startsOutside) {
        // Let the increment operator bring us into the first cell
        // so that the starting axis is initialized correctly.
        ++(*this);
    }
}
Exemple #14
0
int	main(int argc, char* argv[])
{
	char*	infile = NULL;
	char*	outfile = NULL;
	int	tree_depth = 6;
	int	tile_size = 256;

	for ( int arg = 1; arg < argc; arg++ ) {
		if ( argv[arg][0] == '-' ) {
			// command-line switch.
			
			switch ( argv[arg][1] ) {
			case 'h':
			case '?':
				print_usage();
				exit( 1 );
				break;

			case 't':
				// Set the tilesize.
				if (arg + 1 >= argc) {
					printf("error: -t option requires an integer for tile_size\n");
					print_usage();
					exit(1);
				}
				arg++;
				tile_size = atoi(argv[arg]);
				break;
			case 'd':
				// Tree depth.
				if (arg + 1 >= argc) {
					printf("error: -d option requires an integer for tree_depth\n");
					print_usage();
					exit(1);
				}
				arg++;
				tree_depth = atoi(argv[arg]);
				break;

			default:
				printf("error: unknown command-line switch -%c\n", argv[arg][1]);
				exit(1);
				break;
			}

		} else {
			// File argument.
			if ( infile == NULL ) {
				infile = argv[arg];
			} else if ( outfile == NULL ) {
				outfile = argv[arg];
			} else {
				// This looks like extra noise on the command line; complain and exit.
				printf( "argument '%s' looks like extra noise; exiting.\n", argv[arg]);
				print_usage();
				exit( 1 );
			}
		}
	}

	// Must specify input filename.
	if (infile == NULL) {
		printf("error: you must supply an input filename which points to a .jpg image\n");
		print_usage();
		exit(1);
	}

	// Must specify an output filename.
	if (outfile == NULL) {
		printf("error: you must specify an output filename, for the texture quadtree output\n");
		print_usage();
		exit(1);
	}

	// Validate the tile_size.  Must be a power of two.
	int	logged_tile_size = 1 << frnd(log2((float) tile_size));
	if (tile_size <= 0 || logged_tile_size != tile_size) {
		printf("error: tile_size must be a power of two.\n");
		print_usage();
		exit(1);
	}

	// Validate tree depth.  Keep it within reason.
	if (tree_depth <= 0 || tree_depth > 12)
	{
		printf("error: tree_depth out of range.  Keep it between 1 and 12.\n");
		print_usage();
		exit(1);
	}
	
	// Open input file.
	tu_file*	in = new tu_file(infile, "rb");
	if (in->get_error())
	{
		printf("Can't open input file '%s'!\n", infile);
		delete in;
		exit(1);
	}

	// Open output file.
	tu_file*	out = new tu_file(outfile, "w+b");
	if (out->get_error())
	{
		printf("Can't open output file '%s'!\n", outfile);
		delete in;
		delete out;
		exit(1);
	}

	// Start reading the input.
	jpeg::input*	j_in = jpeg::input::create(in);
	if (j_in == NULL) {
		printf("Failure reading JPEG header of input file '%s'!\n", infile);
		delete in;
		delete out;
		exit(1);
	}

	// Size the tiles.
	int	tile_dim = 1 << (tree_depth - 1);

	// Write .tqt header.
	out->write_bytes("tqt\0", 4);	// filetype tag
	out->write_le32(1);			// version number.
	out->write_le32(tree_depth);
	out->write_le32(tile_size);

	// Make a null table of contents, and write it to the file.
	array<Uint32>	toc;
	toc.resize(tqt::node_count(tree_depth));

	int	toc_start = out->get_position();
	for (int i = 0; i < toc.size(); i++) {
		toc[i] = 0;
		out->write_le32(toc[i]);
	}

	int	tile_max_source_height = int(j_in->get_height() / float(tile_dim) + 1);

	// Create a horizontal strip, as wide as the image, and tall
	// enough to cover a whole tile.
	image::rgb*	strip = image::create_rgb(j_in->get_width(), tile_max_source_height);

	// Initialize the strip by reading the first set of scanlines.
	int	next_scanline = 0;
	int	strip_top = 0;
	while (next_scanline < tile_max_source_height) {
		j_in->read_scanline(image::scanline(strip, next_scanline));
		next_scanline++;
	}

	image::rgb*	tile = image::create_rgb(tile_size, tile_size);

	printf("making leaf tiles....     ");

	// generate base level tiles.
	for (int row = 0; row < tile_dim; row++) {
		float	y0 = float(row) / tile_dim * j_in->get_height();
		float	y1 = float(row + 1) / tile_dim * j_in->get_height();

		int	lines_to_read = imin(int(y1), j_in->get_height()) - (strip_top + strip->m_height);
		if (lines_to_read > 0)
		{
			// Copy existing lines up...
			int	lines_to_keep = strip->m_height - lines_to_read;
			{for (int i = 0; i < lines_to_keep; i++) {
				memcpy(image::scanline(strip, i), image::scanline(strip, i + lines_to_read /*keep*/), strip->m_width * 3);
			}}

			// Read new lines
			{for (int i = lines_to_keep; i < strip->m_height; i++) {
				j_in->read_scanline(image::scanline(strip, i));
			}}

			strip_top += lines_to_read;
		}

		for (int col = 0; col < tile_dim; col++) {
			float	x0 = float(col) / tile_dim * j_in->get_width();
			float	x1 = float(col + 1) / tile_dim * j_in->get_width();

			// Resample from the input strip to the output tile.
			image::resample(tile, 0, 0, tile_size - 1, tile_size - 1,
					strip, x0, y0 - strip_top, x1, y1 - strip_top);

			// Update the table of contents with an offset
			// to the data we're about to write.
			int	offset = out->get_position();
			int	quadtree_index = tqt::node_index(tree_depth - 1, col, row);
			toc[quadtree_index] = offset;

			// Write the jpeg data.
			image::write_jpeg(out, tile, 90);

			int	percent_done = int(100.f * float(col + row * tile_dim) / (tile_dim * tile_dim));
			printf("\b\b\b\b\b\b%3d%% %c", percent_done, spinner[(spin_count++)&3]);
		}
	}


	// Done reading the input file.
	delete j_in;
	delete in;

	delete strip;
	delete tile;	// done with the working tile surface.

	printf("\n");

	printf("making interior tiles....");

	// Now generate the upper levels of the tree by resampling the
	// lower levels.
	// 
	// The output file is both input and output at this point.
	tqt_info	inf(out, &toc, tree_depth, tile_size);
	image::rgb*	root_tile = generate_tiles(&inf, 0, 0, 0);

	delete root_tile;	// dispose of root tile.

	// Write the TOC back into the head of the file.
	out->set_position(toc_start);
	{for (int i = 0; i < toc.size(); i++) {
		out->write_le32(toc[i]);
	}}

	delete out;

	return 0;
}
Exemple #15
0
// constructors
Terrain::Terrain(real width, real height, real depth)
{
	dimensions.x = inf(width, 0.0f);
	dimensions.y = height;
	dimensions.z = inf(depth, 0.0f);
}
Exemple #16
0
void ProjectHandle::loadData(){

    QString Name = QFileDialog::getOpenFileName(NULL,tr("Open picture"), ".",tr("Project files (*.bmp *.jpg *.jpeg *.png)"));
    if (Name.isEmpty()){
        return;
    }


    QImage* load_image = new QImage(Name);

    New_dlg dlg(libPath);
    QPixmap pic =QPixmap::fromImage(load_image->scaled(dlg.pic_label->size())) ;
    dlg.pic_label->setPixmap(pic);

    QFile libFile(libPath);
    if(!libFile.open(QFile::ReadOnly | QFile::WriteOnly)){
        emit addToLog("Не найден файл библиотек");
        QDir dir;
        QFileInfo inf(libPath);
        dir=inf.dir();
        dir.mkdir(dir.absolutePath());
        QTextStream s(&libFile);
        s << "";
    }else{

        QTextStream readS(&libFile);
        while(!readS.atEnd()){
            QString inp;
            readS >> inp;
            dlg.material_Box->addItem(inp);
        }
    }


    if(!dlg.exec()){
        delete load_image;
        return;
    }

    colorMap = load_image;

    PObject object;
    if(dlg.width_sizeBox->currentText()=="um"){
        object.width = dlg.width_SpinBox->value();
    }else{
        object.width = dlg.width_SpinBox->value()*1000;
    }

    if(dlg.height_sizeBox->currentText()=="um"){
        object.height = dlg.height_SpinBox->value();
    }else{
        object.height = dlg.height_SpinBox->value()*1000;
    }

    object.map = new Image;
    object.map->data = new uchar[colorMap->width()*colorMap->height()];
    object.material     =   dlg.material_Box->currentText();
    object.map->sizeX   =   colorMap->width() ;
    object.map->sizeY   =   colorMap->height() ;


    calculate(&object);

    map=object.map;
    object.path=Name;

    QFileInfo inf(Name);
    projObjects.insert(inf.fileName(),object);

    curName=inf.fileName();
    emit addToList(inf.fileName());
    emit cleanGl();
    emit set_glwMap(map);
    emit imageLoad(map->sizeX,map->sizeY);
}
Exemple #17
0
inline BigFloat Infinity<BigFloat>( const BigFloat& alpha )
{
    BigFloat inf(0,alpha.Precision());
    mpfr_set_inf( inf.Pointer(), 1 );
    return inf;
}
Exemple #18
0
static void tst1() {
    ext_numeral inf(true);
    ext_numeral minus_inf(false);
    ext_numeral zero(0);

    SASSERT(ext_numeral(10) + ext_numeral(3) == ext_numeral(13));
    SASSERT(inf + zero == inf);
    SASSERT(minus_inf + zero == minus_inf);
    SASSERT(minus_inf + ext_numeral(3) == minus_inf);
    SASSERT(inf + inf == inf);
    SASSERT(minus_inf + minus_inf == minus_inf);
    SASSERT(minus_inf + ext_numeral(10) == minus_inf);
    SASSERT(minus_inf + ext_numeral(-10) == minus_inf);
    SASSERT(inf + ext_numeral(10) == inf);
    SASSERT(inf + ext_numeral(-10) == inf);

    SASSERT(ext_numeral(10) - ext_numeral(3) == ext_numeral(7));
    SASSERT(inf - zero == inf);
    SASSERT(minus_inf - zero == minus_inf);
    SASSERT(minus_inf - ext_numeral(3) == minus_inf);
    SASSERT(inf - minus_inf == inf);
    SASSERT(minus_inf - inf == minus_inf);
    SASSERT(zero - minus_inf == inf);
    SASSERT(zero - inf == minus_inf);
    SASSERT(ext_numeral(-10) - minus_inf == inf);
    SASSERT(ext_numeral(10) - minus_inf == inf);
    SASSERT(ext_numeral(-10) - inf == minus_inf);
    SASSERT(ext_numeral(10) - inf == minus_inf);

    SASSERT(ext_numeral(10) * inf == inf);
    SASSERT(ext_numeral(-10) * inf == minus_inf);
    SASSERT(zero * inf == zero);
    SASSERT(zero * minus_inf == zero);
    SASSERT(zero * ext_numeral(10) == zero);
    SASSERT(ext_numeral(10) * ext_numeral(-20) == ext_numeral(-200));
    SASSERT(ext_numeral(3) * ext_numeral(2) == ext_numeral(6));
    SASSERT(inf * inf == inf);
    SASSERT(inf * minus_inf == minus_inf);
    SASSERT(minus_inf * minus_inf == inf);
    SASSERT(minus_inf * inf == minus_inf);
    SASSERT(minus_inf * ext_numeral(10) == minus_inf);
    SASSERT(minus_inf * ext_numeral(-10) == inf);

    SASSERT(minus_inf < inf);
    SASSERT(!(inf < minus_inf));
    SASSERT(minus_inf < ext_numeral(10));
    SASSERT(ext_numeral(-3) < inf);
    SASSERT(ext_numeral(-10) < ext_numeral(4));
    SASSERT(ext_numeral(2) < ext_numeral(10));
    SASSERT(!(inf < ext_numeral(30)));
    SASSERT(!(ext_numeral(10) < minus_inf));
    SASSERT(!(inf < inf));
    SASSERT(!(minus_inf < minus_inf));
    SASSERT(!(zero < zero));
    SASSERT(!(ext_numeral(10) < ext_numeral(10)));
    SASSERT(inf > minus_inf);
    SASSERT(inf > zero);
    SASSERT(inf > ext_numeral(10));
    SASSERT(ext_numeral(10) > minus_inf);
    SASSERT(zero > minus_inf);
    SASSERT(!(zero > inf));
    SASSERT(!(minus_inf > inf));
    SASSERT(inf >= minus_inf);
    SASSERT(inf >= inf);
    SASSERT(minus_inf >= minus_inf);
    SASSERT(inf >= zero);
    SASSERT(zero >= minus_inf);
    SASSERT(inf <= inf);
    SASSERT(minus_inf <= minus_inf);
    SASSERT(zero <= inf);
    SASSERT(minus_inf <= zero);

    ext_numeral val(10);
    val.neg();
    SASSERT(val == ext_numeral(-10));
    val = inf;
    val.neg();
    SASSERT(val == minus_inf);
    val.neg();
    SASSERT(val == inf);

    SASSERT(minus_inf.sign());
    SASSERT(!zero.sign());
    SASSERT(!inf.sign());
    SASSERT(ext_numeral(-10).sign());
    SASSERT(!ext_numeral(10).sign());
    
    SASSERT(inf.is_infinite());
    SASSERT(minus_inf.is_infinite());
    SASSERT(!zero.is_infinite());
    SASSERT(!ext_numeral(10).is_infinite());
    SASSERT(!inf.is_zero());
    SASSERT(!minus_inf.is_zero());
    SASSERT(zero.is_zero());
    SASSERT(!ext_numeral(10).is_zero());
}
CXBindingsFileInfo CXBindingsCppObjectsGenerator::DoGenerateRuleCodeFor( CXBindingsRuleInfo& ruleInfo , CXBindings& , CXBindingsGeneratorOptions& options )
{
    CXBindingsFileInfo res;

    //wxLogMessage( "\t\t Rule make is : ") + ruleInfo.make  ;
    //wxLogMessage( "\t\t Rule name is : ") + ruleInfo.name.content  ;
    //wxLogMessage( "\t\t Rule type is : ") + ruleInfo.type.content  ;



    CXBindingsStringStringMap& types = m_genfile->GetTypeInfo().GetTypes();
    std::string realType = ruleInfo.type.content;
    std::string typeTemplate = ruleInfo.type.stemplate;

    CXBindingsGeneratorFileTemplate* arrayTemplate = NULL;

    CXBindingsStringStringMap::iterator it = types.find( realType );

    realType = GetRealType( realType  , options );

    std::string typeExt = realType;
    if( !IsKnownType( realType ) )
        typeExt = GetRealType( realType , options );

    if( it != types.end() ) {
        realType = it->second;
        typeExt = realType;
    }

    std::string savedType = typeExt;

    if( typeTemplate == "array")    {
        typeExt = "std::vector< " + typeExt + " >" ;
        arrayTemplate = m_genfile->FindTemplate( "array_addons")  ;
    }


    if( ruleInfo.make == "import")    {

        // We have to add here all informations about the object from which this one is derived
        // this information is contained in the realType variable

        /* for each element in the info object of the grammar */
        CXBindings& grammar = m_interpreterInfo.grammar;
        CXBindingsInfo& info = grammar.GetInfo();
        CXBindingsArrayString genOrder = info.GetGeneration().GetObjects();

        /* The first thing to do is to estabilsh the generation objects dependecy list
         * So that object will be generated in the right order...
         */
        CXBindingsArrayString dependencies;

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

            CXBindingsArrayGrammarObjectInfoMap& objectsInfoMap = m_interpreterInfo.objects;
            CXBindingsArrayGrammarObjectInfo& objectsInfo = objectsInfoMap[genOrder[i]];

            for( unsigned int j = 0; j < objectsInfo.size() ; ++j ) {

                std::string name = objectsInfo[j].properties["name" ];

                name = GetRealType( name , options );

                if( name == savedType )  {
                    std::pair< std::string , CXBindingsFileInfo> inf( name , m_objectInfos[name] );
                    res.bases.push_back( inf );

                    return res;
                }

            }
        }

        std::pair< std::string , CXBindingsFileInfo> inf( savedType , m_objectInfos[savedType] );
        res.bases.push_back( inf );

        return res;
    }

    std::string nameExt = ruleInfo.name.content;
    nameExt = GetPropertyExtension( nameExt , options );
    SetMacro( "name_extension" , nameExt)  ;

    SetMacro( "name" , ruleInfo.name.content)  ;
    SetMacro( "type" , typeExt)  ;
    SetMacro( "real_type" , savedType)  ;
    SetMacro( "variable" , ruleInfo.variable.content)  ;

    CXBindingsGeneratorFileTemplate* rTemplate = m_genfile->FindTemplate( ruleInfo.make );

    if( rTemplate == NULL )
        CXB_THROW( "Error cannot find template : " + ruleInfo.make)  ;

    if( ruleInfo.make == "property" || ruleInfo.make ==  "attribute" )    {
        std::pair< std::string , std::string > mpair( ruleInfo.name.content , typeExt );
        res.properties.push_back( mpair );
    }

    if( ruleInfo.make == "property" || ruleInfo.make == "attribute" || ruleInfo.make == "variant_accessor"  || ruleInfo.make == "variant_array_accessor")  {
        std::pair< std::string , std::string > mpair( ruleInfo.name.content , savedType );
        res.dependencies.push_back( mpair );
    }

    CXBindingsArrayGrammarGeneratorFileObjectPart& objects = rTemplate->GetObjects();

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

        std::string content = objects[i].GetContent();
        DoReplaceMacros( content );

        if( objects[i].GetFile() =="header")
        {
            if( objects[i].GetPermission() == "private")
                res.headerPrivateInfo += content;
            else if( objects[i].GetPermission() == "protected")
                res.headerProtectedInfo += content;
            else
                res.headerPublicInfo += content;
        }
        else
            res.srcInfo += content;
    }

    if( arrayTemplate != NULL ) {
        CXBindingsArrayGrammarGeneratorFileObjectPart& objectsArray = arrayTemplate->GetObjects();

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

            std::string content = objectsArray[i].GetContent();
            DoReplaceMacros( content );

            if( objectsArray[i].GetFile() =="header")
            {
                if( objectsArray[i].GetPermission() == "private")
                    res.headerPrivateInfo += content;
                else if( objectsArray[i].GetPermission() == "protected")
                    res.headerProtectedInfo += content;
                else
                    res.headerPublicInfo += content;
            }
            else
                res.srcInfo += content;
        }
    }

    return res;

}
Exemple #20
0
void FileList::addFile(const QString &filepath)
{
    QFileInfo inf(filepath);
    if (filterMatches(inf))
        mFileList << inf;
}
/*!
	\param e target editor
	\param file filename displayed by the editor

	The \a file parameter may actuall be either a filename, an extension or the name of the language,
	checked in that order.

	If it is a filename, complete extension as higher priority than simple extension
	(see QFileInfo suffix() and completeSuffix()).

	Matches are first done case-sensitively.

	If no matching language definition is found for all three possible interpretations of the \a file
	parameter, the same search is done case-insensitively.

	If no matching language is found the previous language definition/completion engine of the editor
	are removed, leaving it blank, and the format scheme of the document is set to the defaultFormatScheme()
*/
void QLanguageFactory::setLanguage(QEditor *e, const QString& file)
{
	QString lang;
	QFileInfo inf(file);
	const QString ext = inf.suffix(),
				cext = inf.completeSuffix();

	//qDebug("suff:%s; compSuff:%s", qPrintable(ext), qPrintable(cext));

	QLanguageDefinition *oldLang = e->languageDefinition();

	if ( file.count() )
	{
		QList<Qt::CaseSensitivity> lcs;
		lcs << Qt::CaseSensitive << Qt::CaseInsensitive;

		foreach ( Qt::CaseSensitivity cs, lcs )
		{
			int n = 0, idx = -1;
			QStringList ext_langs, cext_langs, fcext_langs;

			foreach ( QString lang, m_languages )
			{
				const QStringList& exts = m_data[lang].extensions;

				//qDebug("%s in (%s) ?", qPrintable(ext), qPrintable(exts.join(" ")));

				foreach ( QString x, exts )
				{
					if ( !x.compare(ext, cs) )
						ext_langs << lang;

					if ( !x.compare(cext, cs) )
						cext_langs << lang;

					if ( !x.compare(file, cs) )
						fcext_langs << lang;
				}

				if ( !lang.compare(file, cs) )
					idx = n;

				++n;
			}

			if ( cext_langs.count() )
			{
				// TODO : use MIME types to resolve ambiguity
				lang = cext_langs.first();
			} else if ( ext_langs.count() ) {
				// TODO : use MIME types to resolve ambiguity
				lang = ext_langs.first();
			} else if ( fcext_langs.count() ) {
				// TODO : use MIME types to resolve ambiguity
				lang = fcext_langs.first();
			} else if ( idx != -1 ) {
				lang = m_languages.at(idx);
			}

			if ( lang.count() )
				break;
		}
Exemple #22
0
/* Check that forking won't return the same random. */
static void
check_forking (void)
{
#ifdef HAVE_W32_SYSTEM
    if (verbose)
        inf ("check_forking skipped: not applicable on Windows\n");
#else /*!HAVE_W32_SYSTEM*/
    pid_t pid;
    int rp[2];
    int i, status;
    size_t nread;
    char tmp1[16], tmp1c[16], tmp1p[16];

    if (verbose)
        inf ("checking that a fork won't cause the same random output\n");

    /* We better make sure that the RNG has been initialzied. */
    gcry_randomize (tmp1, sizeof tmp1, GCRY_STRONG_RANDOM);
    if (verbose)
        print_hex ("initial random: ", tmp1, sizeof tmp1);

    if (pipe (rp) == -1)
        die ("pipe failed: %s\n", strerror (errno));

    pid = fork ();
    if (pid == (pid_t)(-1))
        die ("fork failed: %s\n", strerror (errno));
    if (!pid)
    {
        gcry_randomize (tmp1c, sizeof tmp1c, GCRY_STRONG_RANDOM);
        if (writen (rp[1], tmp1c, sizeof tmp1c))
            die ("write failed: %s\n", strerror (errno));
        if (verbose)
        {
            print_hex ("  child random: ", tmp1c, sizeof tmp1c);
            fflush (stdout);
        }
        _exit (0);
    }
    gcry_randomize (tmp1p, sizeof tmp1p, GCRY_STRONG_RANDOM);
    if (verbose)
        print_hex (" parent random: ", tmp1p, sizeof tmp1p);

    close (rp[1]);
    if (readn (rp[0], tmp1c, sizeof tmp1c, &nread))
        die ("read failed: %s\n", strerror (errno));
    if (nread != sizeof tmp1c)
        die ("read too short\n");

    while ( (i=waitpid (pid, &status, 0)) == -1 && errno == EINTR)
        ;
    if (i != (pid_t)(-1)
            && WIFEXITED (status) && !WEXITSTATUS (status))
        ;
    else
        die ("child failed\n");

    if (!memcmp (tmp1p, tmp1c, sizeof tmp1c))
        die ("parent and child got the same random number\n");
#endif  /*!HAVE_W32_SYSTEM*/
}
Exemple #23
0
/****************
 * Copy the option file skeleton to the given directory.  If NAME2 is
 * not NULL it is used as the destination name.
 */
static int
copy_file (const char *name, const char *name2)
{
  char *srcname, *dstname;
  FILE *srcfp, *dstfp;
  int tried_mkdir = 0;
  char buffer[4096];

  if (verbose > 1)
    {
      if (name2)
        inf ("copying '%s' as '%s'", name, name2);
      else
        inf ("copying '%s'", name);
    }

  srcname = make_sourcename (name);
  dstname = make_targetname (name2? name2:name);

  srcfp = fopen (srcname, "rb");
  if (!srcfp)
    {
      err ("failed to open '%s': %s\n", srcname, strerror (errno));
      free (srcname);
      free (dstname);
      return 1;
    }

 again:
  dstfp = fopen (dstname, "wb");
  if (!dstfp)
    {
      if (!tried_mkdir && errno == ENOENT && strchr (name, '/'))
        {
          tried_mkdir = 1;
          make_dirs (name);
          goto again;
        }

      err ("failed to create '%s': %s\n", dstname, strerror (errno));
      fclose (srcfp);
      free (srcname);
      free (dstname);
      return 1;
    }

  while (!feof (srcfp))
    {
      size_t n;

      n = fread (buffer, 1, sizeof buffer, srcfp);
      if (n < sizeof buffer && ferror (srcfp))
        {
          err ("error reading '%s'\n", srcname);
          fclose (srcfp);
          fclose (dstfp);
          free (srcname);
          free (dstname);
          return 1;
        }

      errno = 0;
      if (fwrite (buffer, 1, n, dstfp) != n)
        {
          err ("error writing to '%s': %s\n", dstname, strerror (errno));
          fclose (srcfp);
          fclose (dstfp);
          free (srcname);
          free (dstname);
          return 1;
        }
    }

  if (fflush (dstfp) == EOF)
    {
      err ("error writing to '%s': %s\n", dstname, strerror (errno));
      fclose (srcfp);
      fclose (dstfp);
      free (srcname);
      free (dstname);
      return 1;
    }
  if (fclose (dstfp) == EOF)
    {
      err ("error closing '%s': %s\n", dstname, strerror (errno));
      fclose (srcfp);
      fclose (dstfp);
      free (srcname);
      free (dstname);
      return 1;
    }

  fclose  (srcfp);

  free (srcname);
  free (dstname);
  return 0;
}
Exemple #24
0
/* Check that forking won't return the same nonce. */
static void
check_nonce_forking (void)
{
#ifdef HAVE_W32_SYSTEM
    if (verbose)
        inf ("check_nonce_forking skipped: not applicable on Windows\n");
#else /*!HAVE_W32_SYSTEM*/
    pid_t pid;
    int rp[2];
    int i, status;
    size_t nread;
    char nonce1[10], nonce1c[10], nonce1p[10];

    if (verbose)
        inf ("checking that a fork won't cause the same nonce output\n");

    /* We won't get the same nonce back if we never initialized the
       nonce subsystem, thus we get one nonce here and forget about
       it. */
    gcry_create_nonce (nonce1, sizeof nonce1);
    if (verbose)
        print_hex ("initial nonce: ", nonce1, sizeof nonce1);

    if (pipe (rp) == -1)
        die ("pipe failed: %s\n", strerror (errno));

    pid = fork ();
    if (pid == (pid_t)(-1))
        die ("fork failed: %s\n", strerror (errno));
    if (!pid)
    {
        gcry_create_nonce (nonce1c, sizeof nonce1c);
        if (writen (rp[1], nonce1c, sizeof nonce1c))
            die ("write failed: %s\n", strerror (errno));
        if (verbose)
        {
            print_hex ("  child nonce: ", nonce1c, sizeof nonce1c);
            fflush (stdout);
        }
        _exit (0);
    }
    gcry_create_nonce (nonce1p, sizeof nonce1p);
    if (verbose)
        print_hex (" parent nonce: ", nonce1p, sizeof nonce1p);

    close (rp[1]);
    if (readn (rp[0], nonce1c, sizeof nonce1c, &nread))
        die ("read failed: %s\n", strerror (errno));
    if (nread != sizeof nonce1c)
        die ("read too short\n");

    while ( (i=waitpid (pid, &status, 0)) == -1 && errno == EINTR)
        ;
    if (i != (pid_t)(-1)
            && WIFEXITED (status) && !WEXITSTATUS (status))
        ;
    else
        die ("child failed\n");

    if (!memcmp (nonce1p, nonce1c, sizeof nonce1c))
        die ("parent and child got the same nonce\n");
#endif  /*!HAVE_W32_SYSTEM*/
}
Exemple #25
0
int
main (int argc, char **argv)
{
  int last_argc = -1;
  int force = 0;

  if (argc)
    {
      argc--; argv++;
    }

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--version"))
        usage (-1);
      else if (!strcmp (*argv, "--help"))
        usage (0);
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--force"))
        {
          force = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--vanilla"))
        {
          install_type = iVANILLA;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--light"))
        {
          install_type = iLIGHT;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--full"))
        {
          install_type = iFULL;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        die ("unknown option '%s'", *argv);
    }

  if (argc != 1 || !*argv[0])
    usage (1);
  target_dir = fix_backslashes (argv[0]);

  inf ("source directory is '%s'", get_sourcedir ());
  inf ("target directory is '%s'", target_dir);

  switch (install_type)
    {
    case iVANILLA: filelist = vanilla_files; install_name = "vanilla"; break;
    case iLIGHT:   filelist = light_files;   install_name = "light"; break;
    case iFULL:    filelist = full_files;    install_name = "full"; break;
    default:  assert (!"bug");
    }

  if (check_target_dir (force))
    return 1;

  if (check_all_files ())
    return 1;

  if (copy_all_files ())
    return 1;

  if (make_home_dir ())
    return 1;

  if (write_ctl_file ())
    return 1;

  if (write_kde_conf ())
    return 1;

  inf ("ready");

  return 0;
}
CXBindingsHandlerFileInfo CXBindingsCppHandlersGenerator::DoGenerateRuleCodeFor( CXBindingsRuleInfo& ruleInfo , CXBindings& grammar , CXBindingsGeneratorOptions& options )
{
	CXBindingsHandlerFileInfo res;

	//wxLogMessage( "\t\t Rule make is : ") + ruleInfo.make  ;
	//wxLogMessage( "\t\t Rule name is : ") + ruleInfo.name.content  ;
	//wxLogMessage( "\t\t Rule type is : ") + ruleInfo.type.content  ;
	
	CXBindingsStringStringMap& types = m_genfile->GetTypeInfo().GetTypes();
	std::string realType = ruleInfo.type.content;
	
	//wxLogMessage( "\t\t Real type is : ") + realType  ;
	
	if( ruleInfo.make =="object")  
		realType = ruleInfo.name.content;
	
	std::string typeTemplate = ruleInfo.type.stemplate;
	CXBindingsStringStringMap::iterator it = types.find( realType );

	std::string typeExt = GetRealType( realType  , options );
//	if( !IsKnownType( realType ) )
//		typeExt = GetRealType( realType  , options );
//	
	if( it != types.end() ) {
		typeExt = it->second;
		//typeExt = realType;
	}
	
	//wxLogMessage( "\t\t Real type is : ") + realType  ;
	
	if( boost::contains(realType,":") )  
		realType = after_first(realType,':')  ; 
	
	//wxLogMessage( "\t\t Real type is : ") + realType  ;
	
	std::string savedType = realType;
	// Find here type corrspondances
	std::string rType = FindRealTypeFor( realType );
	
	if( ruleInfo.make =="object")  
		rType = "object" ;
	
	if( ruleInfo.make =="child_enumerator")  
		rType = "enum" ;

	if( typeTemplate == "array")    {
		//realType = "std::vector< ") + realType + wxT(" >" ;
		rType = "array"  + rType;
	}
	
	
	//wxLogMessage( "Registering type for : ") + ruleInfo.name.content + " type is :") + realType + wxT(" ") + rType + wxT(" rule make is :"  + ruleInfo.make  ;
	m_types[ruleInfo.name.content] = rType;

	if( ruleInfo.make == "import")    {
		
		// We have to add here all informations about the object from which this one is derived
		// this information is contained in the realType variable

		/* for each element in the info object of the grammar */
		CXBindings& grammar = m_interpreterInfo.grammar;
		CXBindingsInfo& info = grammar.GetInfo();
		CXBindingsArrayString genOrder = info.GetGeneration().GetObjects();

		/* The first thing to do is to estabilsh the generation objects dependecy list
		 * So that object will be generated in the right order...
		 */
		CXBindingsArrayString dependencies;

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

			CXBindingsArrayGrammarObjectInfoMap& objectsInfoMap = m_interpreterInfo.objects;
			CXBindingsArrayGrammarObjectInfo& objectsInfo = objectsInfoMap[genOrder[i]];

			for( unsigned int j = 0; j < objectsInfo.size() ; ++j ) {

				std::string name = objectsInfo[j].properties["name" ];

				name = GetRealType( name , options );
				//wxLogMessage( "Checking bases for") + name + "-") + typeExt + wxT("-"  + realType  ;
				if( name == typeExt )  {
					std::pair< std::string , CXBindingsHandlerFileInfo> inf( name , m_objectInfos[name] );
					res.bases.push_back( inf );
					//wxLogMessage( "Adding bases for") + name + "-") + typeExt + wxT("-"  + realType  ;
					return res;
				}

			}
		}

		std::pair< std::string , CXBindingsHandlerFileInfo> inf( typeExt , m_objectInfos[typeExt] );
		res.bases.push_back( inf );
		return res;
	}

	
	if( ruleInfo.make == "property")    {
		std::pair< std::string , std::string > mpair( ruleInfo.name.content , typeExt );
		res.properties.push_back( mpair );
	}
	else if( ruleInfo.make == "attribute")    {
		std::pair< std::string , std::string > mpair( ruleInfo.name.content , typeExt );
		res.attributes.push_back( mpair );
	}
	
	if( ruleInfo.make == "property" || ruleInfo.make == "attribute" || ruleInfo.make == "variant_accessor"  || ruleInfo.make == "variant_array_accessor")   {
		std::pair< std::string , std::string > mpair( ruleInfo.name.content , typeExt );
		res.dependencies.push_back( mpair );
	}

	return res;
	
}
Exemple #27
0
/*!
 * \brief Xyce::createNetlist
 * \param[out] stream QTextStream that associated with spice netlist file
 * \param[in] simulations The list of simulations that need to included in netlist.
 * \param[out] vars The list of output variables and node names.
 * \param[out] outputs The list of spice output raw text files.
 */
void Xyce::createNetlist(QTextStream &stream, int , QStringList &simulations,
                    QStringList &vars, QStringList &outputs)
{
    QString s;
    bool hasParSweep = false;

    if(!prepareSpiceNetlist(stream,true)) return; // Unable to perform spice simulation
    startNetlist(stream,true);

    // set variable names for named nodes and wires
    vars.clear();
    for(Node *pn = Sch->DocNodes.first(); pn != 0; pn = Sch->DocNodes.next()) {
      if(pn->Label != 0) {
          if (!vars.contains(pn->Label->Name)) {
              vars.append(pn->Label->Name);
          }
      }
    }
    for(Wire *pw = Sch->DocWires.first(); pw != 0; pw = Sch->DocWires.next()) {
      if(pw->Label != 0) {
          if (!vars.contains(pw->Label->Name)) {
              vars.append(pw->Label->Name);
          }
      }
    }
    for(Component *pc = Sch->DocComps.first(); pc != 0; pc = Sch->DocComps.next()) {
        if (pc->isProbe) {
            QString var_pr = pc->getProbeVariable(true);
            if (!vars.contains(var_pr)) {
                vars.append(var_pr);
            }
        }
        /*if (pc->isEquation) {
            Equation *eq = (Equation *)pc;
            QStringList vars_eq;
            eq->getDepVars(vars_eq);
            vars.append(vars_eq);
        }*/
    }
    vars.sort();
    qDebug()<<vars;

    //execute simulations

    QFileInfo inf(Sch->DocName);
    QString basenam = inf.baseName();

    QString nod,nods;
    nods.clear();
    foreach (nod,vars) {
        if (!nod.startsWith("I(")) {
            nods += QString("v(%1) ").arg(nod);
        } else {
            nods += nod + " ";
        }
    }
    QString sim = simulations.first();

    for(Component *pc = Sch->DocComps.first(); pc != 0; pc = Sch->DocComps.next()) { // Xyce can run
       if(pc->isSimulation) {                        // only one simulations per time.
           QString sim_typ = pc->Model;              // Multiple simulations are forbidden.
           QString s = pc->getSpiceNetlist(true);
           if ((sim_typ==".AC")&&(sim=="ac")) stream<<s;
           if ((sim_typ==".TR")&&(sim=="tran")){
               stream<<s;
               Q3PtrList<Component> comps(Sch->DocComps); // find Fourier tran
               for(Component *pc1 = comps.first(); pc1 != 0; pc1 = comps.next()) {
                   if (pc1->Model==".FOURIER") {
                       if (pc1->Props.at(0)->Value==pc->Name) {
                           QString s1 = pc1->getSpiceNetlist(true);
                           outputs.append("spice4qucs.tran.cir.four");
                           stream<<s1;
                       }
                   }
               }
           }
           if ((sim_typ==".HB")&&(sim=="hb")) stream<<s;
           if (sim_typ==".SW") {
               QString SwpSim = pc->Props.at(0)->Value;
               if (SwpSim.startsWith("DC")&&(sim=="dc")) stream<<s;
               else if (SwpSim.startsWith("AC")&&(sim=="ac")) {
                   stream<<s;
                   hasParSweep = true;
               } else if (SwpSim.startsWith("TR")&&(sim=="tran")) {
                   stream<<s;
                   hasParSweep = true;
               } if (SwpSim.startsWith("HB")&&(sim=="hb")) {
                   stream<<s;
                   hasParSweep = true;
               }
           }
           if ((sim_typ==".DC")) stream<<s;
       }
    }


    QString filename;
    if (hasParSweep) filename = QString("%1_%2_swp.txt").arg(basenam).arg(sim);
    else filename = QString("%1_%2.txt").arg(basenam).arg(sim);
    QString write_str;
    if (sim=="hb") {
        write_str = QString(".PRINT  %1 file=%2 %3\n").arg(sim).arg(filename).arg(nods);
    } else {
        write_str = QString(".PRINT  %1 format=raw file=%2 %3\n").arg(sim).arg(filename).arg(nods);
    }
    stream<<write_str;
    outputs.append(filename);

    stream<<".END\n";
}
Exemple #28
0
void loadTriangles(char * filename)
{
    Triangles t;

    std::fstream inf(filename, std::ios::in | std::ios::binary);

    if(inf.fail())
    {
        std::cerr << "unable to open " << filename << std::endl;
        exit(1);
    }

    // vertex count
    inf.read((char *)&t.count, sizeof(t.count));

    std::cout << "reading " << t.count / 3 << " triangles..." << std::endl;

    // allocate memory for triangle vertices and normals
    // if we're using display lists we don't need to store these
    if(!useDisplayLists)
    {
        t.vertices = new float[3 * t.count];
        t.normals = new float[3 * t.count];
    }

    // save to global vector
    triangles.push_back(t);

    // allocate vertex and normal buffers and read from file
    float * vertexBuf = new float[4 * t.count];
    float * normalBuf = new float[4 * t.count];

    inf.read((char *)vertexBuf, 4 * t.count * sizeof(float));
    inf.read((char *)normalBuf, 4 * t.count * sizeof(float));

    inf.close();

    float * iv = vertexBuf, * ov = t.vertices;
    float * in = normalBuf, * on = t.normals;

    GLuint displayListId;

    if(useDisplayLists)
    {
        displayListId = glGenLists(1);
        glNewList(displayListId, GL_COMPILE);
        glBegin(GL_TRIANGLES);
    }

    for(int i=0; i<t.count; i++, iv+=4, in+=4)
    {
        if(minX > iv[0]) minX = iv[0];
        if(minY > iv[1]) minY = iv[1];
        if(minZ > iv[2]) minZ = iv[2];
        if(maxX < iv[0]) maxX = iv[0];
        if(maxY < iv[1]) maxY = iv[1];
        if(maxZ < iv[2]) maxZ = iv[2];

        if(useDisplayLists)
        {
            // start a new display list if necessary
            if(i % MAX_DISPLAYLIST_SIZE == 0)
            {
                glEnd();
                glEndList();
                displayLists.push_back(displayListId);

                displayListId = glGenLists(1);
                glNewList(displayListId, GL_COMPILE);
                glBegin(GL_TRIANGLES);
            }

            glNormal3f(in[0], in[1], in[2]);
            glVertex3f(iv[0], iv[1], iv[2]);
        }
        else
        {
            *ov++ = iv[0];
            *ov++ = iv[1];
            *ov++ = iv[2];

            *on++ = in[0];
            *on++ = in[1];
            *on++ = in[2];
        }
    }

    if(useDisplayLists)
    {
        glEnd();
        glEndList();
        displayLists.push_back(displayListId);
    }

    // free memory from file buffers
    delete [] vertexBuf;
    delete [] normalBuf;
}
Exemple #29
0
void FMPanel::dirDoubleClicked( const QModelIndex &  index )
{
    if( noDrive )
        return;
    const QStandardItemModel* model = qobject_cast<const QStandardItemModel*>( index.model() );
    if( model != 0 )
    {
        lastClick = QTime::currentTime ();
        QStandardItem* item = model->itemFromIndex( index );
        QString path( dirList->getRootDir() );
        if( path.at(path.size()-1)!='/')
        {
            path.append("/");
        }
        QString dirs( item->data(Qt::DisplayRole ).toString() );
        if(( dirs[0] == '.' )&&( dirs[1] == '.' )&&( dirs[2] == '\t' ))
        {
            QDir dir( path);
            if( dir.cdUp() )
            {
                path.clear();
                path.append( dir.canonicalPath () );
                currentDir.clear();
                currentDir.append( path  );
                dirList->setRootPath( currentDir );
                setPathEditText( currentDir );
                return;
            }
            else
            {
                return;
            }
        }
        path.append(dirs);
        QFileInfo inf( path ) ;
        //isAbsolute()
        //isBundle()
        if( inf.isDir() )
        {
            //mainW->startAnimation();
            currentFile.clear();
            //TODO check the size
            currentDir.clear();
            currentDir.append( path );
            dirList->setRootPath( currentDir );
            setPathEditText( currentDir );
            return;
        }
        if( inf.isExecutable() )
        {
            QProcess::startDetached( inf.absoluteFilePath() );
        }
        if( inf.isFile() )
        {
            if(( inf.suffix().compare( "7z", Qt::CaseInsensitive ) == 0)||
              ( inf.suffix().compare( "zip", Qt::CaseInsensitive ) == 0)||
              ( inf.suffix().compare( "gzip", Qt::CaseInsensitive ) == 0)||
              ( inf.suffix().compare( "bzip2", Qt::CaseInsensitive ) == 0)||
              ( inf.suffix().compare( "tar", Qt::CaseInsensitive ) == 0)||
              ( inf.suffix().compare( "arj", Qt::CaseInsensitive ) == 0)||
              ( inf.suffix().compare( "rar", Qt::CaseInsensitive ) == 0) )
            {
            mainW->startAnimation();
            //TODO make a lin version
#ifdef Q_WS_MAC
            QStringList args;
            //args<<"a"<<"-r"<<"-y"<<output<<fileInfo.fileName();
            //TODO change the output dir
            QString out;
            if( left )
            {
                //TODO check the current dir can be empty
                out.append(mainW->rightCurrentDir());
            }
            else
            {
                //TODO check the current dir can be empty
                out.append(mainW->leftCurrentDir());
            }
            args<<"-o"<<"-qq"<<inf.filePath()<<"-d"<<out;
            //qDebug()<<args;
            QProcess* proc = new QProcess();
            proc->setWorkingDirectory( currentDir );
            connect( proc, SIGNAL(finished( int , QProcess::ExitStatus )), this, SLOT( unzipTaskFinished( int , QProcess::ExitStatus ) ));
            //TODO change the output dir
            unzipVector.append(QPair<QProcess *,QPair<QString, bool> >( proc, QPair<QString, bool>( currentDir, true)) );
            proc->start( "unzip", args );
            reload();
            setPathEditText( currentDir );
            dirList->setFocus();
#endif
#ifdef Q_WS_WIN
            QStringList args;
            //args<<"a"<<"-r"<<"-y"<<output<<fileInfo.fileName();
            //TODO change the output dir
            QString out("-o");
            if( left )
            {
                //TODO check the current dir can be empty
                out.append(mainW->rightCurrentDir());
            }
            else
            {
                //TODO check the current dir can be empty
                out.append(mainW->leftCurrentDir());
            }
            args<<"x"<<"-bd"<<"-y"<<out<<inf.filePath();
            //qDebug()<<args;
            QProcess* proc = new QProcess();
            proc->setWorkingDirectory( currentDir );
            connect( proc, SIGNAL(finished( int , QProcess::ExitStatus )), this, SLOT( unzipTaskFinished( int , QProcess::ExitStatus ) ));
            //TODO change the output dir
            unzipVector.append(QPair<QProcess *,QPair<QString, bool> >( proc, QPair<QString, bool>( currentDir, true)) );
            proc->start( "7z.exe", args );
            reload();
            setPathEditText( currentDir );
            dirList->setFocus();
#endif
            }
            else
            {
Exemple #30
0
bool ExportDialog::isEps()
{
    QFileInfo inf(editFilename->text());
    if (inf.suffix().toLower()=="eps") return true;
    else return false;
}