C++ Code Examples for load data

60 C++ code examples are found related to "load data". These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Project: c_cpp_compiler   Author: tranleduy2000   File: load_flac.c    License: GNU General Public License v3.0 6 votes vote down vote up
static FLAC__StreamDecoderReadStatus flac_read_load_cb(
                                    const FLAC__StreamDecoder *decoder,
                                    FLAC__byte buffer[],
                                    size_t *bytes,
                                    void *client_data)
{
    // make sure there is something to be reading
    if (*bytes > 0) {
        FLAC_SDL_Data *data = (FLAC_SDL_Data *)client_data;

        *bytes = SDL_RWread (data->sdl_src, buffer, sizeof (FLAC__byte),
                                *bytes);

        if (*bytes == 0) { // error or no data was read (EOF)
            return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
        } else { // data was read, continue
            return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
        }
    } 
Example 2
Project: nCine   Author: nCine   File: EmscriptenLocalFile.cpp    License: MIT License 6 votes vote down vote up
void loadFile(const char *accept, FileDataCallbackType *filesReadyCallback, LoadingCallbackType *loadingCallback, void *context)
	{
		// Create file input element which will display a native file dialog.
		emscripten::val document = emscripten::val::global("document");
		emscripten::val input = document.call<emscripten::val>("createElement", std::string("input"));
		input.set("type", "file");
		input.set("style", "display:none");
		input.set("accept", emscripten::val(accept));

		// Set JavaScript `onchange` callback which will be called on selected file(s),
		// and also forward the user C callback pointers so that the `onchange`
		// callback can call it. (The `onchange` callback is actually a C function
		// exposed to JavaScript with EMSCRIPTEN_BINDINGS).
		input.set("onchange", emscripten::val::module_property("jsReadFiles"));
		input.set("data-filesReadyCallback", emscripten::val(size_t(filesReadyCallback)));
		input.set("data-loadingCallback", emscripten::val(size_t(loadingCallback)));
		input.set("data-callbackContext", emscripten::val(size_t(context)));

		// Programatically activate input
		emscripten::val body = document["body"];
		body.call<void>("appendChild", input);
		input.call<void>("click");
		body.call<void>("removeChild", input);
	} 
Example 3
Project: fonline   Author: cvet   File: 3dStuff.cpp    License: MIT License 6 votes vote down vote up
void MeshData::Load(DataReader& reader)
{
    uint len = 0;
    reader.ReadPtr(&len, sizeof(len));
    Vertices.resize(len);
    reader.ReadPtr(&Vertices[0], len * sizeof(Vertices[0]));
    reader.ReadPtr(&len, sizeof(len));
    Indices.resize(len);
    reader.ReadPtr(&Indices[0], len * sizeof(Indices[0]));
    reader.ReadPtr(&len, sizeof(len));
    DiffuseTexture.resize(len);
    reader.ReadPtr(&DiffuseTexture[0], len);
    reader.ReadPtr(&len, sizeof(len));
    SkinBones.resize(len);
    reader.ReadPtr(&SkinBones[0], len * sizeof(SkinBones[0]));
    reader.ReadPtr(&len, sizeof(len));
    SkinBoneOffsets.resize(len);
    reader.ReadPtr(&SkinBoneOffsets[0], len * sizeof(SkinBoneOffsets[0]));
    SkinBones.resize(SkinBoneOffsets.size());
} 
Example 4
Project: ps4delta   Author: Force67   File: UnSELF.cpp    License: GNU General Public License v2.0 6 votes vote down vote up
bool LoadData()
		{
			// align position
			uint64_t pos = (file.Tell() + 0xF) & ~0xF;
	
			// todo: check is always 65?
			uint64_t offset = file.Seek(pos + 0x41, utl::seekMode::seek_set);

#ifdef DELTA_DBG
		//	std::printf(__FUNCTION__ " offset %llx\n", offset);
#endif

			if (offset < file.GetSize()) {

				size_t delta = file.GetSize() - offset;
				data.resize(delta);
			
				return file.Read(data);
			}

			return false;
		} 
Example 5
Project: rubyserver   Author: OLDtherubyproject   File: iologindata.cpp    License: GNU General Public License v2.0 6 votes vote down vote up
Account IOLoginData::loadAccount(uint32_t accno)
{
	Account account;

	std::ostringstream query;
	query << "SELECT `id`, `name`, `password`, `type`, `premdays`, `lastday` FROM `accounts` WHERE `id` = " << accno;
	DBResult_ptr result = Database::getInstance().storeQuery(query.str());
	if (!result) {
		return account;
	}

	account.id = result->getNumber<uint32_t>("id");
	account.name = result->getString("name");
	account.accountType = static_cast<AccountType_t>(result->getNumber<int32_t>("type"));
	account.premiumDays = result->getNumber<uint16_t>("premdays");
	account.lastDay = result->getNumber<time_t>("lastday");
	return account;
} 
Example 6
Project: BrickGame   Author: lfeng1420   File: CCDataReaderHelper.cpp    License: MIT License 6 votes vote down vote up
void DataReaderHelper::loadData()
{
    AsyncStruct *pAsyncStruct = nullptr;

    while (true)
    {
        std::queue<AsyncStruct *> *pQueue = _asyncStructQueue;
        _asyncStructQueueMutex.lock(); // get async struct from queue
        if (pQueue->empty())
        {
            _asyncStructQueueMutex.unlock();
            if (need_quit)
            {
                break;
            }
            else
            {
				std::unique_lock<std::mutex> lk(_sleepMutex);
				_sleepCondition.wait(lk);
                continue;
            }
        }
        else
        { 
Example 7
Project: c2gQtWS_x   Author: ekke   File: imageloader.cpp    License: The Unlicense 6 votes vote down vote up
void ImageLoader::loadSpeaker(QObject* dataObject)
{
    QNetworkAccessManager* netManager = new QNetworkAccessManager(this);

    const QUrl url(m_imageUrl);
    QNetworkRequest request(url);
    // stores the object so we can catch it later
    request.setOriginatingObject(dataObject);

    // QtCon redirects Speaker Images to https://
    // to avoid ssl errors:
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    request.setSslConfiguration(conf);

    QNetworkReply* reply = netManager->get(request);
    connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));
} 
Example 8
Project: EXEgesis   Author: google   File: microarchitectures_test.cc    License: Apache License 2.0 6 votes vote down vote up
void CheckCPU(const char* uarch_id, int num_port_masks,
              const std::string& load_store_address_generation_ports,
              const std::string& store_address_generation_ports,
              const std::string& store_data_ports) {
  const auto& uarch = MicroArchitecture::FromIdOrDie(uarch_id);
  EXPECT_EQ(uarch.port_masks().size(), num_port_masks);
  const PortMask* mask = uarch.load_store_address_generation();
  ASSERT_NE(mask, nullptr);
  EXPECT_EQ(mask->ToString(), load_store_address_generation_ports);
  mask = uarch.store_address_generation();
  ASSERT_NE(mask, nullptr);
  EXPECT_EQ(mask->ToString(), store_address_generation_ports);
  mask = uarch.store_data();
  ASSERT_NE(mask, nullptr);
  EXPECT_EQ(mask->ToString(), store_data_ports);
  EXPECT_FALSE(uarch.IsProtectedMode(-1));
  EXPECT_TRUE(uarch.IsProtectedMode(0));
  EXPECT_FALSE(uarch.IsProtectedMode(3));
  EXPECT_FALSE(uarch.IsProtectedMode(15));
} 
Example 9
Project: coolq-telegram-bot-x   Author: JogleLew   File: webpdec.c    License: GNU General Public License v3.0 6 votes vote down vote up
int LoadWebP(const char* const in_file,
             const uint8_t** data, size_t* data_size,
             WebPBitstreamFeatures* bitstream) {
  VP8StatusCode status;
  WebPBitstreamFeatures local_features;
  if (!ImgIoUtilReadFile(in_file, data, data_size)) return 0;

  if (bitstream == NULL) {
    bitstream = &local_features;
  }

  status = WebPGetFeatures(*data, *data_size, bitstream);
  if (status != VP8_STATUS_OK) {
    free((void*)*data);
    *data = NULL;
    *data_size = 0;
    PrintWebPError(in_file, status);
    return 0;
  }
  return 1;
} 
Example 10
Project: HSCC   Author: CGCL-codes   File: statdyn_tool.cpp    License: GNU General Public License v2.0 6 votes vote down vote up
VOID onImageLoad(IMG img, VOID *data)
{
    SYM sym;

    if (IMG_IsMainExecutable(img))
    {
        bool foundStatic = false;
        bool foundDynamic = false;
        for (sym = IMG_RegsymHead(img); SYM_Valid(sym); sym = SYM_Next(sym))
        {
            if (SYM_Name(sym).find("statdyn_app_staticFunction") != string::npos)
            {
                assert(SYM_Dynamic(sym) == false);
                foundStatic = true;
            }
            if (SYM_Name(sym).find("statdyn_app_dynamicFunction") != string::npos)
            {
                assert(SYM_Dynamic(sym) == true);
                foundDynamic = true;
            }
        }
        assert(foundStatic == true);
        assert(foundDynamic == true);
    }
} 
Example 11
Project: holodec   Author: Cararasu   File: Main.cpp    License: MIT License 6 votes vote down vote up
File* Main::loadDataFromFile (HString file) {
	std::ifstream t (file.cstr(), std::ios_base::binary);
	size_t size;
	std::vector<uint8_t> data;
	if (t) {
		t.seekg (0, t.end);
		size = (size_t) t.tellg();
		data.resize(size);

		t.seekg (0, t.beg);

		uint64_t offset = 0;
		while (offset < size) {
			t.read((char*)data.data() + offset, size);
			uint64_t read = t.gcount();
			if (read == 0)
				break;
			offset += read;
			printf("Read %zu chars\n", t.gcount());
		}
		return new File(file, data);
	}
	return nullptr;
} 
Example 12
Project: lullaby   Author: google   File: model_asset.cc    License: Apache License 2.0 6 votes vote down vote up
void ModelAsset::OnLoad(const std::string& filename, std::string* data) {
  flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t*>(data->data()),
                                 data->size(), 64 /* max_depth */,
                                 1000000 /* max_tables */,
                                 false /* check_alignment */);
  if (!verifier.VerifyBuffer<ModelDef>()) {
    LOG(DFATAL) << filename << " is an invalid model_asset.";
    return;
  }

  model_def_.Set(std::move(*data));
  if (!model_def_) {
    return;
  }
  id_ = Hash(filename);
  PrepareMesh();
  PrepareMaterials();
  PrepareTextures();
  PrepareSkeleton();
} 
Example 13
Project: UE4-Cpp-Tutorials   Author: orfeasel   File: TP_ThirdPersonCharacter.cpp    License: MIT License 6 votes vote down vote up
bool ATP_ThirdPersonCharacter::LoadData()
{
	TArray<uint8> BinaryArray;

	//load disk data to binary array
	if (!FFileHelper::LoadFileToArray(BinaryArray, TEXT(SAVEDATAFILENAME))) return false;

	if (BinaryArray.Num() <= 0) return false;

	//Memory reader is the archive that we're going to use in order to read the loaded data
	FMemoryReader FromBinary = FMemoryReader(BinaryArray, true);
	FromBinary.Seek(0);

	SaveLoadData(FromBinary, Health, CurrentAmmo, RandomLocation);

	//Empty the buffer's contents
	FromBinary.FlushCache();
	BinaryArray.Empty();
	//Close the stream
	FromBinary.Close();

	return true;
} 
Example 14
Project: firebase-cpp-sdk   Author: firebase   File: auth_desktop_test.cc    License: Apache License 2.0 6 votes vote down vote up
bool WaitOnLoadPersistence(AuthData* auth_data) {
  bool load_finished = false;
  int load_wait_counter = 0;
  while (!load_finished) {
    if (load_wait_counter >= kWaitForLoadMaxTryout) {
      break;
    }
    load_wait_counter++;
    firebase::internal::Sleep(1);
    {
      MutexLock lock(auth_data->listeners_mutex);
      load_finished = !auth_data->persistent_cache_load_pending;
    }
  }
  return load_finished;
} 
Example 15
Project: Flux   Author: JulianThijssen   File: Texture.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
bool loadTextureFromFile(Path path, int& width, int& height, TextureType type, void** data) {
        int bpp;
        switch (type) {
        case COLOR: *data = stbi_load(path.str().c_str(), &width, &height, &bpp, STBI_rgb_alpha); break;
        case GREYSCALE: *data = stbi_load(path.str().c_str(), &width, &height, &bpp, STBI_grey); break;
        case HDR: *data = stbi_loadf(path.str().c_str(), &width, &height, &bpp, STBI_rgb_alpha); break;
        }

        if (!*data) {
            Log::error("Failed to load image at: " + path.str());
            return false;
        }

        Log::debug("Loaded texture: " + path.str() + " " + std::to_string(width) + " " + std::to_string(height) + " " + std::to_string(bpp));
        return true;
    } 
Example 16
Project: olive   Author: olive-editor   File: output.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void NodeOutput::Load(QXmlStreamReader* reader, XMLNodeData &xml_node_data, const QAtomicInt *cancelled)
{
  XMLAttributeLoop(reader, attr) {
    if (cancelled && *cancelled) {
      return;
    }

    if (attr.name() == "ptr") {
      quintptr saved_ptr = attr.value().toULongLong();

      xml_node_data.output_ptrs.insert(saved_ptr, this);
    }
  }

  reader->skipCurrentElement();
} 
Example 17
Project: DeepMimic   Author: xbpeng   File: IBuffer.cpp    License: MIT License 6 votes vote down vote up
void cIBuffer::LoadBuffer(int num_elem, int elem_size, int *data, int data_offset)
{
    if (data == NULL)
        return;

    mElemSize = elem_size;
    ResizeBuffer(num_elem * elem_size + data_offset); // does nothing if data is already allocated and large enough
    memcpy(mLocalData, data, num_elem * elem_size);     // note: don't use mSize. This method allows partial copies

#ifdef DEBUG
    GLenum err =  glGetError();
    if (err != GL_NO_ERROR)
    {
        fprintf(stderr, "Buffer Assignment Failed: %08x\n", err);
    }
#endif
} 
Example 18
Project: Arduino_BLE_iOS_CPP   Author: LessonStudio   File: CCDataReaderHelper.cpp    License: MIT License 6 votes vote down vote up
void DataReaderHelper::loadData()
{
    AsyncStruct *pAsyncStruct = nullptr;

    while (true)
    {
        std::queue<AsyncStruct *> *pQueue = _asyncStructQueue;
        _asyncStructQueueMutex.lock(); // get async struct from queue
        if (pQueue->empty())
        {
            _asyncStructQueueMutex.unlock();
            if (need_quit)
            {
                break;
            }
            else
            {
				std::unique_lock<std::mutex> lk(_sleepMutex);
				_sleepCondition.wait(lk);
                continue;
            }
        }
        else
        { 
Example 19
Project: nsg   Author: ZJULearning   File: test_nsg_search.cpp    License: MIT License 6 votes vote down vote up
void load_data(char* filename, float*& data, unsigned& num,
               unsigned& dim) {  // load data with sift10K pattern
  std::ifstream in(filename, std::ios::binary);
  if (!in.is_open()) {
    std::cout << "open file error" << std::endl;
    exit(-1);
  }
  in.read((char*)&dim, 4);
  std::cout << "data dimension: " << dim << std::endl;
  in.seekg(0, std::ios::end);
  std::ios::pos_type ss = in.tellg();
  size_t fsize = (size_t)ss;
  num = (unsigned)(fsize / (dim + 1) / 4);
  data = new float[num * dim * sizeof(float)];

  in.seekg(0, std::ios::beg);
  for (size_t i = 0; i < num; i++) {
    in.seekg(4, std::ios::cur);
    in.read((char*)(data + i * dim), dim * 4);
  }
  in.close();
} 
Example 20
Project: FPGA-ZynqNet   Author: pp-Innovate   File: TestBench.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
int load_data(string filename, int channel_num, int width, int height, int fl, data_t *out)
{
	ifstream ifile(filename.c_str(), ios::in | ios::binary);
	if(!ifile.is_open())
		return -1;

	int length = channel_num * height * width;
	long size = length * 4;

	char *readbuf = new char[size];

	ifile.read(readbuf, size);

	for(int i = 0; i < length; i++)
		out[i] = ((float*)readbuf)[i] * pow(2, fl);

	delete[] readbuf;

	ifile.close();

	return 0;
} 
Example 21
Project: firebase-cpp-sdk   Author: firebase   File: user_secure_fake_internal.cc    License: Apache License 2.0 6 votes vote down vote up
std::string UserSecureFakeInternal::LoadUserData(const std::string& app_name) {
  std::string output;
  std::string filename = GetFilePath(app_name);

  std::ifstream infile;
  infile.open(filename, std::ios::binary);
  if (infile.fail()) {
    LogDebug("LoadUserData: Failed to read %s", filename.c_str());
    return "";
  }

  infile.seekg(0, std::ios::end);
  size_t length = infile.tellg();
  infile.seekg(0, std::ios::beg);
  output.resize(length);
  infile.read(&*output.begin(), length);
  if (infile.fail()) {
    return "";
  }
  infile.close();
  return output;
} 
Example 22
Project: WSSParticleSystem   Author: weiDDD   File: CCDataReaderHelper.cpp    License: Apache License 2.0 6 votes vote down vote up
void DataReaderHelper::loadData()
{
    AsyncStruct *pAsyncStruct = nullptr;

    while (true)
    {
        std::queue<AsyncStruct *> *pQueue = _asyncStructQueue;
        _asyncStructQueueMutex.lock(); // get async struct from queue
        if (pQueue->empty())
        {
            _asyncStructQueueMutex.unlock();
            if (need_quit)
            {
                break;
            }
            else
            {
				std::unique_lock<std::mutex> lk(_sleepMutex);
				_sleepCondition.wait(lk);
                continue;
            }
        }
        else
        { 
Example 23
Project: brave-core   Author: brave   File: publisher_state.cc    License: Mozilla Public License 2.0 6 votes vote down vote up
void LegacyPublisherState::OnLoad(
    const ledger::Result result,
    const std::string& data,
    ledger::ResultCallback callback) {
  if (result != ledger::Result::LEDGER_OK) {
    callback(result);
    return;
  }

  ledger::PublisherSettingsProperties state;
  const ledger::PublisherSettingsState publisher_settings_state;
  if (!publisher_settings_state.FromJson(data.c_str(), &state)) {
    callback(ledger::Result::LEDGER_ERROR);
    return;
  }

  state_.reset(new ledger::PublisherSettingsProperties(state));
  callback(ledger::Result::LEDGER_OK);
} 
Example 24
Project: BesLyric-for-X   Author: BesLyric-for-X   File: LyricListManager.cpp    License: GNU General Public License v3.0 6 votes vote down vote up
void LyricListManager::loadFromDataDir()
{
    QString path = MakeSureConfigPathAvailable();
    if(path.size() == 0)
        return;

    if(!QFile::exists(path))  //不存在,自动创建歌词单文件,并保存
    {
        if(listData.listsHistory.size()==0)
        {
            LyricList lyricList;
            lyricList.name = tr("制作记录");
            listData.listsHistory.push_back(lyricList);
        }

        if(!saveLyricListData(listData))
            BesMessageBox::information(tr("提示"), tr("尝试创建默认歌词单文件失败,可能是程序没有写权限"));
    }
    else //存在,读取配置
    {
		if 
Example 25
Project: service-fabric   Author: microsoft   File: HealthEntityCache.cpp    License: MIT License 6 votes vote down vote up
::LoadStoreDataTimerCallback()
{
    vector<HealthEntitySPtr> nonInitializedEntities;

    { // lock
        AcquireWriteLock lock(lock_);
        if (!acceptRequests_ || allDataLoadedInMemory_)
        {
            healthManagerReplica_.WriteNoise(TraceComponent, "{0}: LoadStoreDataTimerCallback.Cancel: acceptRequests={1}", this->PartitionedReplicaId.TraceId, acceptRequests_);
            return;
        }

        nonInitializedEntities.swap(nonInitializedEntities_);
    } // endlock

    ActivityId activityId;
    if (nonInitializedEntities.empty())
    {
        LoadEntitiesAttributes(activityId);
    }
    else
    { 
Example 26
Project: libpeconv   Author: hasherezade   File: pe_loader.cpp    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
BYTE* load_no_sec_pe(BYTE* dllRawData, size_t r_size, OUT size_t &v_size, bool executable)
    {
        ULONGLONG desired_base = 0;
        size_t out_size = (r_size < PAGE_SIZE) ? PAGE_SIZE : r_size;
        if (executable) {
            desired_base = get_image_base(dllRawData);
            out_size = peconv::get_image_size(dllRawData);
        }
        DWORD protect = (executable) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
        BYTE* mappedPE = peconv::alloc_pe_buffer(out_size, protect, desired_base);
        if (!mappedPE) {
            return NULL;
        }
        memcpy(mappedPE, dllRawData, r_size);
        v_size = out_size;
        return mappedPE;
    } 
Example 27
Project: tts-tutorial   Author: mjansche   File: wfst_train.cc    License: Apache License 2.0 5 votes vote down vote up
LISP load_string_data(EST_WFST &wfst,EST_String &filename)
{
    // Load in sentences into data table, assume sentence per line
    EST_TokenStream ts;
    LISP ss = NIL;
    EST_String t;
    int id;
    int i,j;
    
    if (ts.open(filename) == -1)
	EST_error("wfst_train: failed to read data from \"%s\"",
			  (const char *)filename);

    i = 0;
    j = 0;
    while (!ts.eof())
    {
	LISP s = NIL;
	do
	{
	    t = (EST_String)ts.get();
	    id = wfst.in_symbol(t);
	    if (id == -1)
	    {
		cerr << "wfst_train: data contains unknown symbol \"" <<
		    t << "\"" << endl;
	    }
	    s = cons(flocons(id),s);
	    j++;
	}
	while (!ts.eoln() && !ts.eof());
	i++;
	ss = cons(reverse(s),ss);
    }

    printf("wfst_train: loaded %d lines of %d tokens\n",
	   i,j);

    return reverse(ss);
} 
Example 28
Project: LidarView   Author: Kitware   File: vvLoadDataReaction.cxx    License: Apache License 2.0 5 votes vote down vote up
pqPipelineSource* vvLoadDataReaction::loadData()
{
  pqServer* server = pqActiveObjects::instance().activeServer();
  vtkSMReaderFactory* readerFactory = vtkSMProxyManager::GetProxyManager()->GetReaderFactory();
  QString filters = readerFactory->GetSupportedFileTypes(server->session());
  if (!filters.isEmpty())
  {
    filters += ";;";
  }
  filters += "All files (*)";

  pqSettings* settings = pqApplicationCore::instance()->settings();
  QString defaultDir =
    settings->value("LidarPlugin/OpenData/DefaultDir", QDir::homePath()).toString();

  QString positionFileName;
  QString fileName;

  if (this->SeparatePositionFile)
  {
    fileName = QFileDialog::getOpenFileName(pqCoreUtilities::mainWidget(), tr("Open LiDAR File"),
      defaultDir, "Wireshark Capture (*.pcap);;All files(*)");

    if (fileName.isEmpty())
    {
      return NULL;
    }

    positionFileName =
      QFileDialog::getOpenFileName(pqCoreUtilities::mainWidget(), tr("Open Position File"),
        defaultDir, "Applanix POSCAP Position Data Text Export (*.txt);;All files (*)");

    if (positionFileName.isEmpty())
    {
      return NULL;
    }
  }
  else
  { 
Example 29
Project: seal   Author: Chrisding   File: hdf5_data_layer.cpp    License: MIT License 5 votes vote down vote up
::LoadHDF5FileData(const char* filename) {
  DLOG(INFO) << "Loading HDF5 file: " << filename;
  hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT);
  if (file_id < 0) {
    LOG(FATAL) << "Failed opening HDF5 file: " << filename;
  }

  int top_size = this->layer_param_.top_size();
  hdf_blobs_.resize(top_size);

  const int MIN_DATA_DIM = 1;
  const int MAX_DATA_DIM = INT_MAX;

  for (int i = 0; i < top_size; ++i) {
    hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>());
    hdf5_load_nd_dataset(file_id, this->layer_param_.top(i).c_str(),
        MIN_DATA_DIM, MAX_DATA_DIM, hdf_blobs_[i].get());
  }

  herr_t status = H5Fclose(file_id);
  CHECK_GE(status, 0) << "Failed to close HDF5 file: " << filename;

  // MinTopBlobs==1 guarantees at least one top blob
  CHECK_GE(hdf_blobs_[0]->num_axes(), 1) << "Input must have at least 1 axis.";
  const int num = hdf_blobs_[0]->shape(0);
  for (int i = 1; i < top_size; ++i) {
    CHECK_EQ(hdf_blobs_[i]->shape(0), num);
  }
  // Default to identity permutation.
  data_permutation_.clear();
  data_permutation_.resize(hdf_blobs_[0]->shape(0));
  for (int i = 0; i < hdf_blobs_[0]->shape(0); i++)
    data_permutation_[i] = i;

  // Shuffle if needed.
  if (this->layer_param_.hdf5_data_param().shuffle()) {
    std::random_shuffle(data_permutation_.begin(), data_permutation_.end());
    DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0)
               << " rows (shuffled)";
  } else { 
Example 30
ErrorCode LoadTargetStoreData()
    {
        auto storeTx = this->CreateTransaction();

        switch (owner_.context_.DeploymentType)
        {
        case DeploymentType::Enum::V2Application:
            targetStoreData_ = make_shared<StoreDataSingleInstanceApplicationInstance>(
                owner_.context_.DeploymentName,
                owner_.context_.TargetTypeVersion);
            break;
        default:
            Assert::CodingError("Unknown single instance deployment upgrade type {0}", static_cast<int>(owner_.applicationContext_.ApplicationDefinitionKind));
        }

        return storeTx.ReadExact(*targetStoreData_);
    } 
Example 31
Project: firebase-cpp-sdk   Author: firebase   File: user_secure_linux_internal.cc    License: Apache License 2.0 5 votes vote down vote up
std::string UserSecureLinuxInternal::LoadUserData(const std::string& app_name) {
  std::string empty_str("");

  if (key_namespace_.length() <= 0) {
    return empty_str;
  }

  GError* error = nullptr;
  char* result = secret_password_lookup_sync(
      &storage_schema_,
      /* cancellable= */ nullptr,
      /* error= */ &error,
      /* key1= */ kAppNameKey,
      /* value1= */ app_name.c_str(), /* key2= */ kStorageDomainKey,
      /* value2= */ domain_.c_str(), nullptr);

  if (CheckForError(&error, "lookup") || result == nullptr) {
    return empty_str;
  }
  std::string str_result(result);
  secret_password_free(result);

  return str_result;
} 
Example 32
Project: JUCE-Graph-Component   Author: hkarim   File: juce_ImageFileFormat.cpp    License: MIT License 5 votes vote down vote up
Image ImageFileFormat::loadFrom (const void* rawData, const size_t numBytes)
{
    if (rawData != nullptr && numBytes > 4)
    {
        MemoryInputStream stream (rawData, numBytes, false);
        return loadFrom (stream);
    }

    return Image();
} 
Example 33
Project: DouDiZhu   Author: ZhouWeikuan   File: TGAlib.cpp    License: Apache License 2.0 5 votes vote down vote up
bool tgaLoadImageData(unsigned char *Buffer, unsigned long bufSize, tImageTGA *info)
{
    bool ret = false;

    do 
    {
        int mode,total,i;
        unsigned char aux;
        size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;

        // mode equal the number of components for each pixel
        mode = info->pixelDepth / 8;
        // total is the number of unsigned chars we'll have to read
        total = info->height * info->width * mode;

        size_t dataSize = sizeof(unsigned char) * total;
        CC_BREAK_IF((step + dataSize) > bufSize);
        memcpy(info->imageData, Buffer + step, dataSize);

        // mode=3 or 4 implies that the image is RGB(A). However TGA
        // stores it as BGR(A) so we'll have to swap R and B.
        if (mode >= 3)
        {
            for (i=0; i < total; i+= mode)
            {
                aux = info->imageData[i];
                info->imageData[i] = info->imageData[i+2];
                info->imageData[i+2] = aux;
            }
        }

        ret = true;
    } while (0);

    return ret;
} 
Example 34
Project: oboe   Author: google   File: SampleBuffer.cpp    License: Apache License 2.0 5 votes vote down vote up
void SampleBuffer::loadSampleData(parselib::WavStreamReader* reader) {
    // Although we read this in, at this time we know a-priori that the data is mono
    mAudioProperties.channelCount = reader->getNumChannels();
    mAudioProperties.sampleRate = reader->getSampleRate();

    reader->positionToAudio();

    mNumSamples = reader->getNumSampleFrames() * reader->getNumChannels();
    mSampleData = new float[mNumSamples];

    reader->getDataFloat(mSampleData, reader->getNumSampleFrames());
} 
Example 35
Project: ImsvGraphVis   Author: VIDILabs   File: IGVData.cpp    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void UIGVData::LoadFile(FString const& FilePath, AIGVGraphActor* const GraphActor)
{
	if (!FPaths::FileExists(FilePath))
	{
		IGV_LOG_S(Error, TEXT("File not exist: %s"), *FilePath);
		return;
	}

	FString const Filename = FPaths::GetCleanFilename(FilePath);
	IGV_LOG_S(Log, TEXT("Load File: %s"), *Filename);

	FString JsonStr;
	FFileHelper::LoadFileToString(JsonStr, *FilePath);

	TSharedPtr<FJsonObject> JsonObj = MakeShareable(new FJsonObject());
	if (!DeserializeJson(JsonStr, JsonObj))
	{
		IGV_LOG_S(Error, TEXT("Unable to deserialize JSON file: %s"), *JsonStr);
		return;
	}
	DeserializeGraph(JsonObj, GraphActor);
} 
Example 36
Project: libpeconv   Author: hasherezade   File: pe_loader.cpp    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
BYTE* peconv::load_pe_module(BYTE* dllRawData, size_t r_size, OUT size_t &v_size, bool executable, bool relocate)
{
    if (!peconv::get_nt_hdrs(dllRawData)) {
        return NULL;
    }
    if (peconv::get_sections_count(dllRawData, r_size) == 0) {
        return load_no_sec_pe(dllRawData, r_size, v_size, executable);
    }
    // by default, allow to load the PE at any base:
    ULONGLONG desired_base = NULL;
    // if relocating is required, but the PE has no relocation table...
    if (relocate && !has_relocations(dllRawData)) {
        // ...enforce loading the PE image at its default base (so that it will need no relocations)
        desired_base = get_image_base(dllRawData);
    }
    // load a virtual image of the PE file at the desired_base address (random if desired_base is NULL):
    BYTE *mappedDLL = pe_raw_to_virtual(dllRawData, r_size, v_size, executable, desired_base);
    if (mappedDLL) {
        //if the image was loaded at its default base, relocate_module will return always true (because relocating is already done)
        if (relocate && !relocate_module(mappedDLL, v_size, (ULONGLONG)mappedDLL)) {
            // relocating was required, but it failed - thus, the full PE image is useless
            printf("Could not relocate the module!");
            free_pe_buffer(mappedDLL, v_size);
            mappedDLL = NULL;
        }
    } else { 
Example 37
Project: Arduino_BLE_iOS_CPP   Author: LessonStudio   File: TGAlib.cpp    License: MIT License 5 votes vote down vote up
bool tgaLoadImageData(unsigned char *Buffer, unsigned long bufSize, tImageTGA *info)
{
    bool ret = false;

    do 
    {
        int mode,total,i;
        unsigned char aux;
        size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;

        // mode equal the number of components for each pixel
        mode = info->pixelDepth / 8;
        // total is the number of unsigned chars we'll have to read
        total = info->height * info->width * mode;

        size_t dataSize = sizeof(unsigned char) * total;
        CC_BREAK_IF((step + dataSize) > bufSize);
        memcpy(info->imageData, Buffer + step, dataSize);

        // mode=3 or 4 implies that the image is RGB(A). However TGA
        // stores it as BGR(A) so we'll have to swap R and B.
        if (mode >= 3)
        {
            for (i=0; i < total; i+= mode)
            {
                aux = info->imageData[i];
                info->imageData[i] = info->imageData[i+2];
                info->imageData[i+2] = aux;
            }
        }

        ret = true;
    } while (0);

    return ret;
} 
Example 38
Project: bsnes-hd   Author: DerKoun   File: memory.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
auto SharpRTC::load(const uint8* data) -> void {
  for(auto byte : range(8)) {
    rtcWrite(byte * 2 + 0, data[byte] >> 0);
    rtcWrite(byte * 2 + 1, data[byte] >> 4);
  }

  uint64 timestamp = 0;
  for(auto byte : range(8)) {
    timestamp |= data[8 + byte] << (byte * 8);
  }

  uint64 diff = (uint64)time(0) - timestamp;
  while(diff >= 60 * 60 * 24) { tickDay(); diff -= 60 * 60 * 24; }
  while(diff >= 60 * 60) { tickHour(); diff -= 60 * 60; }
  while(diff >= 60) { tickMinute(); diff -= 60; }
  while(diff--) tickSecond();
} 
Example 39
Project: GVirtuS   Author: cjg   File: CudaDr_module.cpp    License: Apache License 2.0 5 votes vote down vote up
extern CUresult cuModuleLoadData(CUmodule *module, const void *image) {
    CudaDrFrontend::Prepare();
    CudaDrFrontend::AddStringForArguments((char *) image);
    CudaDrFrontend::Execute("cuModuleLoadData");
    if (CudaDrFrontend::Success())
        *module = (CUmodule) (CudaDrFrontend::GetOutputDevicePointer());
    return (CUresult) (CudaDrFrontend::GetExitCode());

} 
Example 40
Project: opticks   Author: opticks-org   File: ImageLoader.cpp    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
void ImageLoader::loadData(void* pData)
{
   if ((pData == NULL) || (mpColorBuffer == NULL))
   {
      return;
   }

   // Get the texture parameters
   GLuint textureId = mpColorBuffer->getTextureObjectId();
   if (textureId == 0)
   {
      return;
   }

   GLenum textureTarget = mpColorBuffer->getTextureTarget();
   int width = mpColorBuffer->getWidth();
   int height = mpColorBuffer->getHeight();
   GLenum textureFormat = mpColorBuffer->getTextureFormat();
   GLenum dataType = mpColorBuffer->getDataType();

   // Bind texture object to texture target
   glEnable(textureTarget);
   glBindTexture(textureTarget, textureId);

   // load data to texture on graphics card
   // Note: Need to call glTexSubImage2D here to load the data because some graphics cards will
   //       try to deallocate and reallocate memory on the graphics card if glTexImage2D is used
   glTexSubImage2D(textureTarget, 0, 0, 0, width, height, textureFormat, dataType, pData);

   // unbind texture
   glBindTexture(textureTarget, 0);
   glDisable(textureTarget);
} 
Example 41
Project: sunstrider-legacy   Author: SunstriderEmu   File: MMapManager.cpp    License: GNU General Public License v2.0 5 votes vote down vote up
bool MMapManager::loadMapData(uint32 mapId)
    {
        // we already have this map loaded?
        auto itr = loadedMMaps.find(mapId);
        if (itr != loadedMMaps.end())
        {
            if (itr->second)
                return true;
        }
        else
        {
            if 
Example 42
Project: TaskExplorer   Author: DavidXanatos   File: qwt_plot_svgitem.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
bool QwtPlotSvgItem::loadData( const QRectF &rect,
    const QByteArray &data )
{
    d_data->boundingRect = rect;
    const bool ok = d_data->renderer.load( data );

    legendChanged();
    itemChanged();

    return ok;
} 
Example 43
Project: LittleSLAM   Author: furo-org   File: SensorDataReader.cpp    License: Mozilla Public License 2.0 5 votes vote down vote up
bool SensorDataReader::loadScan(size_t cnt, Scan2D &scan) {
  bool isScan=false;
  while (!inFile.eof() && !isScan) {     // スキャンを読むまで続ける
    isScan = loadLaserScan(cnt, scan);
  }

  if (isScan) 
    return(false);                       // まだファイルが続くという意味
  else
    return 
Example 44
Project: CPP-Reactive-Programming   Author: PacktPublishing   File: SampleCppLinq.cpp    License: MIT License 5 votes vote down vote up
load_data()
{
	ifstream datafile("data.txt");
    vector<string> v;
    string line;

    if (datafile.fail())
        throw logic_error("could not find file");

    while(getline(datafile, line))
        v.push_back(line);

    return v;
} 
Example 45
Project: ShapePFCN   Author: kalov   File: hdf5_data_layer.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
::LoadHDF5FileData(const char* filename) {
  DLOG(INFO) << "Loading HDF5 file: " << filename;
  hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT);
  if (file_id < 0) {
    LOG(FATAL) << "Failed opening HDF5 file: " << filename;
  }

  int top_size = this->layer_param_.top_size();
  hdf_blobs_.resize(top_size);

  const int MIN_DATA_DIM = 1;
  const int MAX_DATA_DIM = INT_MAX;

  for (int i = 0; i < top_size; ++i) {
    hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>());
    hdf5_load_nd_dataset(file_id, this->layer_param_.top(i).c_str(),
        MIN_DATA_DIM, MAX_DATA_DIM, hdf_blobs_[i].get());
  }

  herr_t status = H5Fclose(file_id);
  CHECK_GE(status, 0) << "Failed to close HDF5 file: " << filename;

  // MinTopBlobs==1 guarantees at least one top blob
  CHECK_GE(hdf_blobs_[0]->num_axes(), 1) << "Input must have at least 1 axis.";
  const int num = hdf_blobs_[0]->shape(0);
  for (int i = 1; i < top_size; ++i) {
    CHECK_EQ(hdf_blobs_[i]->shape(0), num);
  }
  // Default to identity permutation.
  data_permutation_.clear();
  data_permutation_.resize(hdf_blobs_[0]->shape(0));
  for (int i = 0; i < hdf_blobs_[0]->shape(0); i++)
    data_permutation_[i] = i;

  // Shuffle if needed.
  if (this->layer_param_.hdf5_data_param().shuffle()) {
    std::random_shuffle(data_permutation_.begin(), data_permutation_.end());
    DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0)
               << " rows (shuffled)";
  } else { 
Example 46
Project: mediapipe   Author: google   File: graph.cc    License: Apache License 2.0 5 votes vote down vote up
::mediapipe::Status Graph::LoadBinaryGraph(const char* data, int size) {
  CalculatorGraphConfig graph_config;
  if (!graph_config.ParseFromArray(data, size)) {
    return ::mediapipe::InvalidArgumentError("Failed to parse the graph");
  }
  graph_configs_.push_back(graph_config);
  return ::mediapipe::OkStatus();
} 
Example 47
Project: brave-core   Author: brave   File: bat_state.cc    License: Mozilla Public License 2.0 5 votes vote down vote up
void LegacyBatState::OnLoad(
      const ledger::Result result,
      const std::string& data,
      ledger::ResultCallback callback) {
  if (result != ledger::Result::LEDGER_OK) {
    callback(result);
    return;
  }

  ledger::ClientProperties state;
  const ledger::ClientState client_state;
  if (!client_state.FromJson(data, &state)) {
    BLOG(0, "Failed to load client state: " << data);
    callback(ledger::Result::LEDGER_ERROR);
    return;
  }

  state_.reset(new ledger::ClientProperties(state));

  // fix timestamp ms to s conversion
  if (std::to_string(state_->reconcile_timestamp).length() > 10) {
    state_->reconcile_timestamp = state_->reconcile_timestamp / 1000;
  }

  // fix timestamp ms to s conversion
  if (std::to_string(state_->boot_timestamp).length() > 10) {
    state_->boot_timestamp = state_->boot_timestamp / 1000;
  }

  callback(ledger::Result::LEDGER_OK);
} 
Example 48
Project: serominer   Author: sero-cash   File: keccak_utils.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
inline uint64_t load_le(const uint8_t *data) noexcept
{
    // memcpy is the best way of expressing the intention. Every compiler will
    // optimize is to single load instruction if the target architecture
    // supports unaligned memory access (GCC and clang even in O0).
    // This is great trick because we are violating C/C++ memory alignment
    // restrictions with no performance penalty.
    uint64_t word;
    memcpy(&word, data, sizeof(word));
    return word;
} 
Example 49
Project: Face_Alignment_Two_Stage_Re-initialization   Author: shaoxiaohu   File: hdf5_data_layer.cpp    License: MIT License 5 votes vote down vote up
::LoadHDF5FileData(const char* filename) {
  DLOG(INFO) << "Loading HDF5 file: " << filename;
  hid_t file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT);
  if (file_id < 0) {
    LOG(FATAL) << "Failed opening HDF5 file: " << filename;
  }

  int top_size = this->layer_param_.top_size();
  hdf_blobs_.resize(top_size);

  const int MIN_DATA_DIM = 1;
  const int MAX_DATA_DIM = INT_MAX;

  for (int i = 0; i < top_size; ++i) {
    hdf_blobs_[i] = shared_ptr<Blob<Dtype> >(new Blob<Dtype>());
    hdf5_load_nd_dataset(file_id, this->layer_param_.top(i).c_str(),
        MIN_DATA_DIM, MAX_DATA_DIM, hdf_blobs_[i].get());
  }

  herr_t status = H5Fclose(file_id);
  CHECK_GE(status, 0) << "Failed to close HDF5 file: " << filename;

  // MinTopBlobs==1 guarantees at least one top blob
  CHECK_GE(hdf_blobs_[0]->num_axes(), 1) << "Input must have at least 1 axis.";
  const int num = hdf_blobs_[0]->shape(0);
  for (int i = 1; i < top_size; ++i) {
    CHECK_EQ(hdf_blobs_[i]->shape(0), num);
  }
  // Default to identity permutation.
  data_permutation_.clear();
  data_permutation_.resize(hdf_blobs_[0]->shape(0));
  for (int i = 0; i < hdf_blobs_[0]->shape(0); i++)
    data_permutation_[i] = i;

  // Shuffle if needed.
  if (this->layer_param_.hdf5_data_param().shuffle()) {
    std::random_shuffle(data_permutation_.begin(), data_permutation_.end());
    DLOG(INFO) << "Successully loaded " << hdf_blobs_[0]->shape(0)
               << " rows (shuffled)";
  } else { 
Example 50
Project: OpenMF-Archived   Author: MafiaHub   File: load_def.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
void dump(MFFormat::DataFormatLoadDEF loadDef)
{
    MFLogger::Logger::raw("number of loading screens: " + std::to_string(loadDef.getNumLoadingScreens()), "dump");
    for (auto loadingScreen : loadDef.getLoadingScreens())
    {
        MFLogger::Logger::raw("\t" + std::string(loadingScreen.mMissionName) + "\t" + std::string(loadingScreen.mFileName) + "\t" + std::to_string(loadingScreen.mTextId), "dump");
    }
} 
Example 51
Project: RobustGNSS   Author: wvu-navLab   File: OrbElemFIC109.cpp    License: MIT License 5 votes vote down vote up
void OrbElemFIC109::loadData( const FICData& fic109)
      throw( InvalidParameter )
   {
      if (fic109.blockNum!=109)
      {
         InvalidParameter exc("Invalid FIC Block: "+StringUtils::asString(fic109.blockNum));
         GPSTK_THROW(exc);
      }
      short XmitGPSWeek = fic109.i[0];
      short PRNID = fic109.i[1];
      long SF1[10], SF2[10], SF3[10];
      for(int i = 0; i < 10; i++)
      {
         SF1[i] = fic109.i[2+i];
         SF2[i] = fic109.i[12+i];
         SF3[i] = fic109.i[22+i];
      }

         // FIC only stores GPS data, so the system is well-defined.
      SatID sid(PRNID, SatID::systemGPS);

      OrbElemLNav::loadData( SF1,
                             SF2,
                             SF3,
                             sid,
                             XmitGPSWeek );
   } 
Example 52
Project: TWiLightMenu   Author: DS-Homebrew   File: formdesc.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
void FormDesc::loadData(const std::string &topleftBmpFile,
                         const std::string &toprightBmpFile,
                         const std::string &middleBmpFile)
{
    _topleft = createBMP15FromFile(topleftBmpFile);
    _topright = createBMP15FromFile(toprightBmpFile);
    _middle = createBMP15FromFile(middleBmpFile);
} 
Example 53
Project: ANESE   Author: daniel5151   File: load.cc    License: MIT License 5 votes vote down vote up
bool ANESE_fs::load::load_file(const char* filepath, u8*& data, uint& data_len) {
  if (!filepath) {
    fprintf(stderr, "[Load] filepath == nullptr in load_file!\n");
    assert(false);
  }

  std::ifstream rom_file (std::string(filepath), std::ios::binary);

  if (!rom_file.is_open()) {
    fprintf(stderr, "[Load] Could not open '%s'\n", filepath);
    return false;
  }

  // get length of file
  rom_file.seekg(0, rom_file.end);
  std::streamoff rom_file_size = rom_file.tellg();
  rom_file.seekg(0, rom_file.beg);

  if (rom_file_size == -1) {
    fprintf(stderr, "[Load] Could not read '%s'\n", filepath);
    return false;
  }

  data_len = rom_file_size;
  data = new u8 [data_len];
  rom_file.read((char*) data, data_len);

  fprintf(stderr, "[Load] Successfully read '%s'\n", filepath);

  return true;
} 
Example 54
Project: hls_lfcd_lds_driver   Author: ROBOTIS-GIT   File: lds_polar_graph.cpp    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void LdsPolarGraph::loadData()
{
  uint16_t *laser_sensor_data;
  laser_sensor_data = poll();

  series_->clear();

  for (int i = angular_min_; i < angular_max_; i++)
  {
    series_->append(i, laser_sensor_data[i]);
  }

  this->setChart(chart_);
} 
Example 55
Project: btcpool   Author: btccom   File: testdataoperationmanager_common.cpp    License: MIT License 5 votes vote down vote up
void CheckReadyToLoad(DataOperationManagerBase& manager)
{
    EXPECT_NE(manager.GetDataHandler("correct.txt"), nullptr);
    EXPECT_NE(manager.GetDataHandler("correct.empty.txt"), nullptr);
    EXPECT_NE(manager.GetDataHandler("correct.number.txt"), nullptr);
    EXPECT_EQ(manager.GetDataHandler("wrong.txt"), nullptr);
    EXPECT_EQ(manager.GetDataHandler("notexist.txt"), nullptr);
} 
Example 56
Project: interactive_slam   Author: SMRT-AIST   File: interactive_graph.cpp    License: GNU General Public License v3.0 5 votes vote down vote up
bool InteractiveGraph::load_map_data(const std::string& directory, guik::ProgressInterface& progress) {
  // load graph file
  progress.set_title("Opening " + directory);
  progress.set_text("loading graph");
  if(!load(directory + "/graph.g2o")) {
    return false;
  }

  // re-assign edge ids
  // note: newly created edges may have inconsistent IDs (who cares!)
  edge_id_gen = 0;
  for(auto& edge : graph->edges()) {
    edge->setId(edge_id_gen++);
  }

  // load keyframes
  progress.increment();
  progress.set_text("loading keyframes");
  if(!load_keyframes(directory, progress)) {
    return false;
  }

  // load anchor and floor nodes
  if(!load_special_nodes(directory, progress)) {
    return false;
  }

  return true;
} 
Example 57
Project: prefabricator-ue4   Author: coderespawn   File: PrefabDebugActor.cpp    License: MIT License 5 votes vote down vote up
void APrefabDebugActor::LoadActorData()
{
	if (Actor) {
		UObject* Obj = Actor->GetComponents().Array()[0];
		FObjectReader ObectReader(Obj, ActorData);

		Obj->PostLoad();
		Actor->PostLoad();
		Actor->ReregisterAllComponents();
		Actor->PostActorCreated();

#if WITH_EDITOR
		FCoreUObjectDelegates::OnObjectModified.Broadcast(Obj);
		//Obj->PostEditChange();
#endif

		Actor->Modify(true);
	}
} 
Example 58
Project: CocosCreator-Android-StartupBooster   Author: zhitaocai   File: TGAlib.cpp    License: MIT License 5 votes vote down vote up
bool tgaLoadImageData(unsigned char *Buffer, unsigned long bufSize, tImageTGA *info)
{
    bool ret = false;

    do
    {
        int mode,total,i;
        unsigned char aux;
        size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6;

        // mode equal the number of components for each pixel
        mode = info->pixelDepth / 8;
        // total is the number of unsigned chars we'll have to read
        total = info->height * info->width * mode;

        size_t dataSize = sizeof(unsigned char) * total;
        CC_BREAK_IF((step + dataSize) > bufSize);
        memcpy(info->imageData, Buffer + step, dataSize);

        // mode=3 or 4 implies that the image is RGB(A). However TGA
        // stores it as BGR(A) so we'll have to swap R and B.
        if (mode >= 3)
        {
            for (i=0; i < total; i+= mode)
            {
                aux = info->imageData[i];
                info->imageData[i] = info->imageData[i+2];
                info->imageData[i+2] = aux;
            }
        }

        ret = true;
    } while (0);

    return ret;
} 
Example 59
Project: VoxelConeTracingGI   Author: compix   File: Mesh.cpp    License: MIT License 5 votes vote down vote up
void Mesh::load(const MeshData& meshData)
{
    ensureCapacity(0);
    SubMesh& subMesh = m_subMeshes[0];
    subMesh.vertices.resize(meshData.vertices.size());
    subMesh.normals.resize(meshData.vertices.size());
    subMesh.tangents.resize(meshData.vertices.size());
    subMesh.bitangents.resize(meshData.vertices.size());
    subMesh.uvs.resize(meshData.vertices.size());
    subMesh.indices = meshData.indices;

    for (size_t i = 0; i < meshData.vertices.size(); ++i)
    {
        subMesh.vertices[i] = meshData.vertices[i].pos;
        subMesh.normals[i] = meshData.vertices[i].normal;
        subMesh.tangents[i] = meshData.vertices[i].tangent;
        subMesh.bitangents[i] = meshData.vertices[i].bitanget;
        subMesh.uvs[i] = meshData.vertices[i].uv;
    }

    finalize();
} 
Example 60
Project: carnage3d   Author: codenamecpp   File: GtaFontData.cpp    License: MIT License 5 votes vote down vote up
bool GtaFontData::LoadFromStream(std::istream& inStream)
{
    // read header
    unsigned char numChars = 0;
    READ_I8(inStream, numChars);

    unsigned char charsHeight = 0;
    READ_I8(inStream, charsHeight);

    // clear previous content
    Clear();

    mChars.resize(numChars);
    for (int iChar = 0; iChar < numChars; ++iChar)
    {
        char charWidth = 0;
        READ_I8(inStream, charWidth);

        int charDataLength = charWidth * charsHeight;
        mChars[iChar].mCharWidth = charWidth;
        mChars[iChar].mBits.resize(charDataLength);

        if (!inStream.read(reinterpret_cast<char*>(&mChars[iChar].mBits[0]), charDataLength))
        {
            debug_assert(false);
        }
    }

    // read palette entries
    for (int icolor = 0; icolor < CountOf(mPalette.mColors); ++icolor)
    {
        READ_I8(inStream, mPalette.mColors[icolor].mG);
        READ_I8(inStream, mPalette.mColors[icolor].mG);
        READ_I8(inStream, mPalette.mColors[icolor].mB);
        mPalette.mColors[icolor].mA = 0xFF;
    }
    return true;
}