Esempio n. 1
0
// loads/saves multiple lists to one binary file
int LoadList::loadBinaryMulti(const char * filename, int * numLists, int ** numListEntries, int *** listEntries, int offset)
{
  FILE * fin;
  fin = fopen(filename, "rb");
  if (!fin)
  {
    printf("Error: could not open list file %s.\n",filename);
    return 1;
  }

  int item = fread(numLists, sizeof(int), 1, fin);
  if (item != 1)
  {
    printf("Error: could not read the number of list.\n");
    return 1;
  }

  *numListEntries = (int*) malloc (sizeof(int) * *numLists);
  *listEntries = (int**) malloc (sizeof(int*) * *numLists);

  int code = 0;
  for(int i=0; i<*numLists; i++)
    code = code || loadBinary(fin, &((*numListEntries)[i]), &((*listEntries)[i]), offset);

  fclose(fin);

  return code;
}
Esempio n. 2
0
bool Bundle3D::load(const std::string& path)
{
    if (_path == path)
        return true;

    getModelRelativePath(path);

    bool ret = false;
    std::string ext = path.substr(path.length() - 4, 4);
    std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
    if (ext == ".c3t")
    {
        _isBinary = false;
        ret = loadJson(path);
    }
    else if (ext == ".c3b")
    {
        _isBinary = true;
        ret = loadBinary(path);
    }
    else
    {
        CCLOGINFO("%s is invalid file formate", path);
    }

    ret?(_path = path):(_path = "");

    return ret;
}
Esempio n. 3
0
LibraryBinary::LibraryBinary(const std::string & binaryPath)
    : _type(LibraryBinary::eLibraryTypeExternal)
    , _library(0)
    , _valid(false)
{
    loadBinary(binaryPath);
}
Esempio n. 4
0
KeyframeAnim::KeyframeAnim(const char *fname, const char *data, int len) :
	Object() {
	_fname = fname;

	if (len >= 4 && READ_BE_UINT32(data) == MKTAG('F','Y','E','K'))
		loadBinary(data, len);
	else {
		TextSplitter ts(data, len);
		loadText(ts);
	}
}
Esempio n. 5
0
Model::Model(const char *filename, const char *data, int len, const CMap *cmap) :
		_numMaterials(0), _numGeosets(0) {
	_fname = filename;

	if (len >= 4 && READ_BE_UINT32(data) == MKID_BE('LDOM'))
		loadBinary(data, cmap);
	else {
		TextSplitter ts(data, len);
		loadText(&ts, cmap);
	}
}
Esempio n. 6
0
LibraryBinary::LibraryBinary(const std::string & binaryPath,
                             const std::vector<std::string> & funcNames)
    : _type(LibraryBinary::eLibraryTypeExternal)
    , _library(0)
    , _valid(false)
{
    if ( !loadBinary(binaryPath) ) {
        return;
    }
    loadFunctions(funcNames);
}
Esempio n. 7
0
/**
 * @class Model
 */
Model::Model(const Common::String &filename, const char *data, int len, CMap *cmap, Model *parent) :
		Object(), _parent(parent), _numMaterials(0), _numGeosets(0), _cmap(cmap) {
	_fname = filename;

	if (g_grim->getGameType() == GType_MONKEY4) {
		Common::MemoryReadStream ms((const byte *)data, len);
		loadEMI(ms);
	} else if (len >= 4 && READ_BE_UINT32(data) == MKTAG('L','D','O','M'))
		loadBinary(data, cmap);
	else {
		TextSplitter ts(data, len);
		loadText(&ts, cmap);
	}

	Math::Vector3d max;

	_rootHierNode->update();
	bool first = true;
	for (int i = 0; i < _numHierNodes; ++i) {
		ModelNode &node = _rootHierNode[i];
		if (node._mesh) {
			Mesh &mesh = *node._mesh;
			//NOTE: Setting p to mesh._matrix._pos seems more similar to original
			// but, as in original, it also stops manny quite far away from the
			// bone wagon when approaching it from behind in set sg.
			// Using the node position looks instead more realistic, but, on the
			// other hand, it may not work right in all cases.
			Math::Vector3d p = node._matrix.getPosition();
			float x = p.x();
			float y = p.y();
			float z = p.z();
			for (int k = 0; k < mesh._numVertices * 3; k += 3) {
				if (first || mesh._vertices[k] + x < _bboxPos.x())
					_bboxPos.x() = mesh._vertices[k] + x;
				if (mesh._vertices[k + 1] + y < _bboxPos.y())
					_bboxPos.y() = mesh._vertices[k + 1] + y;
				if (mesh._vertices[k + 2] + z < _bboxPos.z())
					_bboxPos.z() = mesh._vertices[k + 2] + z;

				if (first || mesh._vertices[k] + x > max.x())
					max.x() = mesh._vertices[k] + x;
				if (mesh._vertices[k + 1] + y > max.y())
					max.y() = mesh._vertices[k + 1] + y;
				if (mesh._vertices[k + 2] + z > max.z())
					max.z() = mesh._vertices[k + 2] + z;

				first = false;
			}
		}
	}

	_bboxSize = max - _bboxPos;
}
Esempio n. 8
0
KeyframeAnim::KeyframeAnim(const Common::String &fname, Common::SeekableReadStream *data) :
	Object(), _fname(fname) {

	uint32 tag = data->readUint32BE();
	if (tag == MKTAG('F','Y','E','K'))
		loadBinary(data);
	else {
		data->seek(0, SEEK_SET);
		TextSplitter ts(fname, data);
		loadText(ts);
	}
}
Esempio n. 9
0
Set::Set(const Common::String &sceneName, const char *buf, int len) :
		PoolObject<Set, MKTAG('S', 'E', 'T', ' ')>(), _locked(false), _name(sceneName), _enableLights(false),
		_lightsConfigured(false) {

	if (len >= 7 && memcmp(buf, "section", 7) == 0) {
		TextSplitter ts(buf, len);
		loadText(ts);
	} else {
		Common::MemoryReadStream ms((const byte *)buf, len);
		loadBinary(&ms);
	}
}
Esempio n. 10
0
int LoadList::loadBinary(const char * filename, int * numListEntries, int ** listEntries, int offset)
{
  FILE * fin;
  fin = fopen(filename, "rb");
  if (!fin)
  {
    printf("Error: could not open list file %s.\n",filename);
    return 1;
  }

  int code = loadBinary(fin, numListEntries, listEntries, offset);
  fclose(fin);
  return code;
}
Esempio n. 11
0
/**
 * @class Model
 */
Model::Model(const Common::String &filename, Common::SeekableReadStream *data, CMap *cmap, Model *parent) :
		Object(), _parent(parent), _numMaterials(0), _numGeosets(0), _cmap(cmap) {
	_fname = filename;

	if (g_grim->getGameType() == GType_MONKEY4) {
		loadEMI(data);
	} else if (data->readUint32BE() == MKTAG('L','D','O','M'))
		loadBinary(data, cmap);
	else {
		data->seek(0, SEEK_SET);
		TextSplitter ts(data);
		loadText(&ts, cmap);
	}
	delete data;

	Math::Vector3d max;

	_rootHierNode->update();
	bool first = true;
	for (int i = 0; i < _numHierNodes; ++i) {
		ModelNode &node = _rootHierNode[i];
		if (node._mesh) {
			Mesh &mesh = *node._mesh;
			Math::Vector3d p = mesh._matrix.getPosition();
			float x = p.x();
			float y = p.y();
			float z = p.z();
			for (int k = 0; k < mesh._numVertices * 3; k += 3) {
				if (first || mesh._vertices[k] + x < _bboxPos.x())
					_bboxPos.x() = mesh._vertices[k] + x;
				if (first || mesh._vertices[k + 1] + y < _bboxPos.y())
					_bboxPos.y() = mesh._vertices[k + 1] + y;
				if (first || mesh._vertices[k + 2] + z < _bboxPos.z())
					_bboxPos.z() = mesh._vertices[k + 2] + z;

				if (first || mesh._vertices[k] + x > max.x())
					max.x() = mesh._vertices[k] + x;
				if (first || mesh._vertices[k + 1] + y > max.y())
					max.y() = mesh._vertices[k + 1] + y;
				if (first || mesh._vertices[k + 2] + z > max.z())
					max.z() = mesh._vertices[k + 2] + z;

				first = false;
			}
		}
	}

	_bboxSize = max - _bboxPos;
}
Esempio n. 12
0
cv::Mat FileUtil::loadDescriptors(const std::string &descriptorDir,
                                  const std::string &labelFile,
                                  const uint32_t maxDescriptors,
                                  bool random)
{
    std::vector<std::pair<std::string, int32_t>> filesWithLabels = getFilesFromLabelFile(labelFile);

    int32_t maxDescriptorsPerFile = maxDescriptors / filesWithLabels.size();

    cv::Mat allDescriptors;
    int32_t idx = 0;

    while((allDescriptors.rows < maxDescriptors || maxDescriptors <= 0) && idx < filesWithLabels.size()) {
        cv::Mat desc = loadBinary(filesWithLabels[idx].first);

        int32_t rows;
        if(maxDescriptors <= 0) {
            rows = desc.rows;
        } else {
            rows = std::min(desc.rows, maxDescriptorsPerFile);
        }

        std::vector<int32_t> indices;
        allDescriptors.reserve(rows);
        if(random) {
            indices = Range<int32_t>::random(0, rows);
        } else {
            indices = Range<int32_t>::unique(0, rows);
        }

        for(size_t i = 0; i < indices.size(); ++i) {
            if(desc.cols == allDescriptors.cols || allDescriptors.empty()) {
                allDescriptors.push_back(desc.row(indices[i]));
            }
        }
        ++idx;
    }

    return allDescriptors;
}
Esempio n. 13
0
void MainWindow::showEvent(QShowEvent *event) {
  QMainWindow::showEvent(event);

  if (shown) return;
  shown = true;

  if (geometry.isEmpty()) {
    resize(900, 500);
    Util::centerWidget(this);
  }
  else {
    restoreGeometry(geometry);
  }

  // Load specified files or open file dialog.
  if (startupFiles.isEmpty()) {
    openBinary();
  }
  else {
    foreach (const auto &file, startupFiles) {
      loadBinary(file);
    }
  }
Esempio n. 14
0
//--------------------
//基本テスト
void basic_test()
{
	std::printf("\n");
	std::printf("================================================================================\n");
	std::printf("[ Test for serialization basic ]\n");
	std::printf("\n");

	//テストデータ作成
	std::printf("----------------------------------------\n");
	std::printf("[ Make data ]\n");
	basicTestData data;
	data.m_memberA = 123;
	data.m_memberB = 4.56f;
	data.m_memberC[0] = 78;
	data.m_memberC[1] = 90;
	data.m_memberD.m_item1 = 987;
	data.m_memberD.m_item2 = 654;

	//テストデータの内容表示
	std::printf("----------------------------------------\n");
	std::printf("[ Print data(1) : before save ]\n");
	auto print_data = [](basicTestData& data)
	{
		std::printf("basicTestData\n");
		std::printf("  .m_memberA = %d\n", data.m_memberA);
		std::printf("  .m_memberB = %.2f\n", data.m_memberB);
		std::printf("  .m_memberC = { %d, %d }\n", data.m_memberC[0], data.m_memberC[1]);
		std::printf("  .m_memberD\n");
		std::printf("      .m_item1 = %d\n", data.m_memberD.m_item1);
		std::printf("      .m_item2 = %d\n", data.m_memberD.m_item2);
	};
	print_data(data);
	
	//バイナリ形式セーブデータをセーブ
	std::printf("----------------------------------------\n");
	std::printf("[ Save binary ]\n");
	saveBinary(data);

	//テキスト形式セーブデータをセーブ
	std::printf("----------------------------------------\n");
	std::printf("[ Save text ]\n");
	saveText(data);

	//一旦データをクリア
	std::memset(&data, 0, sizeof(data));

	//テストデータの内容表示
	std::printf("----------------------------------------\n");
	std::printf("[ Print data(2) : before load ]\n");
	print_data(data);

	//バイナリ形式セーブデータをロード
	std::printf("----------------------------------------\n");
	std::printf("[ Load binary ]\n");
	loadBinary(data);

#if 0//未実装
	//テキスト形式セーブデータをロード
	std::printf("----------------------------------------\n");
	std::printf("[ Load text ]\n");
	loadText(data);
#endif
	
	//テストデータの内容表示
	std::printf("----------------------------------------\n");
	std::printf("[ Print data(3) : after load ]\n");
	print_data(data);

	std::printf("\n");
	std::printf("================================================================================\n");
	std::printf("finish.\n");
}
Esempio n. 15
0
/*
	char const * retrieveBinaryCache(char const* Path)
	{
		return 0;
	}

	enum
	{
		PROGRAM_SEPARATE_BIT = (1 << 0),
		PROGRAM_CACHE_BIT = (1 << 1),
		PROGRAM_BYPASS_CACHE_BIT = (1 << 2)
	};

	bool hasProgramBinarySPIRVSupport()
	{
		GLint NumProgramBinaryFormats(0);
		glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &NumProgramBinaryFormats);

		std::vector<GLint> ProgramBinaryFormats(static_cast<std::size_t>(NumProgramBinaryFormats));
		glGetIntegerv(GL_PROGRAM_BINARY_FORMATS, &ProgramBinaryFormats[0]);

		for(std::size_t FormatIndex = 0; FormatIndex < ProgramBinaryFormats.size(); ++FormatIndex)
		{
			if(ProgramBinaryFormats[FormatIndex] == GL_PROGRAM_BINARY_SPIR_V)
				return true;
		}

		return false;
	}

	bool isProgramBinarySPIRV(GLubyte * binary)
	{
		return *reinterpret_cast<GLuint*>(binary) == 0x07230203;
	}

	GLuint createProgram(char const* Path, GLbitfield Flags)
	{
		assert(HasProgramBinarySPIRVSupport());
		assert(Path);

		if(!(Flags & PROGRAM_BYPASS_CACHE_BIT))
			Path = retrieveBinaryCache(Path);

		GLenum Format = 0;
		GLint Size = 0;
		std::vector<glm::byte> Data;
		if(!loadBinary(Path, Format, Data, Size))
			return 0;

		assert((isProgramBinarySPIRV(&Data[0]) && Format == GL_PROGRAM_BINARY_SPIR_V) || Format != GL_PROGRAM_BINARY_SPIR_V);

		GLuint ProgramName = glCreateProgram();
		glProgramParameteri(ProgramName, GL_PROGRAM_SEPARABLE, Flags & PROGRAM_SEPARATE_BIT ? GL_TRUE : GL_FALSE);
		glProgramParameteri(ProgramName, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, Flags & PROGRAM_CACHE_BIT ? GL_TRUE : GL_FALSE);
		glProgramBinary(ProgramName, Format, &Data[0], Size);
		glLinkProgram(ProgramName);

		return ProgramName;
	}
*/
	bool initProgram()
	{
		bool Validated = true;
		GLint Success = 0;

		glGenProgramPipelines(1, &PipelineName);

		ProgramName[program::VERT] = glCreateProgram();
		glProgramParameteri(ProgramName[program::VERT], GL_PROGRAM_SEPARABLE, GL_TRUE);
		glProgramParameteri(ProgramName[program::VERT], GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);

		ProgramName[program::GEOM] = glCreateProgram();
		glProgramParameteri(ProgramName[program::GEOM], GL_PROGRAM_SEPARABLE, GL_TRUE);
		glProgramParameteri(ProgramName[program::GEOM], GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);

		ProgramName[program::FRAG] = glCreateProgram();
		glProgramParameteri(ProgramName[program::FRAG], GL_PROGRAM_SEPARABLE, GL_TRUE);
		glProgramParameteri(ProgramName[program::FRAG], GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);

		{
			GLenum Format = 0;
			GLint Size = 0;
			std::vector<glm::byte> Data;
			if(loadBinary(getDataDirectory() + VERT_PROGRAM_BINARY, Format, Data, Size))
			{
				glProgramBinary(ProgramName[program::VERT], Format, &Data[0], Size);
				glGetProgramiv(ProgramName[program::VERT], GL_LINK_STATUS, &Success);
				Validated = Validated && Success == GL_TRUE;
			}
		}

		{
			GLenum Format = 0;
			GLint Size = 0;
			std::vector<glm::byte> Data;
			if(loadBinary(getDataDirectory() + GEOM_PROGRAM_BINARY, Format, Data, Size))
			{
				glProgramBinary(ProgramName[program::GEOM], Format, &Data[0], Size);
				glGetProgramiv(ProgramName[program::GEOM], GL_LINK_STATUS, &Success);
				Validated = Validated && Success == GL_TRUE;
			}
		}

		{
			GLenum Format = 0;
			GLint Size = 0;
			std::vector<glm::byte> Data;
			if(loadBinary(getDataDirectory() + FRAG_PROGRAM_BINARY, Format, Data, Size))
			{
				glProgramBinary(ProgramName[program::FRAG], Format, &Data[0], Size);
				glGetProgramiv(ProgramName[program::FRAG], GL_LINK_STATUS, &Success);
				Validated = Validated && Success == GL_TRUE;
			}
		}

		compiler Compiler;

		if(Validated && !Success)
		{
			GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE);

			glAttachShader(ProgramName[program::VERT], VertShaderName);
			glLinkProgram(ProgramName[program::VERT]);
		}

		if(Validated && !Success)
		{
			GLuint GeomShaderName = Compiler.create(GL_GEOMETRY_SHADER, getDataDirectory() + GEOM_SHADER_SOURCE);

			glAttachShader(ProgramName[program::GEOM], GeomShaderName);
			glLinkProgram(ProgramName[program::GEOM]);
		}

		if(Validated && !Success)
		{
			GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE);

			glAttachShader(ProgramName[program::FRAG], FragShaderName);
			glLinkProgram(ProgramName[program::FRAG]);
		}

		if(Validated)
		{
			glUseProgramStages(PipelineName, GL_VERTEX_SHADER_BIT, ProgramName[program::VERT]);
			glUseProgramStages(PipelineName, GL_GEOMETRY_SHADER_BIT, ProgramName[program::GEOM]);
			glUseProgramStages(PipelineName, GL_FRAGMENT_SHADER_BIT, ProgramName[program::FRAG]);
			Validated = Validated && this->checkError("initProgram - stage");
		}

		if(Validated)
		{
			Validated = Validated && Compiler.checkProgram(ProgramName[program::VERT]);
			Validated = Validated && Compiler.checkProgram(ProgramName[program::GEOM]);
			Validated = Validated && Compiler.checkProgram(ProgramName[program::FRAG]);
		}

		if(Validated)
		{
			UniformMVP = glGetUniformLocation(ProgramName[program::VERT], "MVP");
			UniformDiffuse = glGetUniformLocation(ProgramName[program::FRAG], "Diffuse");
		}

		saveProgram(ProgramName[program::VERT], getDataDirectory() + VERT_PROGRAM_BINARY);
		saveProgram(ProgramName[program::GEOM], getDataDirectory() + GEOM_PROGRAM_BINARY);
		saveProgram(ProgramName[program::FRAG], getDataDirectory() + FRAG_PROGRAM_BINARY);

		return Validated && this->checkError("initProgram");
	}
Esempio n. 16
0
/*
* Loads a resource from the stream, from originalHandle index to destHandle placeholder.
*/
bool Syscall::loadResource(Stream& file, MAHandle originalHandle, MAHandle destHandle)  {

    if(!file.isOpen())
    {
        return false;
    }

    if ((resourceType == NULL) || (resourceSize == NULL) || (resourceOffset == NULL))
    {
        return false;
    }

    int type = resourceType[originalHandle - 1];
    int size = resourceSize[originalHandle - 1];
    int offset = resourceOffset[originalHandle - 1];
    int rI = destHandle;

    if ( resources.is_loaded(rI) )
    {
        return true;
    }

    TEST(file.seek(Seek::Start, offset));

    switch(type) {
    case RT_BINARY:
    {
#ifndef _android
        MemStream* ms = new MemStream(size);
#else
        char* b = loadBinary(rI, size);
        MemStream* ms = new MemStream(b, size);
#endif
        TEST(file.readFully(*ms));
        ROOM(resources.dadd_RT_BINARY(rI, ms));
#ifdef _android
        checkAndStoreAudioResource(rI);
#endif
    }
    break;
    case RT_IMAGE:
    {
        MemStream b(size);
        TEST(file.readFully(b));
#ifndef _android
        // On all platforms except Android, we load and add
        // the image data. "dadd" means "delete and add",
        // and is defined in runtimes\cpp\base\ResourceArray.h
        RT_IMAGE_Type* image = loadImage(b);
        if(!image)
            BIG_PHAT_ERROR(ERR_IMAGE_LOAD_FAILED);
        ROOM(resources.dadd_RT_IMAGE(rI, image));
#else
        // On Android images are stored on the Java side.
        // Here we allocate a dummy array (real image is
        // in a table in Java) so that the resource handling,
        // like deleting resources, will work also on Android.
        // The actual image will be garbage collected on
        // Android when a resource is replaced in the Java table.
        ROOM(resources.dadd_RT_IMAGE(rI, new int[1]));
        int pos;
        file.tell(pos);
        loadImage(
            rI,
            pos - size,
            size,
            Base::gSyscall->getReloadHandle());
#endif
    }
    break;
    case RT_SPRITE:
    {
        DAR_USHORT(indexSource);
        DAR_USHORT(left);
        DAR_USHORT(top);
        DAR_USHORT(width);
        DAR_USHORT(height);
        DAR_SHORT(cx);
        DAR_SHORT(cy);
#ifndef _android
        ROOM(resources.dadd_RT_IMAGE(rI, loadSprite(resources.get_RT_IMAGE(indexSource),
                                     left, top, width, height, cx, cy)));
#endif
    }
    break;
    default:
        LOG("Cannot load resource type %d.", type);
    }
    return true;
}
Esempio n. 17
0
/*
* Loads all resources from the given buffer.
*/
bool Syscall::loadResourcesFromBuffer(Stream& file, const char* aFilename)  {
    bool hasResources = true;
    if(!file.isOpen())
        hasResources = false;
    else {
        int len, pos;
        TEST(file.length(len));
        TEST(file.tell(pos));
        if(len == pos)
            hasResources = false;
    }
    if(!hasResources/* && aFilename != NULL*/) {
        resources.init(0);
        return true;
    }

#define MATCH_BYTE(c) { DAR_UBYTE(b); if(b != c) { FAIL; } }
    MATCH_BYTE('M');
    MATCH_BYTE('A');
    MATCH_BYTE('R');
    MATCH_BYTE('S');

    DAR_UVINT(nResources);
    DAR_UVINT(rSize);
    resources.init(nResources);

    // rI is the resource index.
    int rI = 1;

    while(true) {
        DAR_UBYTE(type);
        if(type == 0)
            break;

        //dispose flag

        DAR_UVINT(size);
        LOG_RES("Type %i, size %i\n", type, size);

        switch(type) {
        case RT_BINARY:
        {
#ifndef _android
            MemStream* ms = new MemStream(size);
#else
            char* b = loadBinary(rI, size);
            MemStream* ms = new MemStream(b, size);
#endif
            TEST(file.readFully(*ms));
            ROOM(resources.dadd_RT_BINARY(rI, ms));
#ifdef _android
            checkAndStoreAudioResource(rI);
#endif
        }
        break;
        case RT_UBIN:
        {
            int pos;
            MYASSERT(aFilename, ERR_RES_LOAD_UBIN);
            TEST(file.tell(pos));
#ifndef _android
            ROOM(resources.dadd_RT_BINARY(rI,
                                          new LimitedFileStream(aFilename, pos, size)));
#else
            // Android loads ubins by using JNI.
            loadUBinary(rI, pos, size);
            ROOM(resources.dadd_RT_BINARY(rI,
                                          new LimitedFileStream(
                                              aFilename,
                                              pos,
                                              size,
                                              getJNIEnvironment(),
                                              getJNIThis())));
#endif
            TEST(file.seek(Seek::Current, size));
        }
        break;
        case RT_PLACEHOLDER:
            ROOM(resources.dadd_RT_PLACEHOLDER(rI, NULL));
            break;
        case RT_IMAGE:
        {
            MemStream b(size);
            TEST(file.readFully(b));
#ifndef _android
            // On all platforms except Android, we load and add
            // the image data. "dadd" means "delete and add",
            // and is defined in runtimes\cpp\base\ResourceArray.h
            RT_IMAGE_Type* image = loadImage(b);
            if(!image)
                BIG_PHAT_ERROR(ERR_IMAGE_LOAD_FAILED);
            ROOM(resources.dadd_RT_IMAGE(rI, image));
#else
            // On Android images are stored on the Java side.
            // Here we allocate a dummy array (real image is
            // in a table in Java) so that the resource handling,
            // like deleting resources, will work also on Android.
            // The actual image will be garbage collected on
            // Android when a resource is replaced in the Java table.
            ROOM(resources.dadd_RT_IMAGE(rI, new int[1]));
            int pos;
            file.tell(pos);
            loadImage(
                rI,
                pos - size,
                size,
                Base::gSyscall->getReloadHandle());
#endif
        }
        break;
        case RT_SPRITE:
        {
            DAR_USHORT(indexSource);
            DAR_USHORT(left);
            DAR_USHORT(top);
            DAR_USHORT(width);
            DAR_USHORT(height);
            DAR_SHORT(cx);
            DAR_SHORT(cy);
#ifndef _android
            ROOM(resources.dadd_RT_IMAGE(rI, loadSprite(resources.get_RT_IMAGE(indexSource),
                                         left, top, width, height, cx, cy)));
#endif
        }
        break;
        case RT_LABEL:
        {
            MemStream b(size);
            TEST(file.readFully(b));
            ROOM(resources.dadd_RT_LABEL(rI, new Label((const char*)b.ptr(), rI)));
        }
        break;

#ifdef LOGGING_ENABLED
        case 99:  //testtype
#define DUMP_UVI { DAR_UVINT(u); LOG_RES("u %i\n", u); }
#define DUMP_SVI { DAR_SVINT(s); LOG_RES("s %i\n", s); }
            DUMP_UVI;
            DUMP_UVI;
            DUMP_UVI;
            DUMP_SVI;
            DUMP_SVI;
            DUMP_SVI;
            DUMP_SVI;
            DUMP_SVI;
            DUMP_SVI;
            break;
#endif
        default:
            TEST(file.seek(Seek::Current, size));
        }
        rI++;
    }
    if(rI != nResources + 1) {
        LOG("rI %i, nR %i\n", rI, nResources);
        BIG_PHAT_ERROR(ERR_RES_FILE_INCONSISTENT);
    }
    LOG_RES("ResLoad complete\n");
    return true;
}
Esempio n. 18
0
int main(int argc, char **argv)
{
    FILE *fp;
    int width, height, alpha;
    unsigned char *image, *fb;
    SDL_Surface *screen;
    struct triangles *triangles, *best, *absbest;
    long long diff;
    float percdiff, bestdiff;

    /* Initialization */
    srand(time(NULL));
    state.max_shapes = 64;
    state.max_shapes_incremental = 1;
    state.temperature = 0.10;
    state.generation = 0;
    state.absbestdiff = 100; /* 100% is worst diff possible. */

    /* Check arity and parse additional args if any. */
    if (argc < 4) {
        showHelp(argv[0]);
        exit(1);
    }

    if (argc > 4) {
        int j;
        for (j = 4; j < argc; j++) {
            int moreargs = j+1 < argc;

            if (!strcmp(argv[j],"--use-triangles") && moreargs) {
                opt_use_triangles = atoi(argv[++j]);
            } else if (!strcmp(argv[j],"--use-circles") && moreargs) {
                opt_use_circles = atoi(argv[++j]);
            } else if (!strcmp(argv[j],"--max-shapes") && moreargs) {
                state.max_shapes = atoi(argv[++j]);
            } else if (!strcmp(argv[j],"--initial-shapes") && moreargs) {
                state.max_shapes_incremental = atoi(argv[++j]);
            } else if (!strcmp(argv[j],"--mutation-rate") && moreargs) {
                opt_mutation_rate = atoi(argv[++j]);
            } else if (!strcmp(argv[j],"--restart")) {
                opt_restart = 1;
            } else if (!strcmp(argv[j],"--help")) {
                showHelp(argv[0]);
            } else {
                fprintf(stderr,"Invalid options.");
                showHelp(argv[0]);
                exit(1);
            }
        }
    }

    /* Sanity check. */
    if (state.max_shapes_incremental > state.max_shapes)
        state.max_shapes = state.max_shapes_incremental;
    if (opt_mutation_rate > 1000)
        opt_mutation_rate = 1000;

    /* Load the PNG in memory. */
    fp = fopen(argv[1],"rb");
    if (!fp) {
        perror("Opening PNG file");
        exit(1);
    }
    if ((image = PngLoad(fp,&width,&height,&alpha)) == NULL) {
        printf("Can't load the specified image.");
        exit(1);
    }

    printf("Image %d %d, alpha:%d at %p\n", width, height, alpha, image);
    fclose(fp);

    /* Initialize SDL and allocate our arrays of triangles. */
    screen = sdlInit(width,height,0);
    fb = malloc(width*height*3);
    triangles = mkRandomtriangles(state.max_shapes,width,height);
    best = mkRandomtriangles(state.max_shapes,width,height);
    absbest = mkRandomtriangles(state.max_shapes,width,height);
    state.absbestdiff = bestdiff = 100;

    /* Load the binary file if any. */
    if (!opt_restart) {
        loadBinary(argv[2],best);
    } else {
        best->inuse = state.max_shapes_incremental;
    }
    absbest->inuse = best->inuse;
    memcpy(absbest->triangles,best->triangles,
        sizeof(struct triangle)*best->count);

    /* Show the current evolved image and the real image for one scond each. */
    memset(fb,0,width*height*3);
    drawtriangles(fb,width,height,best);
    sdlShowRgb(screen,fb,width,height);
    sleep(1);
    sdlShowRgb(screen,image,width,height);
    sleep(1);

    /* Evolve the current solution using simulated annealing. */
    while(1) {
        state.generation++;
        if (state.temperature > 0 && !(state.generation % 10)) {
            state.temperature -= 0.00001;
            if (state.temperature < 0) state.temperature = 0;
        }

        /* From time to time allow the current solution to use one more
         * triangle, up to the configured max number. */
        if ((state.generation % 1000) == 0) {
            if (state.max_shapes_incremental < triangles->count &&
                triangles->inuse > state.max_shapes_incremental-1)
            {
                state.max_shapes_incremental++;
            }
        }

        /* Copy what is currenly the best solution, and mutate it. */
        memcpy(triangles->triangles,best->triangles,
            sizeof(struct triangle)*best->count);
        triangles->inuse = best->inuse;
        mutatetriangles(triangles,10,width,height);

        /* Draw the mutated solution, and check what is its fitness.
         * In our case the fitness is the difference bewteen the target
         * image and our image. */
        memset(fb,0,width*height*3);
        drawtriangles(fb,width,height,triangles);
        diff = computeDiff(image,fb,width,height);

        /* The percentage of difference is calculate taking the ratio between
         * the maximum difference and the current difference.
         * The magic constant 422 is actually the max difference between
         * two pixels as r,g,b coordinates in the space, so sqrt(255^2*3). */
        percdiff = (float)diff/(width*height*442)*100;
        if (percdiff < bestdiff ||
            (state.temperature > 0 &&
             ((float)rand()/RAND_MAX) < state.temperature &&
             (percdiff-state.absbestdiff) < 2*state.temperature))
        {
            /* Save what is currently our "best" solution, even if actually
             * this may be a jump backward depending on the temperature.
             * It will be used as a base of the next iteration. */
            best->inuse = triangles->inuse;
            memcpy(best->triangles,triangles->triangles,
                sizeof(struct triangle)*best->count);

            if (percdiff < bestdiff) {
                /* We always save a copy of the absolute best solution we found
                 * so far, after some generation without finding anything better
                 * we may jump back to that solution.
                 *
                 * We also use the absolute best solution to save the program
                 * state in the binary file, and as SVG output. */
                absbest->inuse = best->inuse;
                memcpy(absbest->triangles,best->triangles,
                    sizeof(struct triangle)*best->count);
                state.absbestdiff = percdiff;
            }

            printf("Diff is %f%% (inuse:%d, max:%d, gen:%lld, temp:%f)\n",
                percdiff,
                triangles->inuse,
                state.max_shapes_incremental,
                state.generation,
                state.temperature);

            bestdiff = percdiff;
            sdlShowRgb(screen,fb,width,height);
        }
        processSdlEvents();

        /* From time to time save the current state into a binary save
         * and produce an SVG of the current solution. */
        if ((state.generation % 100) == 0) {
            saveSvg(argv[3],absbest,width,height);
            saveBinary(argv[2],absbest);
        }
    }
    return 0;
}
Esempio n. 19
0
bool
LadderList::load()
{
  return loadBinary();
}
Esempio n. 20
0
RString 
File::loadAscii()
{
  return new String(RcharArray(loadBinary()));
}