示例#1
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_qrs_hr_features(void *args) {

	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	ITheEventBoard *board = Factory::GetEventBoard();

	//raw
	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data/ecg");
	reader->getOptions()->block = 0.2;
	ITransformable *ecg_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	// qrs detection
	QRSDetection *ecg_chain = ssi_create(QRSDetection, 0, true);
	ecg_chain->getOptions()->sendEvent = false;
	ITransformable *ecg_qrs_t = frame->AddTransformer(ecg_p, ecg_chain, "0.75s", "0", "60.0s");

	// heart rate
	QRSHeartRate *qrshr = ssi_create(QRSHeartRate, 0, true);
	ITransformable *ecg_hr_t = frame->AddTransformer(ecg_qrs_t, qrshr, "1.0s", "0", "60.0s");

	// heart rate features
	Spectrogram *spectogram = ssi_create(Spectrogram, 0, true);
	ssi_strcpy(spectogram->getOptions()->file, "hrspect.banks");
	spectogram->getOptions()->nbanks = 3;
	ITransformable *ecg_hr_spec_t = frame->AddTransformer(ecg_hr_t, spectogram, "1", "29", "60.0s");

	//hrv_spectral
	QRSHRVspectral *ecg_hr_spectralfeatures = ssi_create(QRSHRVspectral, 0, true);
	ecg_hr_spectralfeatures->getOptions()->print = true;
	ITransformable *ecg_hr_spectralfeatures_t = frame->AddTransformer(ecg_hr_spec_t, ecg_hr_spectralfeatures, "1", "0", "60.0s");

	//hrv_time
	QRSHRVtime *ecg_hr_timefeatures = ssi_create(QRSHRVtime, 0, true);
	ecg_hr_timefeatures->getOptions()->print = true;
	ITransformable *ecg_hr_timefeatures_t = frame->AddTransformer(ecg_qrs_t, ecg_hr_timefeatures, "1.0s", "6.5s", "60.0s");

	//visual
	SignalPainter *plot = 0;
	ssi_real_t p_size = 100.0f;

	//qrs
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("qrs");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_qrs_t, plot, "0.75s");

	//heart rate
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("hr");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_hr_t, plot, "1");

	//spectrgram
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("hr spect");
	plot->getOptions()->size = p_size;
	plot->getOptions()->type = PaintSignalType::IMAGE;
	frame->AddConsumer(ecg_hr_spec_t, plot, "1");

	//framework

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();

	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#2
0
	bool ProcessDemoFile(const char* filePath)
	{
		for(u32 i = 0; i < ID_MAX_CLIENTS; ++i)
		{
			_players[i].Name.clear();
			_players[i].Valid = false;
		}

		FileReader reader;
		if(!reader.Open(filePath))
		{
			return false;
		}

		udtCuContext* const cuContext = _cuContext;
		const u32 protocol = udtGetProtocolByFilePath(filePath);
		const s32 firstPlayerIdx = udtGetIdConfigStringIndex((u32)udtConfigStringIndex::FirstPlayer, protocol);
		if(firstPlayerIdx < 0)
		{
			PrintError("Failed to get the first index of player config strings");
			return false;
		}

		_protocol = (udtProtocol::Id)protocol;
		_protocolFirstPlayerCsIdx = firstPlayerIdx;

		s32 errorCode = udtCuStartParsing(cuContext, protocol);
		if(errorCode != udtErrorCode::None)
		{
			PrintError("udtCuStartParsing failed: %s", udtGetErrorCodeString(errorCode));
			return false;
		}

		udtCuMessageInput input;
		udtCuMessageOutput output;
		u32 continueParsing = 0;
		for(;;)
		{
			if(!reader.Read(&input.MessageSequence, 4))
			{
				PrintWarning("Demo is truncated");
				return true;
			}

			if(!reader.Read(&input.BufferByteCount, 4))
			{
				PrintWarning("Demo is truncated");
				return true;
			}

			if(input.MessageSequence == -1 &&
			   input.BufferByteCount == u32(-1))
			{
				// End of demo file.
				break;
			}

			if(input.BufferByteCount > ID_MAX_MSG_LENGTH)
			{
				PrintError("Corrupt input: the buffer length exceeds the maximum allowed");
				return false;
			}

			if(!reader.Read(_inMsgData, input.BufferByteCount))
			{
				PrintWarning("Demo is truncated");
				return true;
			}
			input.Buffer = _inMsgData;

			errorCode = udtCuParseMessage(cuContext, &output, &continueParsing, &input);
			if(errorCode != udtErrorCode::None)
			{
				PrintError("udtCuParseMessage failed: %s", udtGetErrorCodeString(errorCode));
				return false;
			}

			if(continueParsing == 0)
			{
				break;
			}

			AnalyzeMessage(output);
		}

		return true;
	}
示例#3
0
void
WorldObjRenderer::process(const FileReader& reader)
{
  // FIXME: does not handle sprite alignment
  // FIXME: does not handle remove groundpieces
  // FIXME: does not handle liquid
  if (reader.get_name() == "surface-background" ||
      reader.get_name() == "starfield-background" ||
      reader.get_name() == "solidcolor-background" ||
      reader.get_name() == "snow-generator" ||
      reader.get_name() == "rain-generator")
  {
    // ignore
  }
  else if (reader.get_name() == "groundpiece" ||
           reader.get_name() == "liquid" ||
           reader.get_name() == "exit" ||
           reader.get_name() == "hotspot")
  {
    process_object_with_surface(reader);
  }
  else if (reader.get_name() == "entrance")
  {
    Vector3f pos;
    reader.read_vector("position", pos);
    render_sprite(ResDescriptor("entrances/generic"), pos);
  }
  else if (reader.get_name() == "spike")
  {
    Vector3f pos;
    reader.read_vector("position", pos);
    render_surface(ResDescriptor("traps/spike_editor"), pos);
  }
  else if (reader.get_name() == "switchdoor-switch")
  {
    Vector3f pos;
    reader.read_vector("position", pos);
    render_surface(ResDescriptor("worldobjs/switchdoor_switch"), pos);
  }
  else if (reader.get_name() == "switchdoor-door")
  {
    Vector3f pos;
    reader.read_vector("position", pos);
    render_surface(ResDescriptor("worldobjs/switchdoor_box"), pos);
  }
  else if (reader.get_name() == "group")
  {
    FileReader objects = reader.read_section("objects");
    process(objects.get_sections());
  }
  else if (reader.get_name() == "prefab")
  {
    std::string name;
    if (!reader.read_string("name", name))
    {
      log_error("'name' tag missing for prefab");
    }
    else
    {
      PrefabFile prefab = PrefabFile::from_resource(name);

      Vector3f position;
      reader.read_vector("position", position);
      push_translate(static_cast<int>(position.x),
                     static_cast<int>(position.y));
      process(prefab.get_objects());
      pop_translate();
    }
  }
  else
  {
    log_error("unknown object type: %1%", reader.get_name());
  }
}
示例#4
0
void BenchmarkDArray(Sorter<char *> &sorter)
{
	DArray<char *> data, rdata;
	Stopwatch sw;
	char buffer[512], format[64];
	sprintf(format, "%s", "%4.3lfs");

	FileReader file;

	file.SetLineEndings(CC_LN_LF);
	file.Open("dataset");

	if (file.IsOpen()) {
		data.setStepDouble();
		rdata.setStepDouble();

		console->Write("Loading... ");

		sw.Start();

		/* Load the file into the data DArray */
		while (file.ReadLine(buffer, sizeof(buffer)) >= 0)
			data.insert(cc_strdup(buffer));

		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		file.Close();

		console->WriteLine("Loaded %d items.", data.used());

		console->Write("Random: ");
		sw.Start();
		data.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		/* Create a reverse-sorted DArray */
		for (long i = (long)data.size(); i >= 0; i--) {
			if (data.valid(i)) {
				rdata.insert(data.get(i));
			}
		}

		console->Write("Pre-sorted: ");
		sw.Start();
		data.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		console->Write("Reverse-sorted: ");
		sw.Start();
		rdata.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		for (size_t i = 0; i < data.size(); i++) {
			if (data.valid(i)) {
				free(data.get(i));
				data.remove(i);
			}
		}

		data.empty();
		rdata.empty();
	} else {
		console->WriteLine("Dataset not found.");
	}
}
示例#5
0
文件: options.cpp 项目: AMDmi3/pingus
Options
Options::from_file_reader(const FileReader& reader)
{
  Options opts;

  int int_value;
  bool bool_value;
  std::string string_value;
  Size size_value;

  FramebufferType fbtype_value = SDL_FRAMEBUFFER;

  if (reader.read_enum("renderer", fbtype_value, framebuffer_type_from_string))
  {
    opts.framebuffer_type.set(fbtype_value);
  }

  if (reader.read_int("master-volume", int_value)) 
  {
    opts.master_volume.set(int_value);
  }
  
  if (reader.read_int("sound-volume", int_value))
  {
    opts.sound_volume.set(int_value);
  }
  
  if (reader.read_int("music-volume", int_value))
  {
    opts.music_volume.set(int_value);
  }

  if (reader.read_size("geometry", size_value))
  {
    opts.geometry.set(size_value);
  }
  
  if (reader.read_size("fullscreen-resolution", size_value))
  {
    opts.fullscreen_resolution.set(size_value);
  }

  if (reader.read_bool("fullscreen", bool_value))
  {
    opts.fullscreen.set(bool_value);
  }
  
  if (reader.read_bool("resizable", bool_value))
  {
    opts.resizable.set(bool_value);
  }

  if (reader.read_bool("mouse-grab", bool_value))
  {
    opts.mouse_grab.set(bool_value);
  }
  
  if (reader.read_bool("print-fps", bool_value))
  {
    opts.mouse_grab.set(bool_value);
  }

  if (reader.read_string("controller", string_value))
  {
    opts.controller.set(string_value);
  }

  if (reader.read_string("language", string_value))
  {
    opts.language.set(string_value);
  }
  
  if (reader.read_bool("software-cursor", bool_value))
  {
    opts.software_cursor.set(bool_value);
  }
  
  if (reader.read_bool("auto-scrolling", bool_value))
  {
    opts.auto_scrolling.set(bool_value);
  }

  if (reader.read_bool("drag-drop-scrolling", bool_value))
  {
    opts.drag_drop_scrolling.set(bool_value);
  }

  return opts;
}
示例#6
0
bool ex_framework (void *arg) {

	TheFramework *frame = ssi_pcast (TheFramework, Factory::GetFramework ());
	//frame->getOptions ()->monitor = true;
	//frame->getOptions ()->setMonitorPos (800, 0, 400, 200);
	//frame->getOptions ()->console = true;
	//frame->getOptions ()->setConsolePos (800, 200, 400, 200);
	//ThePainter *painter = ssi_pcast (ThePainter, Factory::GetPainter ());

	double sample_rate = 200.0;
	double frequency = 5.0;
	double sine_len = 60.0;
	double plot_dur = 11.1;
	const ssi_char_t *print_dur = "1.0s";
	double provide_size = 0.1;
	bool repeat = true;

	unsigned int len = static_cast<unsigned int> (sample_rate * sine_len);
	double *data = new double [len];
	data[0] = 0.0;
	double delta = 1/sample_rate;
	for (unsigned int i = 1; i < len; i++) {
		data[i] = data[i-1] + delta;
	}
	for (unsigned int i = 0; i < len; i++) {
		data[i] = sin (2.0 * PI * frequency * data[i]);
	}

	//Provider::SetLogLevel (SSI_LOG_LEVEL_DEBUG);
	//Transformer::SetLogLevel (SSI_LOG_LEVEL_DEBUG);
	//Consumer::SetLogLevel (SSI_LOG_LEVEL_DEBUG);
	frame->SetLogLevel (SSI_LOG_LEVEL_DEBUG);

	FileReader *simulator = ssi_create (FileReader, 0, true);
	simulator->getOptions ()->setPath ("input");
	simulator->getOptions ()->loop = true;
	simulator->getOptions ()->block = provide_size;
	ITransformable *provider = frame->AddProvider (simulator, SSI_FILEREADER_PROVIDER_NAME);
	//simulator.setLogLevel (SSI_LOG_LEVEL_DEBUG);
	frame->AddSensor (simulator);

	AbsFilt<float> abs;
	RampFilt<float> ramp;
	IFilter *filter[2] = {&abs, &ramp};
	MeanFeat<float> mean;
	MinMaxFeat<float> minmax;
	IFeature *feature[2] = {&mean, &minmax};

	//Chain chain (2, filter, 2, feature);
	Chain *chain = ssi_create (Chain, 0, true);
	chain->set (2, filter, 2, feature);
	ITransformable *chain_t = frame->AddTransformer (provider, chain, "0.05s", "0.05s");

	MyConsumer my_consumer_;
	//Chain chain_2 (2, filter, 2, feature);
	Chain *chain_2 = ssi_create (Chain, 0, true);
	chain_2->set (2, filter, 2, feature);
	frame->AddConsumer (provider, &my_consumer_, "0.05s", "0.05s", chain_2);

/*
	SignalPainter *signal_painter = ssi_create (SignalPainter, 0, true);
	signal_painter->getOptions ()->setName ("signal");
	signal_painter->getOptions ()->size = plot_dur;
	frame->AddConsumer (provider, signal_painter, "0.1s");

	SignalPainter *chain_painter = ssi_create (SignalPainter, 0, true);
	chain_painter->getOptions ()->setName ("chain");
	chain_painter->getOptions ()->size = plot_dur;
	frame->AddConsumer (chain_t, chain_painter, "0.1s");
*/
	FileWriter *signal_printer = ssi_create (FileWriter, 0, true);
	signal_printer->getOptions ()->type = File::ASCII;
	signal_printer->getOptions ()->setPath ("signal.txt");
	frame->AddConsumer (provider, signal_printer, print_dur);

	FileWriter *signal_bprinter = ssi_create (FileWriter, 0, true);
	signal_bprinter->getOptions ()->setPath ("signal.dat");
	frame->AddConsumer (provider, signal_bprinter, print_dur);

	FileWriter *chain_printer = ssi_create (FileWriter, 0, true);
	chain_printer->getOptions ()->type = File::ASCII;
	chain_printer->getOptions ()->setPath ("chain.txt");
	frame->AddConsumer (chain_t, chain_printer, print_dur);

	FileWriter *chain_bprinter = ssi_create (FileWriter, 0, true);
	chain_bprinter->getOptions ()->setPath ("chain.dat");
	frame->AddConsumer (chain_t, chain_bprinter, print_dur);

	frame->Start ();
	//painter->Arrange (1, 2, 0, 0, 800, 400);
	frame->Wait ();
	frame->Stop ();
	frame->Clear ();
	//painter->Clear ();

	delete[] data;

	return true;
}
int main(int argc, char* argv[]) {

  // parse flags
  gflags::SetUsageMessage("This script builds a database for a given dataset of vectors\n"
        "Usage:\n"
        "    tool_createdb --c1 4 --c2 4 --p 2 --basename \"tmp\""
        " You should convert the fvecs beforehand using the accompanying convert script\n");
  gflags::SetVersionString("1.0.0");
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  // select cuda device
  cudaSetDevice(FLAGS_device);
  cudaSetDeviceFlags (cudaDeviceMapHost);

  const string preName  = FLAGS_basename + "_" + std::to_string(FLAGS_dim) + "_" + std::to_string(FLAGS_p)
                        + "_" + std::to_string(FLAGS_c1) + "_" + std::to_string(FLAGS_c2);


  // read in dataset
  FileReader<float> DataReader = FileReader<float>(FLAGS_dataset);
  EXPECT_EQ((uint) FLAGS_dim, DataReader.dim());
  arr<float> data((int) FLAGS_chunksize * FLAGS_dim);
  data.mallocHost();
  data.mallocDevice();
  data.host = DataReader.data(FLAGS_chunksize);
  data.toDevice();

  // building the codebook
  // ==============================================================================================
  int k = 16;
  PerturbationProTree ppt(FLAGS_dim, FLAGS_p, FLAGS_p);
  const string codebook_file = preName + ".ppqt";

  ppt.createTree(FLAGS_c1, FLAGS_c2, data.device, 20000);
  ppt.writeTreeToFile(codebook_file);

  

  const string lineName   = preName + "_" + std::to_string(FLAGS_lineparts) + ".lines";
  const string prefixName = preName + ".prefix";
  const string countsName = preName + ".count";
  const string dbIdxName  = preName + ".dbIdx";

  const uint chunkMax = DataReader.num() / FLAGS_chunksize;
  const uint data_num = chunkMax * FLAGS_chunksize;

  uint* binPrefix = new uint[FLAGS_hashsize];
  uint* binCounts = new uint[FLAGS_hashsize];
  uint* dbIdx = new uint[data_num];

  // building the data base
  // ==============================================================================================
  uint* dbIdxSave = new uint[data_num];

  memset(binPrefix, 0, FLAGS_hashsize * sizeof(uint));
  memset(binCounts, 0, FLAGS_hashsize * sizeof(uint));
  memset(dbIdx, 0, data_num * sizeof(uint));

  uint* chBinPrefix = new uint[FLAGS_hashsize];
  uint* chBinCounts = new uint[FLAGS_hashsize];
  uint* chDBIdx     = new uint[FLAGS_chunksize];
  float* chLines    = new float[FLAGS_chunksize * FLAGS_lineparts];


  ppt.buildKBestDB(data.device, FLAGS_chunksize);
  ppt.lineDist(data.device, FLAGS_chunksize);

  // GPU -> CPU memory
  SAFE_CUDA_CALL(cudaMemcpy(chBinPrefix, ppt.getBinPrefix(), FLAGS_hashsize * sizeof(uint),  cudaMemcpyDeviceToHost));
  SAFE_CUDA_CALL(cudaMemcpy(chBinCounts, ppt.getBinCounts(), FLAGS_hashsize * sizeof(uint),  cudaMemcpyDeviceToHost));
  SAFE_CUDA_CALL(cudaMemcpy(chDBIdx,     ppt.getDBIdx(),     FLAGS_chunksize * sizeof(uint), cudaMemcpyDeviceToHost));
  SAFE_CUDA_CALL(cudaMemcpy(chLines,     ppt.getLine(),      FLAGS_chunksize * FLAGS_lineparts * sizeof(float), cudaMemcpyDeviceToHost));

  ofstream fLines(lineName.c_str(), std::ofstream::out | std::ofstream::binary);
  fLines.write((char*) chLines, FLAGS_chunksize * FLAGS_lineparts * sizeof(float));
  fLines.close();
  cout << "written " << lineName << endl;

  // prefixSum for bin-idx
  ofstream fprefix(prefixName.c_str(), std::ofstream::out | std::ofstream::binary);
  fprefix.write((char*) binPrefix, FLAGS_hashsize * sizeof(uint));
  fprefix.close();
  cout << "written " << prefixName << endl;

  // size of non-empty bins
  ofstream fcounts(countsName.c_str(), std::ofstream::out | std::ofstream::binary);
  fcounts.write((char*) binCounts, FLAGS_hashsize * sizeof(uint));
  fcounts.close();
  cout << "written " << countsName << endl;
  cout << "size: " << (FLAGS_hashsize * sizeof(uint)) << endl;

  // for each bin the ids of containing vectors
  ofstream fdb(dbIdxName.c_str(), std::ofstream::out | std::ofstream::binary);
  fdb.write((char*) dbIdx, data_num * sizeof(uint));
  fdb.close();
  cout << "written " << dbIdxName << endl;

  if (data.device)
    cudaFree(data.device);
  delete[] data.host;


  gflags::ShutDownCommandLineFlags();
  return 0;

}
int main(int argc, char* argv[]) {

  // parse flags
  gflags::SetUsageMessage("This script builds a database for a given dataset of vectors\n"
                          "Usage:\n"
                          "    tool_createdb --c1 4 --c2 4 --p 2 --basename \"tmp\""
                          " You should convert the fvecs beforehand using the accompanying convert script\n");
  gflags::SetVersionString("1.0.0");
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  // select cuda device
  cudaSetDevice(FLAGS_device);
  cudaSetDeviceFlags (cudaDeviceMapHost);

  const string preName  = FLAGS_basename + "_" + std::to_string(FLAGS_dim) + "_" + std::to_string(FLAGS_p)
                          + "_" + std::to_string(FLAGS_c1) + "_" + std::to_string(FLAGS_c2);


  FileReader<float> DataReader = FileReader<float>(FLAGS_dataset);

  FileReader<float> QueryReader = FileReader<float>(FLAGS_queryset);
  EXPECT_EQ((uint) FLAGS_dim, QueryReader.dim());
  arr<float> query = arr<float>(FLAGS_chunksize * FLAGS_dim);
  query.mallocHost();
  query.mallocDevice();
  query.host = QueryReader.data(FLAGS_chunksize);
  query.toDevice();


  PerturbationProTree ppt(FLAGS_dim, FLAGS_p, FLAGS_p);
  const string codebook_file = preName + ".ppqt";

  if (!file_exists(codebook_file)) {
    cout << "you need to generate a codebook first. No codebook found in " << codebook_file << endl;
    return 1;
  } else {
    cout << "codebook exists, reading from " << codebook_file << endl;
    ppt.readTreeFromFile(codebook_file);
  }

  const uint base_num = DataReader.num();

  const string lineName   = preName + "_" + std::to_string(FLAGS_lineparts) + ".lines";
  const string prefixName = preName + ".prefix";
  const string countsName = preName + ".count";
  const string dbIdxName  = preName + ".dbIdx";

  const uint chunkMax = base_num / FLAGS_chunksize;
  const uint data_num = chunkMax * FLAGS_chunksize;

  uint* binPrefix = new uint[FLAGS_hashsize];
  uint* binCounts = new uint[FLAGS_hashsize];
  uint* dbIdx     = new uint[data_num];

  // read data base
  ifstream fprefix(prefixName.c_str(), std::ifstream::in | std::ofstream::binary);
  fprefix.read((char*) binPrefix, FLAGS_hashsize * sizeof(uint));
  fprefix.close();
  cout << "read " << prefixName << endl;

  ifstream fcounts(countsName.c_str(), std::ofstream::in | std::ofstream::binary);
  fcounts.read((char*) binCounts, HASH_SIZE * sizeof(uint));
  fcounts.close();
  cout << "read " << countsName << endl;

  size_t nfloats = DataReader.num();
  nfloats *= FLAGS_lineparts;

  float* hLines = nullptr;
  float* dLines;

  cudaHostAlloc((void **) &hLines, nfloats * sizeof(float), cudaHostAllocMapped);
  cudaHostGetDevicePointer((void **) &dLines, (void *) hLines, 0);
  if (!hLines) {
    cerr << " did not get hLine memory " << endl;
    exit(1);
  }

  ifstream fdb(dbIdxName.c_str(), std::ifstream::in | std::ofstream::binary);
  fdb.read((char*) dbIdx, base_num * sizeof(uint));
  fdb.close();
  cout << "read " << dbIdxName << endl;


  ppt.setDB(base_num, binPrefix, binCounts, dbIdx);

  // query
  vector<uint> resIdx;
  vector<float> resDist;
  
  for (int idxA = 0; idxA < FLAGS_chunksize; idxA += 4096) {
    const int len = min(4096, (int)(FLAGS_chunksize - idxA));
    ppt.queryKNN(resIdx, resDist, query.device + 4096 * idxA * FLAGS_dim, len, 4096);
    for (int r = 0; r < len; ++r) {
      const int queryVectorId = idxA*4096 + r;
      const int bestfoundBaseVectorId = resIdx[4096*r];
      const int secondbestfoundBaseVectorId = resIdx[4096*r+1];
    }
  }

  gflags::ShutDownCommandLineFlags();
  return 0;

}
void SimpleFileSystemVolume::load(FileReader& file)
{
    auto lock = ScopedMutexLock(mutex_);

    file.readPointerVector(entries_);
}
示例#10
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_gsr_baseline_mean(void *args) {

	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	ITheEventBoard *board = Factory::GetEventBoard();

	//raw
	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data/gsr");
	reader->getOptions()->block = 0.2;
	ITransformable *gsr_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	//lowpass
	Butfilt *lowpass = ssi_create(Butfilt, 0, true);
	lowpass->getOptions()->low = 0.01;
	lowpass->getOptions()->order = 3;
	lowpass->getOptions()->type = Butfilt::LOW;
	lowpass->getOptions()->zero = true;
	ITransformable *gsr_low_t = frame->AddTransformer(gsr_p, lowpass, "0.25s");

	//detrend
	GSRRemoveBaseline *detrend = ssi_create(GSRRemoveBaseline, 0, true);
	ITransformable *gsr_detrend_t = frame->AddTransformer(gsr_low_t, detrend, "0.25s");

	//norm
	MvgNorm *norm = ssi_create(MvgNorm, 0, true);
	norm->getOptions()->norm = MvgNorm::SUBMIN;
	norm->getOptions()->method = MvgNorm::SLIDING;
	norm->getOptions()->win = 15.0;
	ITransformable *gsr_detrend_norm_t = frame->AddTransformer(gsr_detrend_t, norm, "0.25s");

	GSRBaselineMean *mean = ssi_create(GSRBaselineMean, 0, true);
	mean->getOptions()->winsize = 15.0;
	frame->AddConsumer(gsr_detrend_norm_t, mean, "0.25s");
	board->RegisterSender(*mean);

	//visual
	SignalPainter *plot = 0;
	ssi_real_t p_size = 100.0f;

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("gsr(lowpassed)");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(gsr_low_t, plot, "0.3s");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("gsr(detrended)");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(gsr_detrend_t, plot, "0.3s");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("gsr(detrended & normed)");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(gsr_detrend_norm_t, plot, "0.3s");

	//events
	EventMonitor *monitor = ssi_create_id(EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, mean->getEventAddress());

	//framework

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();

	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#11
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_qrs_hrv_event(void *args) {

	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	ITheEventBoard *board = Factory::GetEventBoard();

	//raw
	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data/ecg");
	reader->getOptions()->block = 0.2;
	ITransformable *ecg_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	//bandpass
	Butfilt *ecg_band = ssi_create(Butfilt, 0, true);
	ecg_band->getOptions()->type = Butfilt::BAND;
	ecg_band->getOptions()->norm = false;
	ecg_band->getOptions()->high = 15;
	ecg_band->getOptions()->low = 5;
	ecg_band->getOptions()->order = 13;
	ITransformable *ecg_band_t = frame->AddTransformer(ecg_p, ecg_band, "0.75s");

	//diff
	Derivative *ecg_diff = ssi_create(Derivative, 0, true);
	ssi_strcpy(ecg_diff->getOptions()->names, "1st");
	ITransformable *ecg_diff_t = frame->AddTransformer(ecg_band_t, ecg_diff, "0.75s");

	//qrs-pre-process
	QRSPreProcess *ecg_QRSpre = ssi_create(QRSPreProcess, 0, true);
	ITransformable *ecg_QRSpre_t = frame->AddTransformer(ecg_diff_t, ecg_QRSpre, "0.75s");

	Butfilt *lowpass = ssi_create(Butfilt, 0, true);
	lowpass->getOptions()->zero = true;
	lowpass->getOptions()->norm = false;
	lowpass->getOptions()->low = 6.4;
	lowpass->getOptions()->order = 3;
	lowpass->getOptions()->type = Butfilt::LOW;
	ITransformable *ecg_QRSpre_low_t = frame->AddTransformer(ecg_QRSpre_t, lowpass, "0.75s");

	//qrs-detect
	QRSDetect *ecg_qrs = ssi_create(QRSDetect, 0, true);
	ecg_qrs->getOptions()->sendEvent = true;
	ITransformable *ecg_qrs_t = frame->AddTransformer(ecg_QRSpre_low_t, ecg_qrs, "0.75s");
	board->RegisterSender(*ecg_qrs);

	//visual
	SignalPainter *plot = 0;
	ssi_real_t p_size = 10.0f;
	//raw
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("raw");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_p, plot, "0.2s");
	//bandpass
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("bandpass");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_band_t, plot, "0.2s");
	//diff
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("diff");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_diff_t, plot, "0.2s");
	//qrs-pre
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("qrs-pre");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_QRSpre_low_t, plot, "0.2s");
	//qrs
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("qrs");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_qrs_t, plot, "0.2s");

	//events
	QRSHrvEventListener *hrv = ssi_create(QRSHrvEventListener, 0, true);
	hrv->getOptions()->span = 120000;
	hrv->getOptions()->update_ms = 5000;
	board->RegisterListener(*hrv, ecg_qrs->getEventAddress(), 10000);
	board->RegisterSender(*hrv);

	EventMonitor *monitor = ssi_create_id(EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, hrv->getEventAddress(), 10000);

	//framework

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();
	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#12
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_gsr_peaks_online(void *args) {

	ITheEventBoard *board = Factory::GetEventBoard();
	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data\\gsr");
	reader->getOptions()->block = 0.2;
	ITransformable *gsr_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	Butfilt *lowpass = ssi_create(Butfilt, 0, true);
	lowpass->getOptions()->low = 0.01;
	lowpass->getOptions()->order = 3;
	lowpass->getOptions()->type = Butfilt::LOW;
	lowpass->getOptions()->zero = true;
	ITransformable *gsr_low = frame->AddTransformer(gsr_p, lowpass, "0.2s");

	GSREventSender *gsr_event = ssi_create(GSREventSender, 0, true);
	gsr_event->getOptions()->tuple = true;
	gsr_event->setLogLevel(SSI_LOG_LEVEL_DEBUG);
	frame->AddConsumer(gsr_low, gsr_event, "4.0s");
	board->RegisterSender(*gsr_event);

	EventMonitor *monitor = ssi_create_id(EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, gsr_event->getEventAddress());

	SignalPainter *plot = 0;

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("gsr");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(gsr_p, plot, "0.2s");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("gsr(lowpassed)");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(gsr_low, plot, "0.2s");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("peak");
	plot->getOptions()->reset = true;
	frame->AddEventConsumer(gsr_low, plot, board, "peak@");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("slope");
	plot->getOptions()->reset = true;
	frame->AddEventConsumer(gsr_low, plot, board, "slope@");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("drop");
	plot->getOptions()->reset = true;
	frame->AddEventConsumer(gsr_low, plot, board, "drop@");

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();
	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#13
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_bvp_beat_events_raw(void *args) {

	ITheEventBoard *board = Factory::GetEventBoard();
	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data\\bvp");
	reader->getOptions()->block = 0.2;
	reader->getOptions()->loop = false;

	ITransformable *bvp_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	SignalPainter *plot = 0;

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("bvp");
	plot->getOptions()->size = 10.0;
	frame->AddConsumer(bvp_p, plot, "1");

	BVPBeatEventSender *bvp_event = ssi_create(BVPBeatEventSender, 0, true);
	bvp_event->getOptions()->beep = true;
	bvp_event->getOptions()->mean_window = 1;
	bvp_event->getOptions()->tuple = true;

	bvp_event->setLogLevel(SSI_LOG_LEVEL_DEBUG);

	frame->AddConsumer(bvp_p, bvp_event, "0.2s");

	board->RegisterSender(*bvp_event);

	BVPBeatEventRawListener *event_listener = ssi_create(BVPBeatEventRawListener, 0, true);
	event_listener->getOptions()->sr = 9;

	ITransformable *heartRate = frame->AddProvider(event_listener, SSI_BVP_EVENTLISTENER_CHANNEL_HEART_RATE_PROVIDER_NAME);
	ITransformable *amp = frame->AddProvider(event_listener, SSI_BVP_EVENTLISTENER_CHANNEL_AMPLITUDE_PROVIDER_NAME);
	ITransformable *interBeat = frame->AddProvider(event_listener, SSI_BVP_EVENTLISTENER_CHANNEL_INTERBEAT_INTERVAL_PROVIDER_NAME);

	frame->AddSensor(event_listener);

	board->RegisterListener(*event_listener, bvp_event->getEventAddress());

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("heartRate");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(heartRate, plot, "1");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("amp");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(amp, plot, "1");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("interBeat");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(interBeat, plot, "1");

	EventMonitor *monitor = ssi_create_id(EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, bvp_event->getEventAddress());

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();
	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}
示例#14
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_gsr_response_amplitude_events(void *args) {

	ITheEventBoard *board = Factory::GetEventBoard();
	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data\\gsr");
	reader->getOptions()->block = 0.2;
	reader->getOptions()->loop = false;

	ITransformable *gsr_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	SignalPainter *plot = 0;

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("gsr(lowpassed)");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(gsr_p, plot, "1");

	GSRResponseEventSender *gsr_event = ssi_create(GSRResponseEventSender, 0, true);
	gsr_event->getOptions()->tuple = true;
	gsr_event->getOptions()->minRisingTime = 0;
	gsr_event->getOptions()->minAllowedRegression = 0.1f;
	gsr_event->getOptions()->minAmplitude = 0.5f;
	gsr_event->getOptions()->print = false;

	gsr_event->setLogLevel(SSI_LOG_LEVEL_DEBUG);

	frame->AddConsumer(gsr_p, gsr_event, "0.2s");

	board->RegisterSender(*gsr_event);

	GSREventListener *event_listener = ssi_create(GSREventListener, 0, true);
	event_listener->getOptions()->statisticalFn = GSR_SUM;
	event_listener->getOptions()->window = SSI_GSR_EVENTLISTENER_NO_WINDOW;

	ITransformable *nr_of_responses = frame->AddProvider(event_listener, SSI_GSR_EVENTLISTENER_NUMBER_OF_RESPONSES_PROVIDER_NAME);
	ITransformable *amp = frame->AddProvider(event_listener, SSI_GSR_EVENTLISTENER_AMPLITUDE_PROVIDER_NAME);
	ITransformable *power = frame->AddProvider(event_listener, SSI_GSR_EVENTLISTENER_POWER_PROVIDER_NAME);

	frame->AddSensor(event_listener);

	board->RegisterListener(*event_listener, gsr_event->getEventAddress());

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("nr_of_responses");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(nr_of_responses, plot, "1");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("amp");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(amp, plot, "1");

	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("power");
	plot->getOptions()->size = 150.0;
	frame->AddConsumer(power, plot, "1");

	EventMonitor *monitor = ssi_create_id(EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, gsr_event->getEventAddress());

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();
	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;

}
示例#15
0
void FPNGTexture::MakeTexture ()
{
	FileReader *lump;

	if (SourceLump >= 0)
	{
		lump = new FWadLump(Wads.OpenLumpNum(SourceLump));
	}
	else
	{
		lump = new FileReader(SourceFile.GetChars());
	}

	Pixels = new BYTE[Width*Height];
	if (StartOfIDAT == 0)
	{
		memset (Pixels, 0x99, Width*Height);
	}
	else
	{
		DWORD len, id;
		lump->Seek (StartOfIDAT, SEEK_SET);
		lump->Read(&len, 4);
		lump->Read(&id, 4);

		if (ColorType == 0 || ColorType == 3)	/* Grayscale and paletted */
		{
			M_ReadIDAT (lump, Pixels, Width, Height, Width, BitDepth, ColorType, Interlace, BigLong((unsigned int)len));

			if (Width == Height)
			{
				if (PaletteMap != NULL)
				{
					FlipSquareBlockRemap (Pixels, Width, Height, PaletteMap);
				}
				else
				{
					FlipSquareBlock (Pixels, Width, Height);
				}
			}
			else
			{
				BYTE *newpix = new BYTE[Width*Height];
				if (PaletteMap != NULL)
				{
					FlipNonSquareBlockRemap (newpix, Pixels, Width, Height, Width, PaletteMap);
				}
				else
				{
					FlipNonSquareBlock (newpix, Pixels, Width, Height, Width);
				}
				BYTE *oldpix = Pixels;
				Pixels = newpix;
				delete[] oldpix;
			}
		}
		else		/* RGB and/or Alpha present */
		{
			int bytesPerPixel = ColorType == 2 ? 3 : ColorType == 4 ? 2 : 4;
			BYTE *tempix = new BYTE[Width * Height * bytesPerPixel];
			BYTE *in, *out;
			int x, y, pitch, backstep;

			M_ReadIDAT (lump, tempix, Width, Height, Width*bytesPerPixel, BitDepth, ColorType, Interlace, BigLong((unsigned int)len));
			in = tempix;
			out = Pixels;

			// Convert from source format to paletted, column-major.
			// Formats with alpha maps are reduced to only 1 bit of alpha.
			switch (ColorType)
			{
			case 2:		// RGB
				pitch = Width * 3;
				backstep = Height * pitch - 3;
				for (x = Width; x > 0; --x)
				{
					for (y = Height; y > 0; --y)
					{
						if (!HaveTrans)
						{
							*out++ = RGB32k.RGB[in[0]>>3][in[1]>>3][in[2]>>3];
						}
						else
						{
							if (in[0] == NonPaletteTrans[0] &&
								in[1] == NonPaletteTrans[1] &&
								in[2] == NonPaletteTrans[2])
							{
								*out++ = 0;
							}
							else
							{
								*out++ = RGB32k.RGB[in[0]>>3][in[1]>>3][in[2]>>3];
							}
						}
						in += pitch;
					}
					in -= backstep;
				}
				break;

			case 4:		// Grayscale + Alpha
				pitch = Width * 2;
				backstep = Height * pitch - 2;
				if (PaletteMap != NULL)
				{
					for (x = Width; x > 0; --x)
					{
						for (y = Height; y > 0; --y)
						{
							*out++ = in[1] < 128 ? 0 : PaletteMap[in[0]];
							in += pitch;
						}
						in -= backstep;
					}
				}
				else
				{
					for (x = Width; x > 0; --x)
					{
						for (y = Height; y > 0; --y)
						{
							*out++ = in[1] < 128 ? 0 : in[0];
							in += pitch;
						}
						in -= backstep;
					}
				}
				break;

			case 6:		// RGB + Alpha
				pitch = Width * 4;
				backstep = Height * pitch - 4;
				for (x = Width; x > 0; --x)
				{
					for (y = Height; y > 0; --y)
					{
						*out++ = in[3] < 128 ? 0 : RGB32k.RGB[in[0]>>3][in[1]>>3][in[2]>>3];
						in += pitch;
					}
					in -= backstep;
				}
				break;
			}
			delete[] tempix;
		}
示例#16
0
Spike::Spike (const FileReader& reader)
  : surface(Resource::load_sprite("traps/spike")),
    killing(false)
{
  reader.read_vector("position", pos);
}
示例#17
0
WorldObj::WorldObj(const FileReader& reader)
{
  reader.read_string("id", id);
}
示例#18
0
bool CSoundFile::ReadDIGI(FileReader &file, ModLoadingFlags loadFlags)
//--------------------------------------------------------------------
{
    file.Rewind();

    DIGIFileHeader fileHeader;
    if(!file.ReadConvertEndianness(fileHeader)
            || memcmp(fileHeader.signature, "DIGI Booster module\0", 20)
            || !fileHeader.numChannels
            || fileHeader.numChannels > 8
            || fileHeader.lastOrdIndex > 127)
    {
        return false;
    } else if(loadFlags == onlyVerifyHeader)
    {
        return true;
    }

    // Globals
    InitializeGlobals();
    InitializeChannels();

    m_nType = MOD_TYPE_DIGI;
    m_nChannels = fileHeader.numChannels;
    m_nSamples = 31;
    m_nSamplePreAmp = 256 / m_nChannels;
    madeWithTracker = mpt::String::Print("Digi Booster %1.%2", fileHeader.versionInt >> 4, fileHeader.versionInt & 0x0F);

    Order.ReadFromArray(fileHeader.orders, fileHeader.lastOrdIndex + 1);

    // Read sample headers
    for(SAMPLEINDEX smp = 0; smp < 31; smp++)
    {
        ModSample &sample = Samples[smp + 1];
        sample.Initialize(MOD_TYPE_MOD);
        sample.nLength = fileHeader.smpLength[smp];
        sample.nLoopStart = fileHeader.smpLoopStart[smp];
        sample.nLoopEnd = sample.nLoopStart + fileHeader.smpLoopLength[smp];
        if(fileHeader.smpLoopLength[smp])
        {
            sample.uFlags.set(CHN_LOOP);
        }
        sample.SanitizeLoops();

        sample.nVolume = std::min(fileHeader.smpVolume[smp], uint8(64)) * 4;
        sample.nFineTune = MOD2XMFineTune(fileHeader.smpFinetune[smp]);
    }

    // Read song + sample names
    file.ReadString<mpt::String::maybeNullTerminated>(songName, 32);
    for(SAMPLEINDEX smp = 1; smp <= 31; smp++)
    {
        file.ReadString<mpt::String::maybeNullTerminated>(m_szNames[smp], 30);
    }

    for(PATTERNINDEX pat = 0; pat <= fileHeader.lastPatIndex; pat++)
    {
        FileReader patternChunk;
        if(fileHeader.packEnable)
        {
            patternChunk = file.GetChunk(file.ReadUint16BE());
        } else
        {
            patternChunk = file.GetChunk(4 * 64 * GetNumChannels());
        }

        if(!(loadFlags & loadPatternData) || Patterns.Insert(pat, 64))
        {
            continue;
        }

        if(fileHeader.packEnable)
        {
            std::vector<uint8> eventMask;
            patternChunk.ReadVector(eventMask, 64);

            // Compressed patterns are stored in row-major order...
            for(ROWINDEX row = 0; row < 64; row++)
            {
                PatternRow patRow = Patterns[pat].GetRow(row);
                uint8 bit = 0x80;
                for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++, bit >>= 1)
                {
                    if(eventMask[row] & bit)
                    {
                        ModCommand &m = patRow[chn];
                        ReadDIGIPatternEntry(patternChunk, m, *this);
                    }
                }
            }
        } else
        {
            // ...but uncompressed patterns are stored in column-major order. WTF!
            for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++)
示例#19
0
OPENMPT_NAMESPACE_BEGIN

// Version changelog:
// v1.03: - Relative unicode instrument paths instead of absolute ANSI paths
//        - Per-path variable string length
//        - Embedded samples are IT-compressed
//        (rev. 3249)
// v1.02: Explicitely updated format to use new instrument flags representation (rev. 483)
// v1.01: Added option to embed instrument headers


bool CSoundFile::ReadITProject(FileReader &file, ModLoadingFlags loadFlags)
//-------------------------------------------------------------------------
{
#ifndef MPT_EXTERNAL_SAMPLES
	// Doesn't really make sense to support this format when there's no support for external files...
	MPT_UNREFERENCED_PARAMETER(file);
	MPT_UNREFERENCED_PARAMETER(loadFlags);
	return false;
#else // MPT_EXTERNAL_SAMPLES
	
	enum ITPSongFlags
	{
		ITP_EMBEDMIDICFG	= 0x00001,	// Embed macros in file
		ITP_ITOLDEFFECTS	= 0x00004,	// Old Impulse Tracker effect implementations
		ITP_ITCOMPATGXX		= 0x00008,	// IT "Compatible Gxx" (IT's flag to behave more like other trackers w/r/t portamento effects)
		ITP_LINEARSLIDES	= 0x00010,	// Linear slides vs. Amiga slides
		ITP_EXFILTERRANGE	= 0x08000,	// Cutoff Filter has double frequency range (up to ~10Khz)
		ITP_ITPROJECT		= 0x20000,	// Is a project file
		ITP_ITPEMBEDIH		= 0x40000,	// Embed instrument headers in project file
	};

	uint32 version;
	FileReader::off_t size;

	file.Rewind();

	// Check file ID
	if(!file.CanRead(12 + 4 + 24 + 4)
		|| file.ReadUint32LE() != MAGIC4BE('.','i','t','p')	// Magic bytes
		|| (version = file.ReadUint32LE()) > 0x00000103		// Format version
		|| version < 0x00000100)
	{
		return false;
	} else if(loadFlags == onlyVerifyHeader)
	{
		return true;
	}

	InitializeGlobals(MOD_TYPE_IT);
	m_playBehaviour.reset();
	file.ReadString<mpt::String::maybeNullTerminated>(m_songName, file.ReadUint32LE());

	// Song comments
	m_songMessage.Read(file, file.ReadUint32LE(), SongMessage::leCR);

	// Song global config
	const uint32 songFlags = file.ReadUint32LE();
	if(!(songFlags & ITP_ITPROJECT))
	{
		return false;
	}
	if(songFlags & ITP_EMBEDMIDICFG)	m_SongFlags.set(SONG_EMBEDMIDICFG);
	if(songFlags & ITP_ITOLDEFFECTS)	m_SongFlags.set(SONG_ITOLDEFFECTS);
	if(songFlags & ITP_ITCOMPATGXX)		m_SongFlags.set(SONG_ITCOMPATGXX);
	if(songFlags & ITP_LINEARSLIDES)	m_SongFlags.set(SONG_LINEARSLIDES);
	if(songFlags & ITP_EXFILTERRANGE)	m_SongFlags.set(SONG_EXFILTERRANGE);

	m_nDefaultGlobalVolume = file.ReadUint32LE();
	m_nSamplePreAmp = file.ReadUint32LE();
	m_nDefaultSpeed = std::max(uint32(1), file.ReadUint32LE());
	m_nDefaultTempo.Set(std::max(uint32(32), file.ReadUint32LE()));
	m_nChannels = static_cast<CHANNELINDEX>(file.ReadUint32LE());
	if(m_nChannels == 0 || m_nChannels > MAX_BASECHANNELS)
	{
		return false;
	}

	// channel name string length (=MAX_CHANNELNAME)
	size = file.ReadUint32LE();

	// Channels' data
	for(CHANNELINDEX chn = 0; chn < m_nChannels; chn++)
	{
		ChnSettings[chn].nPan = std::min(static_cast<uint16>(file.ReadUint32LE()), uint16(256));
		ChnSettings[chn].dwFlags.reset();
		uint32 flags = file.ReadUint32LE();
		if(flags & 0x100) ChnSettings[chn].dwFlags.set(CHN_MUTE);
		if(flags & 0x800) ChnSettings[chn].dwFlags.set(CHN_SURROUND);
		ChnSettings[chn].nVolume = std::min(static_cast<uint16>(file.ReadUint32LE()), uint16(64));
		file.ReadString<mpt::String::maybeNullTerminated>(ChnSettings[chn].szName, size);
	}

	// Song mix plugins
	{
		FileReader plugChunk = file.ReadChunk(file.ReadUint32LE());
		LoadMixPlugins(plugChunk);
	}

	// MIDI Macro config
	file.ReadStructPartial(m_MidiCfg, file.ReadUint32LE());
	m_MidiCfg.Sanitize();

	// Song Instruments
	m_nInstruments = static_cast<INSTRUMENTINDEX>(file.ReadUint32LE());
	if(m_nInstruments >= MAX_INSTRUMENTS)
	{
		return false;
	}

	// Instruments' paths
	if(version <= 0x00000102)
	{
		size = file.ReadUint32LE();	// path string length
	}

	std::vector<mpt::PathString> instrPaths(GetNumInstruments());
	for(INSTRUMENTINDEX ins = 0; ins < GetNumInstruments(); ins++)
	{
		if(version > 0x00000102)
		{
			size = file.ReadUint32LE();	// path string length
		}
		std::string path;
		file.ReadString<mpt::String::maybeNullTerminated>(path, size);
		if(version <= 0x00000102)
		{
			instrPaths[ins] = mpt::PathString::FromLocaleSilent(path);
		} else
		{
			instrPaths[ins] = mpt::PathString::FromUTF8(path);
		}
	}

	// Song Orders
	size = file.ReadUint32LE();
	Order.ReadAsByte(file, size, size, 0xFF, 0xFE);

	// Song Patterns
	const PATTERNINDEX numPats = static_cast<PATTERNINDEX>(file.ReadUint32LE());
	const PATTERNINDEX numNamedPats = static_cast<PATTERNINDEX>(file.ReadUint32LE());
	size_t patNameLen = file.ReadUint32LE();	// Size of each pattern name
	FileReader pattNames = file.ReadChunk(numNamedPats * patNameLen);

	// modcommand data length
	size = file.ReadUint32LE();
	if(size != 6)
	{
		return false;
	}

	for(PATTERNINDEX pat = 0; pat < numPats; pat++)
	{
		const ROWINDEX numRows = file.ReadUint32LE();
		FileReader patternChunk = file.ReadChunk(numRows * size * GetNumChannels());

		// Allocate pattern
		if(!(loadFlags & loadPatternData) || !Patterns.Insert(pat, numRows))
		{
			pattNames.Skip(patNameLen);
			continue;
		}

		if(pat < numNamedPats)
		{
			char patName[32];
			pattNames.ReadString<mpt::String::maybeNullTerminated>(patName, patNameLen);
			Patterns[pat].SetName(patName);
		}

		// Pattern data
		size_t numCommands = GetNumChannels() * numRows;

		if(patternChunk.CanRead(sizeof(MODCOMMAND_ORIGINAL) * numCommands))
		{
			ModCommand *target = Patterns[pat].GetpModCommand(0, 0);
			while(numCommands-- != 0)
			{
				STATIC_ASSERT(sizeof(MODCOMMAND_ORIGINAL) == 6);
				MODCOMMAND_ORIGINAL data;
				patternChunk.ReadStruct(data);
				if(data.command >= MAX_EFFECTS) data.command = CMD_NONE;
				if(data.volcmd >= MAX_VOLCMDS) data.volcmd = VOLCMD_NONE;
				if(data.note > NOTE_MAX && data.note < NOTE_MIN_SPECIAL) data.note = NOTE_NONE;
				*(target++) = data;
			}
		}
	}

	// Load embedded samples

	// Read original number of samples
	m_nSamples = static_cast<SAMPLEINDEX>(file.ReadUint32LE());
	LimitMax(m_nSamples, SAMPLEINDEX(MAX_SAMPLES - 1));

	// Read number of embedded samples
	uint32 embeddedSamples = file.ReadUint32LE();

	// Read samples
	for(uint32 smp = 0; smp < embeddedSamples; smp++)
	{
		SAMPLEINDEX realSample = static_cast<SAMPLEINDEX>(file.ReadUint32LE());
		ITSample sampleHeader;
		file.ReadConvertEndianness(sampleHeader);
		FileReader sampleData = file.ReadChunk(file.ReadUint32LE());

		if(realSample >= 1 && realSample <= GetNumSamples() && !memcmp(sampleHeader.id, "IMPS", 4) && (loadFlags & loadSampleData))
		{
			sampleHeader.ConvertToMPT(Samples[realSample]);
			mpt::String::Read<mpt::String::nullTerminated>(m_szNames[realSample], sampleHeader.name);

			// Read sample data
			sampleHeader.GetSampleFormat().ReadSample(Samples[realSample], sampleData);
		}
	}

	// Load instruments
	for(INSTRUMENTINDEX ins = 0; ins < GetNumInstruments(); ins++)
	{
		if(instrPaths[ins].empty())
			continue;

		if(!file.GetFileName().empty())
		{
			instrPaths[ins] = instrPaths[ins].RelativePathToAbsolute(file.GetFileName().GetPath());
		}
#ifdef MODPLUG_TRACKER
		else if(GetpModDoc() != nullptr)
		{
			instrPaths[ins] = instrPaths[ins].RelativePathToAbsolute(GetpModDoc()->GetPathNameMpt().GetPath());
		}
#endif // MODPLUG_TRACKER

		InputFile f(instrPaths[ins]);
		FileReader file = GetFileReader(f);
		if(!ReadInstrumentFromFile(ins + 1, file, true))
		{
			AddToLog(LogWarning, MPT_USTRING("Unable to open instrument: ") + instrPaths[ins].ToUnicode());
		}
	}

	// Extra info data
	uint32 code = file.ReadUint32LE();

	// Embed instruments' header [v1.01]
	if(version >= 0x00000101 && (songFlags & ITP_ITPEMBEDIH) && code == MAGIC4BE('E', 'B', 'I', 'H'))
	{
		code = file.ReadUint32LE();

		INSTRUMENTINDEX ins = 1;
		while(ins <= GetNumInstruments() && file.CanRead(4))
		{
			if(code == MAGIC4BE('M', 'P', 'T', 'S'))
			{
				break;
			} else if(code == MAGIC4BE('S', 'E', 'P', '@') || code == MAGIC4BE('M', 'P', 'T', 'X'))
			{
				// jump code - switch to next instrument
				ins++;
			} else
			{
				ReadExtendedInstrumentProperty(Instruments[ins], code, file);
			}

			code = file.ReadUint32LE();
		}
	}

	// Song extensions
	if(code == MAGIC4BE('M', 'P', 'T', 'S'))
	{
		file.SkipBack(4);
		LoadExtendedSongProperties(file);
	}

	m_nMaxPeriod = 0xF000;
	m_nMinPeriod = 8;

	// Before OpenMPT 1.20.01.09, the MIDI macros were always read from the file, even if the "embed" flag was not set.
	if(m_dwLastSavedWithVersion >= MAKE_VERSION_NUMERIC(1,20,01,09) && !m_SongFlags[SONG_EMBEDMIDICFG])
	{
		m_MidiCfg.Reset();
	} else if(!m_MidiCfg.IsMacroDefaultSetupUsed())
	{
		m_SongFlags.set(SONG_EMBEDMIDICFG);
	}

	m_madeWithTracker = "OpenMPT " + MptVersion::ToStr(m_dwLastSavedWithVersion);

	return true;
#endif // MPT_EXTERNAL_SAMPLES
}
示例#20
0
/* 
	If panning or note_to_use != -1, it will be used for all samples,
	instead of the sample-specific values in the instrument file. 

	For note_to_use, any value <0 or >127 will be forced to 0.

	For other parameters, 1 means yes, 0 means no, other values are
	undefined.

	TODO: do reverse loops right */
static Instrument *load_instrument(Renderer *song, const char *name, int percussion,
					int panning, int amp, int note_to_use,
					int strip_loop, int strip_envelope,
					int strip_tail)
{
	Instrument *ip;
	Sample *sp;
	FileReader *fp;
	GF1PatchHeader header;
	GF1InstrumentData idata;
	GF1LayerData layer_data;
	GF1PatchData patch_data;
	int i, j;
	bool noluck = false;

	if (!name) return 0;

	/* Open patch file */
	if ((fp = open_filereader(name, openmode, NULL)) == NULL)
	{
		/* Try with various extensions */
		FString tmp = name;
		tmp += ".pat";
		if ((fp = open_filereader(tmp, openmode, NULL)) == NULL)
		{
#ifdef __unix__			// Windows isn't case-sensitive.
			tmp.ToUpper();
			if ((fp = open_filereader(tmp, openmode, NULL)) == NULL)
#endif
			{
				noluck = true;
			}
		}
	}

	if (noluck)
	{
		cmsg(CMSG_ERROR, VERB_NORMAL, "Instrument `%s' can't be found.\n", name);
		return 0;
	}

	cmsg(CMSG_INFO, VERB_NOISY, "Loading instrument %s\n", name);

	/* Read some headers and do cursory sanity checks. */

	if (sizeof(header) != fp->Read(&header, sizeof(header)))
	{
failread:
		cmsg(CMSG_ERROR, VERB_NORMAL, "%s: Error reading instrument.\n", name);
		delete fp;
		return 0;
	}
	if (strncmp(header.Header, GF1_HEADER_TEXT, HEADER_SIZE - 4) != 0)
	{
		cmsg(CMSG_ERROR, VERB_NORMAL, "%s: Not an instrument.\n", name);
		delete fp;
		return 0;
	}
	if (strcmp(header.Header + 8, "110") < 0)
	{
		cmsg(CMSG_ERROR, VERB_NORMAL, "%s: Is an old and unsupported patch version.\n", name);
		delete fp;
		return 0;
	}
	if (sizeof(idata) != fp->Read(&idata, sizeof(idata)))
	{
		goto failread;
	}

	header.WaveForms = LittleShort(header.WaveForms);
	header.MasterVolume = LittleShort(header.MasterVolume);
	header.DataSize = LittleLong(header.DataSize);
	idata.Instrument = LittleShort(idata.Instrument);

	if (header.Instruments != 1 && header.Instruments != 0) /* instruments. To some patch makers, 0 means 1 */
	{
		cmsg(CMSG_ERROR, VERB_NORMAL, "Can't handle patches with %d instruments.\n", header.Instruments);
		delete fp;
		return 0;
	}

	if (idata.Layers != 1 && idata.Layers != 0) /* layers. What's a layer? */
	{
		cmsg(CMSG_ERROR, VERB_NORMAL, "Can't handle instruments with %d layers.\n", idata.Layers);
		delete fp;
		return 0;
	}

	if (sizeof(layer_data) != fp->Read(&layer_data, sizeof(layer_data)))
	{
		goto failread;
	}

	if (layer_data.Samples == 0)
	{
		cmsg(CMSG_ERROR, VERB_NORMAL, "Instrument has 0 samples.\n");
		delete fp;
		return 0;
	}

	ip = new Instrument;
	ip->samples = layer_data.Samples;
	ip->sample = (Sample *)safe_malloc(sizeof(Sample) * layer_data.Samples);
	memset(ip->sample, 0, sizeof(Sample) * layer_data.Samples);
	for (i = 0; i < layer_data.Samples; ++i)
	{
		if (sizeof(patch_data) != fp->Read(&patch_data, sizeof(patch_data)))
		{
fail:
			cmsg(CMSG_ERROR, VERB_NORMAL, "Error reading sample %d.\n", i);
			delete ip;
			delete fp;
			return 0;
		}

		sp = &(ip->sample[i]);

		sp->data_length = LittleLong(patch_data.WaveSize);
		sp->loop_start = LittleLong(patch_data.StartLoop);
		sp->loop_end = LittleLong(patch_data.EndLoop);
		sp->sample_rate = LittleShort(patch_data.SampleRate);
		sp->low_freq = float(LittleLong(patch_data.LowFrequency));
		sp->high_freq = float(LittleLong(patch_data.HighFrequency)) + 0.9999f;
		sp->root_freq = float(LittleLong(patch_data.RootFrequency));
		sp->high_vel = 127;
		sp->velocity = -1;
		sp->type = INST_GUS;

		// Expand to SF2 range.
		if (panning == -1)
		{
			sp->panning = (patch_data.Balance & 0x0F) * 1000 / 15 - 500;
		}
		else
		{
			sp->panning = (panning & 0x7f) * 1000 / 127 - 500;
		}
		song->compute_pan((sp->panning + 500) / 1000.0, INST_GUS, sp->left_offset, sp->right_offset);

		/* tremolo */
		if (patch_data.TremoloRate == 0 || patch_data.TremoloDepth == 0)
		{
			sp->tremolo_sweep_increment = 0;
			sp->tremolo_phase_increment = 0;
			sp->tremolo_depth = 0;
			cmsg(CMSG_INFO, VERB_DEBUG, " * no tremolo\n");
		}
		else
		{
			sp->tremolo_sweep_increment = convert_tremolo_sweep(song, patch_data.TremoloSweep);
			sp->tremolo_phase_increment = convert_tremolo_rate(song, patch_data.TremoloRate);
			sp->tremolo_depth = patch_data.TremoloDepth;
			cmsg(CMSG_INFO, VERB_DEBUG, " * tremolo: sweep %d, phase %d, depth %d\n",
				sp->tremolo_sweep_increment, sp->tremolo_phase_increment, sp->tremolo_depth);
		}

		/* vibrato */
		if (patch_data.VibratoRate == 0 || patch_data.VibratoDepth == 0)
		{
			sp->vibrato_sweep_increment = 0;
			sp->vibrato_control_ratio = 0;
			sp->vibrato_depth = 0;
			cmsg(CMSG_INFO, VERB_DEBUG, " * no vibrato\n");
		}
		else
		{
			sp->vibrato_control_ratio = convert_vibrato_rate(song, patch_data.VibratoRate);
			sp->vibrato_sweep_increment = convert_vibrato_sweep(song, patch_data.VibratoSweep, sp->vibrato_control_ratio);
			sp->vibrato_depth = patch_data.VibratoDepth;
			cmsg(CMSG_INFO, VERB_DEBUG, " * vibrato: sweep %d, ctl %d, depth %d\n",
				sp->vibrato_sweep_increment, sp->vibrato_control_ratio, sp->vibrato_depth);
		}

		sp->modes = patch_data.Modes;

		/* Mark this as a fixed-pitch instrument if such a deed is desired. */
		if (note_to_use != -1)
		{
			sp->scale_note = note_to_use;
			sp->scale_factor = 0;
		}
		else
		{
			sp->scale_note = LittleShort(patch_data.ScaleFrequency);
			sp->scale_factor = LittleShort(patch_data.ScaleFactor);
			if (sp->scale_factor <= 2)
			{
				sp->scale_factor *= 1024;
			}
			else if (sp->scale_factor > 2048)
			{
				sp->scale_factor = 1024;
			}
			if (sp->scale_factor != 1024)
			{
				cmsg(CMSG_INFO, VERB_DEBUG, " * Scale: note %d, factor %d\n",
					sp->scale_note, sp->scale_factor);
			}
		}

#if 0
		/* seashore.pat in the Midia patch set has no Sustain. I don't
		   understand why, and fixing it by adding the Sustain flag to
		   all looped patches probably breaks something else. We do it
		   anyway. */

		if (sp->modes & PATCH_LOOPEN) 
		{
			sp->modes |= PATCH_SUSTAIN;
		}
#endif
		/* [RH] Alas, eawpats has percussion instruments with bad envelopes. :(
		 * (See cymchina.pat for one example of this sadness.)
		 * Do this logic for instruments without a description, only. Hopefully that
		 * catches all the patches that need it without including any extra.
		 */
		for (j = 0; j < DESC_SIZE; ++j)
		{
			if (header.Description[j] != 0)
				break;
		}
		/* Strip any loops and envelopes we're permitted to */
		/* [RH] (But PATCH_BACKWARD isn't a loop flag at all!) */
		if ((strip_loop == 1) && 
			(sp->modes & (PATCH_SUSTAIN | PATCH_LOOPEN | PATCH_BIDIR | PATCH_BACKWARD)))
		{
			cmsg(CMSG_INFO, VERB_DEBUG, " - Removing loop and/or sustain\n");
			if (j == DESC_SIZE)
			{
				sp->modes &= ~(PATCH_SUSTAIN | PATCH_LOOPEN | PATCH_BIDIR | PATCH_BACKWARD);
			}
			sp->modes |= PATCH_T_NO_LOOP;
		}

		if (strip_envelope == 1)
		{
			cmsg(CMSG_INFO, VERB_DEBUG, " - Removing envelope\n");
			/* [RH] The envelope isn't really removed, but this is the way the standard
			 * Gravis patches get that effect: All rates at maximum, and all offsets at
			 * a constant level.
			 */
			if (j == DESC_SIZE)
			{
				int k;
				for (k = 1; k < ENVELOPES; ++k)
				{ /* Find highest offset. */
					if (patch_data.EnvelopeOffset[k] > patch_data.EnvelopeOffset[0])
					{
						patch_data.EnvelopeOffset[0] = patch_data.EnvelopeOffset[k];
					}
				}
				for (k = 0; k < ENVELOPES; ++k)
				{
					patch_data.EnvelopeRate[k] = 63;
					patch_data.EnvelopeOffset[k] = patch_data.EnvelopeOffset[0];
				}
			}
			sp->modes |= PATCH_T_NO_ENVELOPE;
		}
		else if (strip_envelope != 0)
		{
			/* Have to make a guess. */
			if (!(sp->modes & (PATCH_LOOPEN | PATCH_BIDIR | PATCH_BACKWARD)))
			{
				/* No loop? Then what's there to sustain? No envelope needed either... */
				sp->modes |= PATCH_T_NO_ENVELOPE;
				cmsg(CMSG_INFO, VERB_DEBUG, " - No loop, removing sustain and envelope\n");
			}
			else if (memcmp(patch_data.EnvelopeRate, "??????", 6) == 0 || patch_data.EnvelopeOffset[GF1_RELEASEC] >= 100) 
			{
				/* Envelope rates all maxed out? Envelope end at a high "offset"?
				   That's a weird envelope. Take it out. */
				sp->modes |= PATCH_T_NO_ENVELOPE;
				cmsg(CMSG_INFO, VERB_DEBUG, " - Weirdness, removing envelope\n");
			}
			else if (!(sp->modes & PATCH_SUSTAIN))
			{
				/* No sustain? Then no envelope.  I don't know if this is
				   justified, but patches without sustain usually don't need the
				   envelope either... at least the Gravis ones. They're mostly
				   drums.  I think. */
				sp->modes |= PATCH_T_NO_ENVELOPE;
				cmsg(CMSG_INFO, VERB_DEBUG, " - No sustain, removing envelope\n");
			}
		}
		if (!(sp->modes & PATCH_NO_SRELEASE))
		{ // TiMidity thinks that this is an envelope enable flag.
			sp->modes |= PATCH_T_NO_ENVELOPE;
		}

		for (j = 0; j < 6; j++)
		{
			sp->envelope.gf1.rate[j] = patch_data.EnvelopeRate[j];
			/* [RH] GF1NEW clamps the offsets to the range [5,251], so we do too. */
			sp->envelope.gf1.offset[j] = clamp<BYTE>(patch_data.EnvelopeOffset[j], 5, 251);
		}

		/* Then read the sample data */
		if (((sp->modes & PATCH_16) && sp->data_length/2 > MAX_SAMPLE_SIZE) ||
			(!(sp->modes & PATCH_16) && sp->data_length > MAX_SAMPLE_SIZE))
		{
			goto fail;
		}
		sp->data = (sample_t *)safe_malloc(sp->data_length);

		if (sp->data_length != fp->Read(sp->data, sp->data_length))
			goto fail;

		convert_sample_data(sp, sp->data);

		/* Reverse reverse loops and pass them off as normal loops */
		if (sp->modes & PATCH_BACKWARD)
		{
			int t;
			/* The GUS apparently plays reverse loops by reversing the
			   whole sample. We do the same because the GUS does not SUCK. */

			cmsg(CMSG_WARNING, VERB_NORMAL, "Reverse loop in %s\n", name);
			reverse_data((sample_t *)sp->data, 0, sp->data_length);
			sp->data[sp->data_length] = sp->data[sp->data_length - 1];

			t = sp->loop_start;
			sp->loop_start = sp->data_length - sp->loop_end;
			sp->loop_end = sp->data_length - t;

			sp->modes &= ~PATCH_BACKWARD;
			sp->modes |= PATCH_LOOPEN; /* just in case */
		}

		if (amp != -1)
		{
			sp->volume = (amp) / 100.f;
		}
		else
		{
			/* Try to determine a volume scaling factor for the sample.
			   This is a very crude adjustment, but things sound more
			   balanced with it. Still, this should be a runtime option.
			   (This is ignored unless midi_timiditylike is turned on.) */
			int i;
			sample_t maxamp = 0, a;
			sample_t *tmp;
			for (i = sp->data_length, tmp = sp->data; i; --i)
			{
				a = (sample_t)fabs((*tmp++));
				if (a > maxamp)
					maxamp = a;
			}
			sp->volume = 1 / maxamp;
			cmsg(CMSG_INFO, VERB_DEBUG, " * volume comp: %f\n", sp->volume);
		}

		/* Then fractional samples */
		sp->data_length <<= FRACTION_BITS;
		sp->loop_start <<= FRACTION_BITS;
		sp->loop_end <<= FRACTION_BITS;

		/* Adjust for fractional loop points. */
		sp->loop_start |= (patch_data.Fractions & 0x0F) << (FRACTION_BITS-4);
		sp->loop_end   |= (patch_data.Fractions & 0xF0) << (FRACTION_BITS-4-4);

		/* If this instrument will always be played on the same note,
		   and it's not looped, we can resample it now. */
		if (sp->scale_factor == 0 && !(sp->modes & PATCH_LOOPEN))
		{
			pre_resample(song, sp);
		}

		if (strip_tail == 1)
		{
			/* Let's not really, just say we did. */
			cmsg(CMSG_INFO, VERB_DEBUG, " - Stripping tail\n");
			sp->data_length = sp->loop_end;
		}
	}
	delete fp;
	return ip;
}
示例#21
0
int main(int argc, char* argv[])
{
    // Check for correct number of arguments
    if(argc != 3)
    {
        cerr << "Invalid number of arguments"<<std::endl;
        return 1;
    }
    
    // set up UDP socket, including BINDING hints, IP, and port number
    int sockfd;
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("Can't create socket");
        exit(-1);
    }
    
    int maxSockfd = sockfd;
    char serverIP[20];
    struct addrinfo hints;
    struct addrinfo* res;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET; // IPv4
    hints.ai_socktype = SOCK_DGRAM;
    
    int portno = atoi(argv[1]);
    cout << "port number is " << portno<<endl;
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(portno);     // short, network byte order
    addr.sin_addr.s_addr = inet_addr("10.0.0.1");
    memset(addr.sin_zero, '\0', sizeof(addr.sin_zero));
    
    
    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        perror("bind");
        return 2;
    }
    
    HeaderPacket req_pkt_syn;
    struct sockaddr_in clientAddr;
    socklen_t clilen = sizeof(clientAddr);

    OutputBuffer mybuffer;
    mybuffer.setup();
    uint16_t state = NO_CONNECTION;
    
    if(recvfrom(sockfd, &req_pkt_syn, sizeof(req_pkt_syn), 0, (struct sockaddr*) &clientAddr, (socklen_t*) &clilen) < 0)
    {
        cerr << "recvfrom failed" << endl;
        return 1;
    }
    else
    {
      
        if(ntohs(req_pkt_syn.m_flags) != SYN)
        {
            cerr << "Received a packet that's not SYN, cannot set up connection" <<endl;
            return 1;
        }
        uint16_t initseq = genRandom();
        
        // sending out SYNACK packet
        HeaderPacket resp_pkt_synack;
        resp_pkt_synack.m_seq = htons(initseq);
        resp_pkt_synack.m_ack = htons(0); //server does not need to ack with anything
        resp_pkt_synack.m_flags = htons(SYNACK); //SYNACK flag
        //resp_pkt_synack.m_window = htons(RECV_WINDOW);
        
        if(sendto(sockfd, &resp_pkt_synack, sizeof(resp_pkt_synack), 0, (struct sockaddr*) &clientAddr, clilen)<0)
        {
            cerr << "Sendto fails" << endl;
            return 1;
        }
        state = SYNACK_SENT;
    }
    
    fd_set readFds;
    fd_set writeFds;
    fd_set errFds;
    fd_set watchFds;
    FD_ZERO(&readFds);
    FD_ZERO(&writeFds);
    FD_ZERO(&errFds);
    FD_ZERO(&watchFds);
    
    FileReader myreader;
    myreader.openfile(argv[2]);
    
    bool finish = false;
    
    
    double sRTT = 3;
    double devRtt = 3;

    struct timeval tv;
   
    
    if(!FD_ISSET(sockfd, &readFds))
        FD_SET(sockfd, &readFds);

    while (true) {
        int nReadyFds = 0;
        errFds = watchFds;
        if(!FD_ISSET(sockfd, &watchFds))
            FD_SET(sockfd, &watchFds);
        
        tv.tv_sec = 0;
        tv.tv_usec = 500000;
        if(finish)
        {
            cout << "Time to close the connection"<<endl;
            //close(sockfd);
            break;
        }

        if ((nReadyFds = select(maxSockfd+1, &readFds, &writeFds, &errFds, &tv)) == -1) {
            perror("select");
            return 4;
        }
        
        if (nReadyFds == 0) {
            cout << "TIMEOUT HAPPENS" <<endl;
            if(state == SYNACK_SENT)
            {
                HeaderPacket resp_pkt_synack;
                uint16_t seq = mybuffer.getNextSeqNo();
                cout << "Send out SYNACK packet "<< seq << "Retransmit "<<endl;
                resp_pkt_synack.m_seq = htons(seq);
                resp_pkt_synack.m_ack = htons(0);
                resp_pkt_synack.m_flags = htons(SYNACK); //SYNACK flag
                //resp_pkt_synack.m_window = htons(mybuffer.getWindowSize());
                if(sendto(sockfd, &resp_pkt_synack, sizeof(resp_pkt_synack), 0, (struct sockaddr*) &clientAddr, clilen)<0)
                {
                    cerr << "Sendto fails" << endl;
                    return 1;
                }
                 FD_SET(sockfd, &readFds);
            }
            else if (state == SENT_FIN)
            {
                HeaderPacket resp_pkt_fin;
                resp_pkt_fin.m_seq = htons(mybuffer.getNextSeqNo());
                resp_pkt_fin.m_flags = htons(FIN); //FIN flag
                resp_pkt_fin.m_ack = htons(0);
                //resp_pkt_fin.m_window = htons(mybuffer.getWindowSize());
                
                if(sendto(sockfd, &resp_pkt_fin, sizeof(resp_pkt_fin), 0, (struct sockaddr*) &clientAddr, clilen)<0)
                {
                    cerr << "Sendto fails" << endl;
                    return 1;
                }
                 FD_SET(sockfd, &readFds);
                
            }
            else if (state == CONNECTED)
            {
                if(mybuffer.timeout())
                {
                    FD_CLR(sockfd, &readFds);
                    //close after several retrials
                    close(sockfd);
                    break;
                }
                else
                {
                    myreader.truncate(mybuffer.window_size());
                    uint16_t seq = mybuffer.retcumulative();
                    HeaderPacket res_pkt = mybuffer.getPkt(seq);
                    res_pkt.m_seq = htons(seq);
                    res_pkt.m_flags = htons(0x0);
                    cout << "Sending data packet " << seq << " retransmit " <<endl;
                    if(sendto(sockfd, &res_pkt, sizeof(res_pkt), 0, (struct sockaddr*) &clientAddr, clilen)<0)
                    {
                        cerr << "Sendto fails" << endl;
                        return 1;
                    }
                    FD_SET(sockfd, &readFds);
                }
            }
        }
        else
        {
            for(int fd = 0; fd <= maxSockfd; fd++){
                if (FD_ISSET(fd, &readFds)) // reading, recvfrom cases
                {
                    HeaderPacket req_pkt;
                    if(recvfrom(fd, &req_pkt, sizeof(req_pkt), 0, (struct sockaddr*) &clientAddr, (socklen_t*) &clilen) < 0)
                    {
                        cerr << "recvfrom failed" << endl;
                        return 1;
                    }
                    else
                    {
                        switch(ntohs(req_pkt.m_flags))
                        {
                            case SYNACK:
                            {
                                cout << "Receiveing SYNACK packet "<< ntohs(req_pkt.m_ack)<<endl;
                                mybuffer.setInitSeq(ntohs(req_pkt.m_ack));
                                if(myreader.hasMore())
                                {
                                    
                                    mybuffer.insert(myreader.top());
                                    myreader.pop();
                                }
                                else
                                {
                                    cout <<"nomore"<<endl;
                                }
                                state = CONNECTED;
                                FD_CLR(fd, &readFds);
                                FD_SET(fd, &writeFds);
                                break;
                            }
                            case ACK:
                            {
                                cout << "Receiving ACK packet "<< ntohs(req_pkt.m_ack)<<endl;
                                mybuffer.ack(ntohs(req_pkt.m_ack));
                                
                                /*
                                clock_t end = clock();
                                //reset the timeout
                                double sampleRTT = mybuffer.get_duration(ntohs(req_pkt.m_ack), end);
                                //now update the waiting time
                                
                                double difference = sampleRTT - sRTT;
                                sRTT = sRTT + 0.125 * (difference);
                                devRtt = devRtt + 0.25 * (abs(difference) - devRtt);
                                double ret_to = sRTT + 4* devRtt;
                                
                                double intpart, fracpart;
                                fracpart = modf(ret_to, &intpart);
                                tv.tv_sec = (time_t) intpart;
                                tv.tv_usec = (time_t) 1000000*fracpart;
                                */
                                while(myreader.hasMore() && mybuffer.hasSpace(strlen(myreader.top().payload)))
                                {
                                    cout << "let's do some insert" <<endl;
                                    mybuffer.insert(myreader.top());
                                    myreader.pop();
                                }
                                if(!mybuffer.hasNext())
                                {
                                    cout <<"change state to finish"<<endl;
                                    state = SENT_FIN;
                                }
                            
                                //don't do write until you ack all the packets you just sent out
                                if(mybuffer.switch_to_write())
                                {
                                    cout << "SWITCH TO WRITE STATE " <<endl;
                                    FD_CLR(fd, &readFds);
                                    FD_SET(fd, &writeFds);
                                }
                                break;
                            }
                            case FINACK:
                            {
                                cout << "Receiving FINACK packet "<< ntohs(req_pkt.m_ack)<<endl;
                                finish = true;
                                FD_CLR(fd, &readFds);
                                break;
                            }
                            default:
                                break;
                        }
                    }
                    
                }
                
                else if(FD_ISSET(fd, &writeFds)) // writing, sendto cases
                {
                        cout <<"Do some write" <<endl;

                        HeaderPacket res_pkt;
                        switch(state)
                        {
                            case CONNECTED:
                            {
                                uint16_t seq = mybuffer.getNextSeqNo();
                                res_pkt = mybuffer.getPkt(seq); // initial sequence number
                            
                               // clock_t t = clock();
                                
                                ///mybuffer.record_start(seq, clock());
                                
                                cout << "Sending data packet " << seq << endl;
                                
                                /*
                                cout << "print out payload" <<endl;
                                int p_size = strlen(res_pkt.payload);
                                if(p_size >1024)
                                    p_size = 1024;
                                for (int i = 0; i<p_size; i++) {
                                    cout << res_pkt.payload[i];
                                }
                                cout << endl;
                                */
                                
                                res_pkt.m_flags = htons(0x0);
                                if(sendto(sockfd, &res_pkt, sizeof(res_pkt), 0, (struct sockaddr*) &clientAddr, clilen)<0)
                                {
                                    cerr << "Sendto fails" << endl;
                                    return 1;
                                }
                                if(mybuffer.switch_to_read())
                                {
                                    cout << "SWITCH TO READ STATE" <<endl;
                                    FD_CLR(fd, &writeFds);
                                    FD_SET(fd, &readFds);
                                }
                                break;
                            }
                            case SENT_FIN:
                            {
                                uint16_t seq = mybuffer.retcumulative();
                                res_pkt.m_seq = htons(seq);
                                //res_pkt.m_window = htons(getWindowSize());
                                res_pkt.m_ack = htons(0);
                                res_pkt.m_flags = htons(FIN);
                                cout << "Sending FIN packet " << seq << endl;
                                if(sendto(sockfd, &res_pkt, sizeof(res_pkt), 0, (struct sockaddr*) &clientAddr, clilen)<0)
                                {
                                    cerr << "Sendto fails" << endl;
                                    return 1;
                                }
                                FD_CLR(fd, &writeFds);
                                FD_SET(fd, &readFds);
                                break;
                            }
                        }
                            
                    }
            }
        }
     }
    
    close(sockfd);
    }
示例#22
0
void FWadCollection::AddFile (const char *filename, FileReader *wadinfo)
{
    int startlump;
    bool isdir = false;

    if (wadinfo == NULL)
    {
        // Does this exist? If so, is it a directory?
        struct stat info;
        if (stat(filename, &info) != 0)
        {
            Printf(TEXTCOLOR_RED "Could not stat %s\n", filename);
            PrintLastError();
            return;
        }
        isdir = (info.st_mode & S_IFDIR) != 0;

        if (!isdir)
        {
            try
            {
                wadinfo = new FileReader(filename);
            }
            catch (CRecoverableError &err)
            {   // Didn't find file
                Printf (TEXTCOLOR_RED "%s\n", err.GetMessage());
                PrintLastError ();
                return;
            }
        }
    }

    Printf (" adding %s", filename);
    startlump = NumLumps;

    FResourceFile *resfile;

    if (!isdir)
        resfile = FResourceFile::OpenResourceFile(filename, wadinfo);
    else
        resfile = FResourceFile::OpenDirectory(filename);

    if (resfile != NULL)
    {
        DWORD lumpstart = LumpInfo.Size();

        resfile->SetFirstLump(lumpstart);
        for (DWORD i=0; i < resfile->LumpCount(); i++)
        {
            FResourceLump *lump = resfile->GetLump(i);
            FWadCollection::LumpRecord *lump_p = &LumpInfo[LumpInfo.Reserve(1)];

            lump_p->lump = lump;
            lump_p->wadnum = Files.Size();
        }

        if (Files.Size() == IWAD_FILENUM && gameinfo.gametype == GAME_Strife && gameinfo.flags & GI_SHAREWARE)
        {
            resfile->FindStrifeTeaserVoices();
        }
        Files.Push(resfile);

        for (DWORD i=0; i < resfile->LumpCount(); i++)
        {
            FResourceLump *lump = resfile->GetLump(i);
            if (lump->Flags & LUMPF_EMBEDDED)
            {
                FString path;
                path.Format("%s:%s", filename, lump->FullName.GetChars());
                FileReader *embedded = lump->NewReader();
                AddFile(path, embedded);
            }
        }

        if (hashfile)
        {
            BYTE cksum[16];
            char cksumout[33];
            memset(cksumout, 0, sizeof(cksumout));

            FileReader *reader = wadinfo;

            if (reader != NULL)
            {
                MD5Context md5;
                reader->Seek(0, SEEK_SET);
                md5.Update(reader, reader->GetLength());
                md5.Final(cksum);

                for (size_t j = 0; j < sizeof(cksum); ++j)
                {
                    sprintf(cksumout + (j * 2), "%02X", cksum[j]);
                }

                fprintf(hashfile, "file: %s, hash: %s, size: %ld\n", filename, cksumout, reader->GetLength());
            }

            else
                fprintf(hashfile, "file: %s, Directory structure\n", filename);

            for (DWORD i = 0; i < resfile->LumpCount(); i++)
            {
                FResourceLump *lump = resfile->GetLump(i);

                if (!(lump->Flags & LUMPF_EMBEDDED))
                {
                    reader = lump->NewReader();

                    MD5Context md5;
                    md5.Update(reader, lump->LumpSize);
                    md5.Final(cksum);

                    for (size_t j = 0; j < sizeof(cksum); ++j)
                    {
                        sprintf(cksumout + (j * 2), "%02X", cksum[j]);
                    }

                    fprintf(hashfile, "file: %s, lump: %s, hash: %s, size: %d\n", filename,
                            lump->FullName.IsNotEmpty() ? lump->FullName.GetChars() : lump->Name,
                            cksumout, lump->LumpSize);

                    delete reader;
                }
            }
        }
        return;
    }
}
示例#23
0
	// Reads the animation from file
	void AnimationCPU::ReadAnimation(FileReader &f, SkeletonCPU &skel, float positionFactor, int version)
	{
		
		// Read animation
		f.nextNonEmptyLine(m_name, 128);

		// Partial body animation
		PrimitiveTypes::Int32 numJoints;
		
		f.nextInt32(numJoints);
		
		m_numJoints = numJoints;

		m_startJoint = 0; // todo: partial body animation shouldnt be controlled by range, but rather by retargetting array that we have below
		m_endJoint = m_numJoints-1;

		int targetSkelNumJoints = skel.m_numJoints;

		int animJointToSkelJoint[512];
		PEASSERT(m_endJoint < 512, "not enough buffer to retarget, increase 512");

		int jointUsage[512];
		memset(&jointUsage[0], 0, sizeof(jointUsage));
		PEASSERT(skel.m_numJoints < 512, "need to increase buffer");
		if (version < 3) 
		{
			// no retargetting
			for (int i = 0; i < 512; ++i)
				animJointToSkelJoint[i] = i;
		}
		else
		{
			for (int i = 0; i < 512; ++i)
				animJointToSkelJoint[i] = -1;
			// fill in based on names of joints
			for (int iSrcJoint = 0; iSrcJoint < m_numJoints; ++iSrcJoint)
			{
				char fullJointName[256];
				f.nextNonEmptyLine(fullJointName, 256);
				// need find same joint in skel
				// need to strip out maya napesapce in case the rig was referenced in, in which case joint name will be something like mixamorig:Spine
				int pos = StringOps::lfind(fullJointName, ':');
				const char *jointName = fullJointName;
				if (pos != -1)
				{
					jointName = &fullJointName[pos+1];
				}
				for (int iSkelJoint = 0; iSkelJoint < targetSkelNumJoints; ++iSkelJoint)
				{
					FastJoint &fj = skel.m_fastJoints[iSkelJoint];
					if (StringOps::strcmp(fj.m_pJointCPU->m_name, jointName) == 0 || StringOps::strcmp(fj.m_pJointCPU->m_name, fullJointName) == 0)
					{
						animJointToSkelJoint[iSrcJoint] = iSkelJoint;
						break;
					}
				}
			}
		}

		PrimitiveTypes::Int32 numFrames;
		f.nextInt32(numFrames);
		m_frames.reset(numFrames);

		for (PrimitiveTypes::UInt32 iFrame = 0; iFrame < (PrimitiveTypes::UInt32)(numFrames); iFrame++)
		{
			m_frames.add(Array<TSQ>(*m_pContext, m_arena));
			Array<TSQ> &curFrame = m_frames[iFrame];
			curFrame.reset(targetSkelNumJoints);

			// fill in with default values
			for (int iJoint = 0; iJoint < targetSkelNumJoints; ++iJoint)
			{
				FastJoint &fj = skel.m_fastJoints[iJoint];
				Matrix4x4 parentMatrix;
				parentMatrix.loadIdentity();
				
				if (fj.m_parent)
				{
					float *mf = fj.m_parent->m_pJointCPU->m_matrix;
					int iFloat = 0;

					for (PrimitiveTypes::UInt32 row = 0; row < 4; row++)
					{
						for (PrimitiveTypes::UInt32 col = 0; col < 4; col++)
						{
							parentMatrix.m[col][row] = mf[iFloat++];

							// i dont think we need to multiply since we already have a full matrix from bind pose
							//m.setPos(m.getPos() * positionFactor);
						}
					}
				}
				Matrix4x4 m;
				float *mf = fj.m_pJointCPU->m_matrix;
				int iFloat = 0;

				for (PrimitiveTypes::UInt32 row = 0; row < 4; row++)
				{
					for (PrimitiveTypes::UInt32 col = 0; col < 4; col++)
					{
						m.m[col][row] = mf[iFloat++];

						// i dont think we need to multiply since we already have a full matrix from bind pose
						//m.setPos(m.getPos() * positionFactor);
					}
				}
				
				m = parentMatrix.inverse() * m;
				TSQ tsq(m); // this is experimental, not 100 sure it works properly
				curFrame.add(tsq);
			}

			// read the data in
			for (PrimitiveTypes::UInt32 iJoint = 0; iJoint < m_numJoints; iJoint++)
			{
				// read each frame == numJoints matrices
				int targetJoint = animJointToSkelJoint[iJoint]; // might be retargetting or skipping completely

				Matrix4x4 m;
				Vector3 scale(1.0f, 1.0f, 1.0f);
				if (version == 0)
				{
					for (PrimitiveTypes::UInt32 row = 0; row < 4; row++)
					{
						for (PrimitiveTypes::UInt32 col = 0; col < 4; col++)
						{
							PrimitiveTypes::Float32 val;
							f.nextFloat32(val);
							m.m[col][row] = val;
						}
					}
					scale = Vector3(1.f, 1.f, 1.f);
				}
				else if (version == 1 || version == 2 || version == 3)
				{
					// read translation, rotation, scale
					Vector3 pos;
					f.nextFloat32(pos.m_x); f.nextFloat32(pos.m_y); f.nextFloat32(pos.m_z);
					Matrix4x4 tm(pos);


					Matrix3x3 rm;

					if (version == 1)
					{
						Vector3 rot;
						f.nextFloat32(rot.m_x); f.nextFloat32(rot.m_y); f.nextFloat32(rot.m_z);
						rot *= -1.0f;
						rot *= (PrimitiveTypes::Constants::c_Pi_F32 / 180.0f);

						rm = Matrix3x3(Rotate, rot, RotateOrder_ZYX);
					}
					else
					{
						Quaternion q;
						f.nextFloat32(q.m_w); f.nextFloat32(q.m_x); f.nextFloat32(q.m_y); f.nextFloat32(q.m_z);
						rm = Matrix3x3(q);
					}

					if (iJoint == 0)
					{
						f.nextFloat32(scale.m_x); f.nextFloat32(scale.m_y); f.nextFloat32(scale.m_z);
					}
					else
					{
						Vector3 temp;
						f.nextFloat32(temp.m_x); f.nextFloat32(temp.m_y); f.nextFloat32(temp.m_z);
					}
					Matrix3x3 res3x3 = rm;
					Matrix4x4 res(res3x3, pos);
					m = res;
				}

				m.setPos(m.getPos() * positionFactor);

				TSQ tsq(m, scale);
				if (targetJoint != -1)
				{
					curFrame[targetJoint] = tsq;
					jointUsage[targetJoint]++;
				}
				else
					PEINFO("Skipping joint %d\n", iJoint);
			}
		}
	}
示例#24
0
SpriteData::SpriteData(const Pathname& pathname) :
  actions()
{
  if (pathname.exists())
  {
    const std::string ext = pathname.get_extension();

    if (ext == "sprite")
    {
      FileReader reader = FileReader::parse(pathname);

      if(reader.get_name() != "sprite") {
        std::ostringstream msg;
        msg << "File " << pathname << " is not a windstille sprite";
        throw std::runtime_error(msg.str());
      }
    
      parse(pathname.get_dirname(), reader);
    }
    else if (ext == "png" || ext == "jpg")
    {
      std::auto_ptr<SpriteAction> action(new SpriteAction());
      action->name   = "default";
      action->speed  = 1.0;
      action->scale  = 1.0f;
      action->offset = Vector2f(0, 0);
      action->surfaces.push_back(Surface::create(pathname));
      actions.push_back(action.release());
    }
    else
    {
      std::ostringstream str;
      str << "Sprite " << pathname << " has unknown suffix: '" << ext  << "'";
      throw std::runtime_error(str.str());
    }
  }
  else if (pathname.get_raw_path().length() > std::string(".sprite").length())
  { // If sprite file is not found, we search for a file with the
    // same name ending in .png
    Pathname pngfile(pathname.get_raw_path().substr(0, pathname.get_raw_path().length() - std::string(".sprite").length()) + ".png",
                     pathname.get_type());

    if (pngfile.exists())
    {
      std::auto_ptr<SpriteAction> action(new SpriteAction);
      action->name   = "default";
      action->speed  = 1.0;
      action->scale  = 1.0f;
      action->offset = Vector2f(0, 0);
      action->surfaces.push_back(Surface::create(pngfile));
      actions.push_back(action.release());
    }
    else
    {
      std::ostringstream str;
      str << "Couldn't find " << pngfile;
      throw std::runtime_error(str.str());
    }
  }
  else
  {
    std::ostringstream str;
    str << "Couldn't find " << pathname;
    throw std::runtime_error(str.str());
  }
}
示例#25
0
ServerEvent::ServerEvent(const FileReader& reader) :
  type(PINGU_ACTION_EVENT),
  time_stamp(0),
  pingu_id(0),
  pos(),
  pingu_action(ActionName::WALKER)
{
  if (reader.get_name() == "armageddon")
  {
    type = ARMAGEDDON_EVENT;
    reader.read_int("time", time_stamp);
  }
  else if (reader.get_name() == "end")
  {
    type = END_EVENT;
    reader.read_int("time", time_stamp);
  }
  else if (reader.get_name() == "finish")
  {
    type = FINISH_EVENT;
    reader.read_int("time", time_stamp);
  }
  else if (reader.get_name() == "pingu-action")
  {
    std::string raw_x;
    std::string raw_y;

    type = PINGU_ACTION_EVENT;
    reader.read_int ("time",   time_stamp);
    reader.read_int ("id",     pingu_id);

    if (reader.read_string("raw-x", raw_x))
      pos.x = Math::string2float(raw_x);

    if (reader.read_string("raw-y", raw_y))
      pos.y = Math::string2float(raw_y);

    reader.read_enum("action", pingu_action, &ActionName::from_string);

      
  }
  else
  {
    raise_exception(std::runtime_error, "ServerEvent: Parse error: Unknown event: " << reader.get_name());
  }
}
示例#26
0
int FPNGTexture::CopyTrueColorPixels(FBitmap *bmp, int x, int y, int rotate, FCopyInfo *inf)
{
	// Parse pre-IDAT chunks. I skip the CRCs. Is that bad?
	PalEntry pe[256];
	DWORD len, id;
	FileReader *lump;
	static char bpp[] = {1, 0, 3, 1, 2, 0, 4};
	int pixwidth = Width * bpp[ColorType];
	int transpal = false;

	if (SourceLump >= 0)
	{
		lump = new FWadLump(Wads.OpenLumpNum(SourceLump));
	}
	else
	{
		lump = new FileReader(SourceFile.GetChars());
	}

	lump->Seek(33, SEEK_SET);
	for(int i = 0; i < 256; i++)	// default to a gray map
		pe[i] = PalEntry(255,i,i,i);

	lump->Read(&len, 4);
	lump->Read(&id, 4);
	while (id != MAKE_ID('I','D','A','T') && id != MAKE_ID('I','E','N','D'))
	{
		len = BigLong((unsigned int)len);
		switch (id)
		{
		default:
			lump->Seek (len, SEEK_CUR);
			break;

		case MAKE_ID('P','L','T','E'):
			for(int i = 0; i < PaletteSize; i++)
			{
				(*lump) >> pe[i].r >> pe[i].g >> pe[i].b;
			}
			break;

		case MAKE_ID('t','R','N','S'):
			for(DWORD i = 0; i < len; i++)
			{
				(*lump) >> pe[i].a;
				if (pe[i].a != 0 && pe[i].a != 255)
					transpal = true;
			}
			break;
		}
		lump->Seek(4, SEEK_CUR);		// Skip CRC
		lump->Read(&len, 4);
		id = MAKE_ID('I','E','N','D');
		lump->Read(&id, 4);
	}

	BYTE * Pixels = new BYTE[pixwidth * Height];

	lump->Seek (StartOfIDAT, SEEK_SET);
	lump->Read(&len, 4);
	lump->Read(&id, 4);
	M_ReadIDAT (lump, Pixels, Width, Height, pixwidth, BitDepth, ColorType, Interlace, BigLong((unsigned int)len));
	delete lump;

	switch (ColorType)
	{
	case 0:
	case 3:
		bmp->CopyPixelData(x, y, Pixels, Width, Height, 1, Width, rotate, pe, inf);
		break;

	case 2:
		bmp->CopyPixelDataRGB(x, y, Pixels, Width, Height, 3, pixwidth, rotate, CF_RGB, inf);
		break;

	case 4:
		bmp->CopyPixelDataRGB(x, y, Pixels, Width, Height, 2, pixwidth, rotate, CF_IA, inf);
		transpal = -1;
		break;

	case 6:
		bmp->CopyPixelDataRGB(x, y, Pixels, Width, Height, 4, pixwidth, rotate, CF_RGBA, inf);
		transpal = -1;
		break;

	default:
		break;

	}
	delete[] Pixels;
	return transpal;
}
示例#27
0
bool CSoundFile::ReadOpusSample(SAMPLEINDEX sample, FileReader &file)
{
	file.Rewind();

#if defined(MPT_WITH_OPUSFILE)

	int rate = 0;
	int channels = 0;
	std::vector<int16> raw_sample_data;

	FileReader initial = file.GetChunk(65536); // 512 is recommended by libopusfile
	if(op_test(NULL, initial.GetRawData<unsigned char>(), initial.GetLength()) != 0)
	{
		return false;
	}

	OggOpusFile *of = op_open_memory(file.GetRawData<unsigned char>(), file.GetLength(), NULL);
	if(!of)
	{
		return false;
	}

	rate = 48000;
	channels = op_channel_count(of, -1);
	if(rate <= 0 || channels <= 0)
	{
		op_free(of);
		of = NULL;
		return false;
	}
	if(channels > 2 || op_link_count(of) != 1)
	{
		// We downmix multichannel to stereo as recommended by Opus specification in
		// case we are not able to handle > 2 channels.
		// We also decode chained files as stereo even if they start with a mono
		// stream, which simplifies handling of link boundaries for us.
		channels = 2;
	}

	std::vector<int16> decodeBuf(120 * 48000 / 1000); // 120ms (max Opus packet), 48kHz
	bool eof = false;
	while(!eof)
	{
		int framesRead = 0;
		if(channels == 2)
		{
			framesRead = op_read_stereo(of, &(decodeBuf[0]), static_cast<int>(decodeBuf.size()));
		} else if(channels == 1)
		{
			framesRead = op_read(of, &(decodeBuf[0]), static_cast<int>(decodeBuf.size()), NULL);
		}
		if(framesRead > 0)
		{
			raw_sample_data.insert(raw_sample_data.end(), decodeBuf.begin(), decodeBuf.begin() + (framesRead * channels));
		} else if(framesRead == 0)
		{
			eof = true;
		} else if(framesRead == OP_HOLE)
		{
			// continue
		} else
		{
			// other errors are fatal, stop decoding
			eof = true;
		}
	}

	op_free(of);
	of = NULL;

	if(raw_sample_data.empty())
	{
		return false;
	}

	DestroySampleThreadsafe(sample);
	strcpy(m_szNames[sample], "");
	Samples[sample].Initialize();
	Samples[sample].nC5Speed = rate;
	Samples[sample].nLength = raw_sample_data.size() / channels;

	Samples[sample].uFlags.set(CHN_16BIT);
	Samples[sample].uFlags.set(CHN_STEREO, channels == 2);
	Samples[sample].AllocateSample();

	std::copy(raw_sample_data.begin(), raw_sample_data.end(), Samples[sample].pSample16);

	Samples[sample].Convert(MOD_TYPE_IT, GetType());
	Samples[sample].PrecomputeLoops(*this, false);

	return Samples[sample].pSample != nullptr;

#else // !MPT_WITH_OPUSFILE

	MPT_UNREFERENCED_PARAMETER(sample);
	MPT_UNREFERENCED_PARAMETER(file);

	return false;

#endif // MPT_WITH_OPUSFILE

}
示例#28
0
FPNGTexture::FPNGTexture (FileReader &lump, int lumpnum, const FString &filename, int width, int height,
						  BYTE depth, BYTE colortype, BYTE interlace)
: FTexture(NULL, lumpnum), SourceFile(filename), Pixels(0), Spans(0),
  BitDepth(depth), ColorType(colortype), Interlace(interlace), HaveTrans(false),
  PaletteMap(0), PaletteSize(0), StartOfIDAT(0)
{
	union
	{
		DWORD palette[256];
		BYTE pngpal[256][3];
	} p;
	BYTE trans[256];
	DWORD len, id;
	int i;

	UseType = TEX_MiscPatch;
	LeftOffset = 0;
	TopOffset = 0;
	bMasked = false;

	Width = width;
	Height = height;
	CalcBitSize ();

	memset(trans, 255, 256);

	// Parse pre-IDAT chunks. I skip the CRCs. Is that bad?
	lump.Seek(33, SEEK_SET);

	lump.Read(&len, 4);
	lump.Read(&id, 4);
	while (id != MAKE_ID('I','D','A','T') && id != MAKE_ID('I','E','N','D'))
	{
		len = BigLong((unsigned int)len);
		switch (id)
		{
		default:
			lump.Seek (len, SEEK_CUR);
			break;

		case MAKE_ID('g','r','A','b'):
			// This is like GRAB found in an ILBM, except coordinates use 4 bytes
			{
				DWORD hotx, hoty;
				int ihotx, ihoty;
				
				lump.Read(&hotx, 4);
				lump.Read(&hoty, 4);
				ihotx = BigLong((int)hotx);
				ihoty = BigLong((int)hoty);
				if (ihotx < -32768 || ihotx > 32767)
				{
					Printf ("X-Offset for PNG texture %s is bad: %d (0x%08x)\n", Wads.GetLumpFullName (lumpnum), ihotx, ihotx);
					ihotx = 0;
				}
				if (ihoty < -32768 || ihoty > 32767)
				{
					Printf ("Y-Offset for PNG texture %s is bad: %d (0x%08x)\n", Wads.GetLumpFullName (lumpnum), ihoty, ihoty);
					ihoty = 0;
				}
				LeftOffset = ihotx;
				TopOffset = ihoty;
			}
			break;

		case MAKE_ID('P','L','T','E'):
			PaletteSize = MIN<int> (len / 3, 256);
			lump.Read (p.pngpal, PaletteSize * 3);
			if (PaletteSize * 3 != (int)len)
			{
				lump.Seek (len - PaletteSize * 3, SEEK_CUR);
			}
			for (i = PaletteSize - 1; i >= 0; --i)
			{
				p.palette[i] = MAKERGB(p.pngpal[i][0], p.pngpal[i][1], p.pngpal[i][2]);
			}
			break;

		case MAKE_ID('t','R','N','S'):
			lump.Read (trans, len);
			HaveTrans = true;
			// Save for colortype 2
			NonPaletteTrans[0] = WORD(trans[0] * 256 + trans[1]);
			NonPaletteTrans[1] = WORD(trans[2] * 256 + trans[3]);
			NonPaletteTrans[2] = WORD(trans[4] * 256 + trans[5]);
			break;

		case MAKE_ID('a','l','P','h'):
			bAlphaTexture = true;
			bMasked = true;
			break;
		}
		lump.Seek(4, SEEK_CUR);		// Skip CRC
		lump.Read(&len, 4);
		id = MAKE_ID('I','E','N','D');
		lump.Read(&id, 4);
	}
	StartOfIDAT = lump.Tell() - 8;

	switch (colortype)
	{
	case 4:		// Grayscale + Alpha
		bMasked = true;
		// intentional fall-through

	case 0:		// Grayscale
		if (!bAlphaTexture)
		{
			if (colortype == 0 && HaveTrans && NonPaletteTrans[0] < 256)
			{
				bMasked = true;
				PaletteSize = 256;
				PaletteMap = new BYTE[256];
				memcpy (PaletteMap, GrayMap, 256);
				PaletteMap[NonPaletteTrans[0]] = 0;
			}
			else
			{
				PaletteMap = GrayMap;
			}
		}
		break;

	case 3:		// Paletted
		PaletteMap = new BYTE[PaletteSize];
		GPalette.MakeRemap (p.palette, PaletteMap, trans, PaletteSize);
		for (i = 0; i < PaletteSize; ++i)
		{
			if (trans[i] == 0)
			{
				bMasked = true;
				PaletteMap[i] = 0;
			}
		}
		break;

	case 6:		// RGB + Alpha
		bMasked = true;
		break;

	case 2:		// RGB
		bMasked = HaveTrans;
		break;
	}
}
示例#29
0
 Drawable(FileReader reader)
   : visible(true)
 {
   reader.read_string("name", name);
 }
示例#30
0
文件: Main.cpp 项目: hcmlab/mobileSSI
bool ex_qrs_heartrate_mean(void *args) {

	if (!ssi_exists("data/ecg_qrs.stream")) {
		ex_ecg_detection(args);
	}

	ITheFramework *frame = Factory::GetFramework();

	Decorator *decorator = ssi_create(Decorator, 0, true);
	frame->AddDecorator(decorator);

	ITheEventBoard *board = Factory::GetEventBoard();

	//raw
	FileReader *reader = ssi_create(FileReader, 0, true);
	reader->getOptions()->setPath("data/ecg_qrs");
	reader->getOptions()->block = 0.2;
	ITransformable *qrs_p = frame->AddProvider(reader, SSI_FILEREADER_PROVIDER_NAME);
	frame->AddSensor(reader);

	// heart rate
	QRSHeartRate *qrshr = ssi_create(QRSHeartRate, 0, true);
	ITransformable *ecg_hr_t = frame->AddTransformer(qrs_p, qrshr, "0.25s");

	//heart rate mean
	QRSHeartRateMean *qrshr_mean = ssi_create(QRSHeartRateMean, 0, true);
	qrshr_mean->getOptions()->winsize = 15.0;
	frame->AddConsumer(ecg_hr_t, qrshr_mean, "0.25s");
	board->RegisterSender(*qrshr_mean);

	//visual
	SignalPainter *plot = 0;
	ssi_real_t p_size = 100.0f;

	//qrs
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("qrs");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(qrs_p, plot, "0.3s");

	//heart rate
	plot = ssi_create_id(SignalPainter, 0, "plot");
	plot->getOptions()->setTitle("heartrate");
	plot->getOptions()->size = p_size;
	frame->AddConsumer(ecg_hr_t, plot, "0.3s");

	//events
	EventMonitor *monitor = ssi_create_id(EventMonitor, 0, "monitor");
	board->RegisterListener(*monitor, qrshr_mean->getEventAddress());

	//framework

	decorator->add("console", 0, 0, 650, 800);
	decorator->add("plot*", 650, 0, 400, 400);
	decorator->add("monitor*", 650, 400, 400, 400);

	board->Start();
	frame->Start();

	frame->Wait();
	frame->Stop();
	board->Stop();
	frame->Clear();
	board->Clear();

	return true;
}