VBool vHavokVisualDebuggerAction::Do(const class VArgList &argList)
{
  if (argList.GetArgCount()==1 && argList.IsString(1)) 
  {
    vHavokPhysicsModule *pMod = vHavokPhysicsModule::GetInstance();
    if (!pMod)
    {
      PrintWarning("Could not retrieve an instance of Havok Physics module.");
      return FALSE;
    }

    const char *szArg = argList.AsString(1);
    if (_stricmp(szArg, "on")==0)
    {
      pMod->SetEnabledVisualDebugger(TRUE);
      Print("Enabled Havok Visual Debugger.");
      return TRUE;
    }
    else if (_stricmp(szArg, "off")==0)
    {
      pMod->SetEnabledVisualDebugger(FALSE);
      Print("Disabled Havok Visual Debugger.");
      return TRUE;
    }
    else
      PrintWarning("Invalid argument. Valid arguments are: [on] for enabling and [off] for disabling.");

    return FALSE;
  }
   
  PrintWarning("Invalid argument. Valid arguments are: [on] for enabling and [off] for disabling.");
  return FALSE;
}
Пример #2
0
bool ViewControl::ConvertToPinholeCameraParameters(
        PinholeCameraIntrinsic &intrinsic, Eigen::Matrix4d &extrinsic)
{
    if (window_height_ <= 0 || window_width_ <= 0) {
        PrintWarning("[ViewControl] ConvertToPinholeCameraParameters() failed because window height and width are not set.\n");
        return false;
    }
    if (GetProjectionType() == ProjectionType::Orthogonal) {
        PrintWarning("[ViewControl] ConvertToPinholeCameraParameters() failed because orthogonal view cannot be translated to a pinhole camera.\n");
        return false;
    }
    SetProjectionParameters();
    intrinsic.width_ = window_width_;
    intrinsic.height_ = window_height_;
    intrinsic.intrinsic_matrix_.setIdentity();
    double fov_rad = field_of_view_ / 180.0 * M_PI;
    double tan_half_fov = std::tan(fov_rad / 2.0);
    intrinsic.intrinsic_matrix_(0, 0) = intrinsic.intrinsic_matrix_(1, 1) =
            (double)window_height_ / tan_half_fov / 2.0;
    intrinsic.intrinsic_matrix_(0, 2) = (double)window_width_ / 2.0 - 0.5;
    intrinsic.intrinsic_matrix_(1, 2) = (double)window_height_ / 2.0 - 0.5;
    extrinsic.setZero();
    Eigen::Vector3d front_dir = front_.normalized();
    Eigen::Vector3d up_dir = up_.normalized();
    Eigen::Vector3d right_dir = right_.normalized();
    extrinsic.block<1, 3>(0, 0) = right_dir.transpose();
    extrinsic.block<1, 3>(1, 0) = -up_dir.transpose();
    extrinsic.block<1, 3>(2, 0) = -front_dir.transpose();
    extrinsic(0, 3) = -right_dir.dot(eye_);
    extrinsic(1, 3) = up_dir.dot(eye_);
    extrinsic(2, 3) = front_dir.dot(eye_);
    extrinsic(3, 3) = 1.0;
    return true;
}
Пример #3
0
bool ReadImageFromJPG(const std::string &filename, Image &image)
{
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    FILE *file_in;
    JSAMPARRAY buffer;

    if ((file_in = fopen(filename.c_str(), "rb")) == NULL) {
        PrintWarning("Read JPG failed: unable to open file: %s\n", filename.c_str());
        return false;
    }

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_decompress(&cinfo);
    jpeg_stdio_src(&cinfo, file_in);
    jpeg_read_header(&cinfo, TRUE);

    // We only support two channel types: gray, and RGB.
    int num_of_channels = 3;
    int bytes_per_channel = 1;
    switch (cinfo.jpeg_color_space) {
    case JCS_RGB:
    case JCS_YCbCr:
        cinfo.out_color_space = JCS_RGB;
        cinfo.out_color_components = 3;
        num_of_channels = 3;
        break;
    case JCS_GRAYSCALE:
        cinfo.jpeg_color_space = JCS_GRAYSCALE;
        cinfo.out_color_components = 1;
        num_of_channels = 1;
        break;
    case JCS_CMYK:
    case JCS_YCCK:
    default:
        PrintWarning("Read JPG failed: color space not supported.\n");
        jpeg_destroy_decompress(&cinfo);
        fclose(file_in);
        return false;
    }
    jpeg_start_decompress(&cinfo);
    image.PrepareImage(cinfo.output_width, cinfo.output_height,
            num_of_channels, bytes_per_channel);
    int row_stride = cinfo.output_width * cinfo.output_components;
    buffer = (*cinfo.mem->alloc_sarray)
            ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
    uint8_t *pdata = image.data_.data();
    while (cinfo.output_scanline < cinfo.output_height) {
        jpeg_read_scanlines(&cinfo, buffer, 1);
        memcpy(pdata, buffer[0], row_stride);
        pdata += row_stride;
    }
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    fclose(file_in);
    return true;
}
Пример #4
0
//--------------------------------------------------------------------------------------------------
void CheckForLimitsConflicts
(
    const legato::App& app
)
//--------------------------------------------------------------------------------------------------
{
    size_t maxMemoryBytes = app.MaxMemoryBytes().Get();
    size_t maxFileSystemBytes = app.MaxFileSystemBytes().Get();

    for (const auto& procEnv : app.ProcEnvironments())
    {
        size_t maxLockedMemoryBytes = procEnv.MaxLockedMemoryBytes().Get();

        if (maxLockedMemoryBytes > maxMemoryBytes)
        {
            std::stringstream warning;
            warning << "maxLockedMemoryBytes (" << maxLockedMemoryBytes
                    << ") will be limited by the maxMemoryBytes limit (" << maxMemoryBytes << ").";
            PrintWarning(app, warning.str());
        }

        size_t maxFileBytes = procEnv.MaxFileBytes().Get();
        size_t maxCoreDumpFileBytes = procEnv.MaxCoreDumpFileBytes().Get();

        if (maxCoreDumpFileBytes > maxFileBytes)
        {
            std::stringstream warning;
            warning << "maxCoreDumpFileBytes (" << maxCoreDumpFileBytes
                    << ") will be limited by the maxFileBytes limit (" << maxFileBytes << ").";
            PrintWarning(app, warning.str());
        }

        if (maxCoreDumpFileBytes > maxFileSystemBytes)
        {
            std::stringstream warning;
            warning << "maxCoreDumpFileBytes (" << maxCoreDumpFileBytes
                    << ") will be limited by the maxFileSystemBytes limit ("
                    << maxFileSystemBytes << ") if the core file is inside the sandbox temporary"
                    " file system.";
            PrintWarning(app, warning.str());
        }

        if (maxFileBytes > maxFileSystemBytes)
        {
            std::stringstream warning;
            warning << "maxFileBytes (" << maxFileBytes
                    << ") will be limited by the maxFileSystemBytes limit ("
                    << maxFileSystemBytes << ") if the file is inside the sandbox temporary"
                    " file system.";
            PrintWarning(app, warning.str());
        }
    }
}
Пример #5
0
bool WriteImageToJPG(const std::string &filename, const Image &image,
        int quality/* = 90*/)
{
    if (image.HasData() == false) {
        PrintWarning("Write JPG failed: image has no data.\n");
        return false;
    }
    if (image.bytes_per_channel_ != 1 ||
            (image.num_of_channels_ != 1 && image.num_of_channels_ != 3)) {
        PrintWarning("Write JPG failed: unsupported image data.\n");
        return false;
    }
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    FILE *file_out;
    JSAMPROW row_pointer[1];

    if ((file_out = fopen(filename.c_str(), "wb")) == NULL) {
        PrintWarning("Write JPG failed: unable to open file: %s\n", filename.c_str());
        return false;
    }

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);
    jpeg_stdio_dest(&cinfo, file_out);
    cinfo.image_width = image.width_;
    cinfo.image_height = image.height_;
    cinfo.input_components = image.num_of_channels_;
    cinfo.in_color_space =
            (cinfo.input_components == 1 ? JCS_GRAYSCALE : JCS_RGB);
    jpeg_set_defaults(&cinfo);
    jpeg_set_quality(&cinfo, quality, TRUE);
    jpeg_start_compress(&cinfo, TRUE);
    int row_stride = image.width_ * image.num_of_channels_;
    const uint8_t *pdata = image.data_.data();
    std::vector<uint8_t> buffer(row_stride);
    while (cinfo.next_scanline < cinfo.image_height) {
        memcpy(buffer.data(), pdata, row_stride);
        row_pointer[0] = buffer.data();
        jpeg_write_scanlines(&cinfo, row_pointer, 1);
        pdata += row_stride;
    }
    jpeg_finish_compress(&cinfo);
    fclose(file_out);
    jpeg_destroy_compress(&cinfo);
    return true;
}
Пример #6
0
STLGeometry *  STLTopology :: LoadBinary (istream & ist)
{
  STLGeometry * geom = new STLGeometry();
  Array<STLReadTriangle> readtrigs;

  PrintMessage(1,"Read STL binary file");
  
  if (sizeof(int) != 4 || sizeof(float) != 4) 
    {
      PrintWarning("for stl-binary compatibility only use 32 bit compilation!!!");
    }

  //specific settings for stl-binary format
  const int namelen = 80; //length of name of header in file
  const int nospaces = 2; //number of spaces after a triangle

  //read header: name
  char buf[namelen+1];
  FIOReadStringE(ist,buf,namelen);
  PrintMessage(5,"header = ",buf);

  //Read Number of facets
  int nofacets;
  FIOReadInt(ist,nofacets);
  PrintMessage(5,"NO facets = ",nofacets);

  Point<3> pts[3];
  Vec<3> normal;

  char spaces[nospaces+1];

  for (int cntface = 0; cntface < nofacets; cntface++)
    {
      if (cntface % 10000 == 0)
	// { PrintDot(); } 
	PrintMessageCR (3, cntface, " triangles loaded\r");

      float f;
      FIOReadFloat(ist,f); normal(0) = f;
      FIOReadFloat(ist,f); normal(1) = f;
      FIOReadFloat(ist,f); normal(2) = f;
      
      for (int j = 0; j < 3; j++)
	{
	  FIOReadFloat(ist,f); pts[j](0) = f;
	  FIOReadFloat(ist,f); pts[j](1) = f;
	  FIOReadFloat(ist,f); pts[j](2) = f;	  
	} 

      readtrigs.Append (STLReadTriangle (pts, normal));
      FIOReadString(ist,spaces,nospaces);
    }	    
  PrintMessage (3, nofacets, " triangles loaded\r");  

  geom->InitSTLGeometry(readtrigs);

  return geom;
}
Пример #7
0
void STLTopology :: SaveBinary (const char* filename, const char* aname) const
{
  ofstream ost(filename);
  PrintFnStart("Write STL binary file '",filename,"'");

  if (sizeof(int) != 4 || sizeof(float) != 4) 
    {PrintWarning("for stl-binary compatibility only use 32 bit compilation!!!");}

  //specific settings for stl-binary format
  const int namelen = 80; //length of name of header in file
  const int nospaces = 2; //number of spaces after a triangle

  //write header: aname
  int i, j;
  char buf[namelen+1];
  int strend = 0;
  for(i = 0; i <= namelen; i++) 
    {
      if (aname[i] == 0) {strend = 1;}
      if (!strend) {buf[i] = aname[i];}
      else {buf[i] = 0;}
    }

  FIOWriteString(ost,buf,namelen);
  PrintMessage(5,"header = ",buf);

  //RWrite Number of facets
  int nofacets = GetNT();
  FIOWriteInt(ost,nofacets);
  PrintMessage(5,"NO facets = ", nofacets);

  float f;
  char spaces[nospaces+1];
  for (i = 0; i < nospaces; i++) {spaces[i] = ' ';}
  spaces[nospaces] = 0;

  for (i = 1; i <= GetNT(); i++)
    {
      const STLTriangle & t = GetTriangle(i);

      const Vec<3> & n = t.Normal();
      f = n(0); FIOWriteFloat(ost,f);
      f = n(1); FIOWriteFloat(ost,f);
      f = n(2); FIOWriteFloat(ost,f);

      for (j = 1; j <= 3; j++)
	{
	  const Point3d p = GetPoint(t.PNum(j));
	  
	  f = p.X(); FIOWriteFloat(ost,f);
	  f = p.Y(); FIOWriteFloat(ost,f);
	  f = p.Z(); FIOWriteFloat(ost,f);
	}
      FIOWriteString(ost,spaces,nospaces);
    }
  PrintMessage(5,"done");
}
Пример #8
0
void CCmdCat::WriteChunkToConsoleL(const TDesC8& aData, TReadType aType)
	{
	if (iEncoding == EBinary)
		{
		iBuf16.Copy(aData);
		Write(iBuf16);
		if (aType == MFileReaderObserver::ELast)
			{
			RemoveCurrentFileName();
			ReadNextFile();
			}
		}
	else if (iEncoding == ELtkUtf8)
		{
		iBuf16.Zero();
		iBuf16.AppendUtf8L(aData);
		Write(iBuf16);
		if (aType == MFileReaderObserver::ELast)
			{
			TInt firstBad;
			iBuf16.FinalizeUtf8(firstBad);
			if (firstBad != KErrNotFound) PrintWarning(_L("Found bad UTF-8 sequence in %S at byte offset %d"), &iFiles[0], firstBad);

			RemoveCurrentFileName();
			ReadNextFile();
			}
		}
	else
		{
		switch (aType)
			{
			case MFileReaderObserver::EFirst:
				{
				Write(iCharacterConverter->ConvertChunkL(aData, CCharacterConverter::EFirst));
				break;
				}
			case MFileReaderObserver::EMiddle:
				{
				Write(iCharacterConverter->ConvertChunkL(aData, CCharacterConverter::EMiddle));
				break;
				}
			case MFileReaderObserver::ELast:
				{
				Write(iCharacterConverter->ConvertChunkL(aData, CCharacterConverter::ELast));
				RemoveCurrentFileName();
				ReadNextFile();
				break;
				}
			default:
				{
				ASSERT(FALSE);
				}
			}
		}
	}
Пример #9
0
bool ViewControl::ConvertFromPinholeCameraParameters(
        const PinholeCameraIntrinsic &intrinsic,
        const Eigen::Matrix4d &extrinsic)
{
    if (window_height_ <= 0 || window_width_ <= 0 ||
            window_height_ != intrinsic.height_ ||
            window_width_ != intrinsic.width_ ||
            intrinsic.intrinsic_matrix_(0, 2) !=
            (double)window_width_ / 2.0 - 0.5 ||
            intrinsic.intrinsic_matrix_(1, 2) !=
            (double)window_height_ / 2.0 - 0.5) {
        PrintWarning("[ViewControl] ConvertFromPinholeCameraParameters() failed because window height and width do not match.\n");
        return false;
    }
    double tan_half_fov =
            (double)window_height_ / (intrinsic.intrinsic_matrix_(1, 1) * 2.0);
    double fov_rad = std::atan(tan_half_fov) * 2.0;
    double old_fov = field_of_view_;
    field_of_view_ = std::max(std::min(fov_rad * 180.0 / M_PI,
            FIELD_OF_VIEW_MAX), FIELD_OF_VIEW_MIN);
    if (GetProjectionType() == ProjectionType::Orthogonal) {
        field_of_view_ = old_fov;
        PrintWarning("[ViewControl] ConvertFromPinholeCameraParameters() failed because field of view is impossible.\n");
        return false;
    }
    right_ = extrinsic.block<1, 3>(0, 0).transpose();
    up_ = -extrinsic.block<1, 3>(1, 0).transpose();
    front_ = -extrinsic.block<1, 3>(2, 0).transpose();
    eye_ = extrinsic.block<3, 3>(0, 0).inverse() *
            (extrinsic.block<3, 1>(0, 3) * -1.0);
    double ideal_distance = (eye_ - bounding_box_.GetCenter()).dot(front_);
    double ideal_zoom = ideal_distance *
            std::tan(field_of_view_ * 0.5 / 180.0 * M_PI) /
            bounding_box_.GetSize();
    zoom_ = std::max(std::min(ideal_zoom, ZOOM_MAX), ZOOM_MIN);
    view_ratio_ = zoom_ * bounding_box_.GetSize();
    distance_ = view_ratio_ /
            std::tan(field_of_view_ * 0.5 / 180.0 * M_PI);
    lookat_ = eye_ - front_ * distance_;
    return true;
}
Пример #10
0
void CCmdCat::HandleFileData(const TDesC8& aData, TReadType aType, TBool& aContinue)
	{
	aContinue = ETrue;
	TRAPD(err, WriteChunkToConsoleL(aData, aType));
	if (err)
		{
		aContinue = EFalse;
		PrintWarning(_L("Problem writing chunk of %S to console: %d"), &iFiles[0], err);
		RemoveCurrentFileName();
		ReadNextFile();
		}
	}
Пример #11
0
 void Debug::PrintAtLevel(const Char* message, DebugLevel level) {
     switch (level) {
         case DebugLevel::Normal:
         PrintMessage(message);
         break;
         case DebugLevel::Warning:
         PrintWarning(message);
         break;
         case DebugLevel::Error:
         PrintError(message);
         break;
     }
 }
Пример #12
0
void COGLTexture2D::GenerateMipMaps()
{
	if(m_GenMipMaps)
	{
		COGLBindLock lock(this, COGL_TEXTURE0_SLOT);
		glGenerateMipmap(GL_TEXTURE_2D);
	}
	else
	{
		std::string warning = "GenerateMipMaps() was called but automatic " 
			"MipMap generation was not activated at initialization.";
		PrintWarning(warning);
	}
}
Пример #13
0
/// Environ::Warn
void Environ::Warn(const class Exception &exc)
{  
  m_WarnRoot.m_Exception    = exc;
  //
  // Is the user warned about this exception already? If so,
  // do not do this again.
  if (!m_bSuppressMultiple || !isWarned(exc)) {
    // Deliver this message to the exception hook
    ForwardMessage(m_pWarningHook,m_WarningTags,m_WarnRoot.m_Exception);
    //
    // On debugging, print out the warning immediately
    PrintWarning();
  }
}
Пример #14
0
bool WritePointCloudToXYZ(const std::string &filename,
        const PointCloud &pointcloud, bool write_ascii/* = false*/,
        bool compressed/* = false*/)
{
    FILE *file = fopen(filename.c_str(), "w");
    if (file == NULL) {
        PrintWarning("Write XYZ failed: unable to open file: %s\n", filename.c_str());
        return false;
    }

    for (size_t i = 0; i < pointcloud.points_.size(); i++) {
        const Eigen::Vector3d &point = pointcloud.points_[i];
        if (fprintf(file, "%.10f %.10f %.10f\n",
                point(0), point(1), point(2)) < 0)
        {
            PrintWarning("Write XYZ failed: unable to write file: %s\n", filename.c_str());
            fclose(file);
            return false;    // error happens during writing.
        }
    }

    fclose(file);
    return true;
}
Пример #15
0
  void DisparityPlugin::TopicEdited()
  {
    if (ui_.topic->text().toStdString() != topic_)
    {
      initialized_ = false;
      has_message_ = false;
      topic_ = ui_.topic->text().toStdString();
      PrintWarning("No messages received.");

      disparity_sub_.shutdown();
      disparity_sub_ = node_.subscribe(topic_, 1, &DisparityPlugin::disparityCallback, this);

      ROS_INFO("Subscribing to %s", topic_.c_str());
    }
  }
Пример #16
0
void CCmdKill::DoFindIdAndKillL(const TDesC& aPattern)
	{
	TFullName fullName;
	TInt numFound = 0;
	TFindProcessOrThread finder(aPattern);
	while (finder.Next(fullName) == KErrNone)
		{
		RProcessOrThread handle;
		TInt err = handle.Open(finder, EOwnerThread);
		if ((err == KErrNone) && (handle.ExitType() == EExitPending))
			{
			++numFound;
			TUint id = handle.Id().Id();
			handle.Close();
			if (iAll || numFound == 1)
				{
				KillIdL(id);
				}
			}
		else if (err)
			{
			PrintWarning(_L("Couldn't open %S (err=%d)"), &fullName);
			}
		}
	if (!iAll)
		{
		if (numFound == 0)
			{
			LeaveIfErr(KErrNotFound, _L("No matches for pattern \"%S\", or all matches are zombies"), &aPattern);
			}
		else if (numFound > 1)
			{
			PrintWarning(_L("%d further matches for pattern \"%S\" found, be more specific or use --all option"), numFound-1, &aPattern);
			}
		}
	}
Пример #17
0
  void LaserScanPlugin::TopicEdited()
  {
    if (ui_.topic->text().toStdString() != topic_)
    {
      initialized_ = false;
      scans_.clear();
      has_message_ = false;
      topic_ = boost::trim_copy(ui_.topic->text().toStdString());
      PrintWarning("No messages received.");

      laserscan_sub_.shutdown();
      laserscan_sub_ = node_.subscribe(topic_, 100, &LaserScanPlugin::laserScanCallback, this);

      ROS_INFO("Subscribing to %s", topic_.c_str());
    }
  }
  void AttitudeIndicatorPlugin::TopicEdited()
  {
    std::string topic = ui_.topic->text().trimmed().toStdString();
    if (topic != topic_)
    {
      initialized_ = true;
      PrintWarning("No messages received.");

      odometry_sub_.shutdown();
      topic_ = topic;
      if (!topic_.empty())
      {
        odometry_sub_ = node_.subscribe<topic_tools::ShapeShifter>(
            topic_, 100, &AttitudeIndicatorPlugin::handleMessage, this);

        ROS_INFO("Subscribing to %s", topic_.c_str());
      }
    }
  }
Пример #19
0
bool ReadPointCloudFromXYZ(const std::string &filename, PointCloud &pointcloud)
{
    FILE *file = fopen(filename.c_str(), "r");
    if (file == NULL) {
        PrintWarning("Read XYZ failed: unable to open file: %s\n", filename.c_str());
        return false;
    }

    char line_buffer[DEFAULT_IO_BUFFER_SIZE];
    double x, y, z;
    pointcloud.Clear();

    while (fgets(line_buffer, DEFAULT_IO_BUFFER_SIZE, file)) {
        if (sscanf(line_buffer, "%lf %lf %lf", &x, &y, &z) == 3) {
            pointcloud.points_.push_back(Eigen::Vector3d(x, y, z));
        }
    }

    fclose(file);
    return true;
}
Пример #20
0
static void anim_arci_cb (FL_OBJECT * obj, long arg) {
  switch (arg) {
  case 10 :
    ZANIM->ColOptions.ColBlockExtTime = fl_get_slider_value(ARCI_REAC_TIME);
    anim_col_avoidance_step1(ZANIM);
    anim_udpate_nof_blocks();
    anim_udpate_solved();
    anim_interface_update();
    break;
  case 11 : 
    ZANIM->ColOptions.NofAttempts = fl_get_slider_value(ARCI_NOF_ATTEMPTS);
    anim_col_avoidance_step2(ZANIM);
    anim_udpate_nof_blocks();
    anim_udpate_solved();
    anim_udpate_optimized();
    break;
  case 12 :
    anim_show_form(ZANIM->ColAvoidRes, ZANIM->Robot);
    break;
  case 13 :
    anim_col_avoidance_step3(ZANIM);
    anim_udpate_optimized();    
    break;
  case 14 :
    anim_show_form(ZANIM->ColOpt2Res, ZANIM->Robot);
    break;
  case 15 :
    fl_hide_form(ARCI);
    fl_free_form(ARCI);
    ARCI = NULL;
    anim_interface_update();
    break;
  default :
    PrintWarning (("anim_reac_col_interface.c -- unknown command"));
    break;
  }
}
Пример #21
0
void ViewControl::SetViewMatrices(
        const Eigen::Matrix4d &model_matrix/* = Eigen::Matrix4d::Identity()*/)
{
    if (window_height_ <= 0 || window_width_ <= 0) {
        PrintWarning("[ViewControl] SetViewPoint() failed because window height and width are not set.");
        return;
    }
    glViewport(0, 0, window_width_, window_height_);
    if (GetProjectionType() == ProjectionType::Perspective)
    {
        // Perspective projection
        z_near_ = std::max(0.01 * bounding_box_.GetSize(),
                distance_ - 3.0 * bounding_box_.GetSize());
        z_far_ = distance_ + 3.0 * bounding_box_.GetSize();
        projection_matrix_ = GLHelper::Perspective(field_of_view_, aspect_,
                z_near_, z_far_);
    } else {
        // Orthogonal projection
        // We use some black magic to support distance_ in orthogonal view
        z_near_ = distance_ - 3.0 * bounding_box_.GetSize();
        z_far_ = distance_ + 3.0 * bounding_box_.GetSize();
        projection_matrix_ = GLHelper::Ortho(
                -aspect_ * view_ratio_,    aspect_ * view_ratio_,
                -view_ratio_, view_ratio_, z_near_, z_far_);
    }
    view_matrix_ = GLHelper::LookAt(eye_, lookat_, up_ );
    model_matrix_ = model_matrix.cast<GLfloat>();
    MVP_matrix_ = projection_matrix_ * view_matrix_ * model_matrix_;

    // uncomment to use the deprecated functions of legacy OpenGL
    //glMatrixMode(GL_PROJECTION);
    //glLoadIdentity();
    //glMatrixMode(GL_MODELVIEW);
    //glLoadIdentity();
    //glMultMatrixf(MVP_matrix_.data());
}
Пример #22
0
/**
 * Open file
 *
 * @v This			File handle
 * @ret new			New file handle
 * @v Name			File name
 * @v Mode			File mode
 * @v Attributes	File attributes (for newly-created files)
 * @ret Status		EFI status code
 */
static EFI_STATUS EFIAPI
FileOpen(EFI_FILE_HANDLE This, EFI_FILE_HANDLE *New,
		CHAR16 *Name, UINT64 Mode, UINT64 Attributes)
{
	EFI_STATUS Status;
	EFI_GRUB_FILE *File = _CR(This, EFI_GRUB_FILE, EfiFile);
	EFI_GRUB_FILE *NewFile;

	// TODO: Use dynamic buffers?
	char path[MAX_PATH], clean_path[MAX_PATH], *dirname;
	INTN i, len;
	BOOLEAN AbsolutePath = (*Name == L'\\');

	PrintInfo(L"Open(%llx%s, \"%s\")\n", (UINT64) This,
			IS_ROOT(File)?L" <ROOT>":L"", Name);

	/* Fail unless opening read-only */
	if (Mode != EFI_FILE_MODE_READ) {
		PrintWarning(L"File '%s' can only be opened in read-only mode\n", Name);
		return EFI_WRITE_PROTECTED;
	}

	/* Additional failures */
	if ((StrCmp(Name, L"..") == 0) && IS_ROOT(File)) {
		PrintInfo(L"Trying to open <ROOT>'s parent\n");
		return EFI_NOT_FOUND;
	}

	/* See if we're trying to reopen current (which the EFI Shell insists on doing) */
	if ((*Name == 0) || (StrCmp(Name, L".") == 0)) {
		PrintInfo(L"  Reopening %s\n", IS_ROOT(File)?L"<ROOT>":FileName(File));
		File->RefCount++;
		*New = This;
		PrintInfo(L"  RET: %llx\n", (UINT64) *New);
		return EFI_SUCCESS;
	}

	/* If we have an absolute path, don't bother completing with the parent */
	if (AbsolutePath) {
		len = 0;
	} else {
		strcpya(path, File->path);
		len = strlena(path);
		/* Add delimiter if needed */
		if ((len == 0) || (path[len-1] != '/'))
			path[len++] = '/';
	}

	/* Copy the rest of the path (converted to UTF-8) */
	Status = Utf16ToUtf8NoAlloc(Name, &path[len], sizeof(path) - len);
	if (EFI_ERROR(Status)) {
		PrintStatusError(Status, L"Could not convert path to UTF-8");
		return Status;
	}
	/* Convert the delimiters */
	for (i = strlena(path) - 1 ; i >= len; i--) {
		if (path[i] == '\\')
			path[i] = '/';
	}

	/* We only want to handle with absolute paths */
	clean_path[0] = '/';
	/* Find out if we're dealing with root by removing the junk */
	CopyPathRelative(&clean_path[1], path, MAX_PATH - 1);
	if (clean_path[1] == 0) {
		/* We're dealing with the root */
		PrintInfo(L"  Reopening <ROOT>\n");
		*New = &File->FileSystem->RootFile->EfiFile;
		/* Must make sure that DirIndex is reset too (NB: no concurrent access!) */
		File->FileSystem->RootFile->DirIndex = 0;
		PrintInfo(L"  RET: %llx\n", (UINT64) *New);
		return EFI_SUCCESS;
	}

	// TODO: eventually we should seek for already opened files and increase RefCount */
	/* Allocate and initialise an instance of a file */
	Status = GrubCreateFile(&NewFile, File->FileSystem);
	if (EFI_ERROR(Status)) {
		PrintStatusError(Status, L"Could not instantiate file");
		return Status;
	}

	NewFile->path = AllocatePool(strlena(clean_path)+1);
	if (NewFile->path == NULL) {
		GrubDestroyFile(NewFile);
		PrintError(L"Could not instantiate path\n");
		return EFI_OUT_OF_RESOURCES;
	}
	strcpya(NewFile->path, clean_path);

	/* Isolate the basename and dirname */
	// TODO: would be nicer to have those if path.c
	for (i = strlena(clean_path) - 1; i >= 0; i--) {
		if (clean_path[i] == '/') {
			clean_path[i] = 0;
			break;
		}
	}
	dirname = (i <= 0) ? "/" : clean_path;
	NewFile->basename = &NewFile->path[i+1];

	/* Find if we're working with a directory and fill the grub timestamp */
	Status = GrubDir(NewFile, dirname, InfoHook, (VOID *) NewFile);
	if (EFI_ERROR(Status)) {
		if (Status != EFI_NOT_FOUND)
			PrintStatusError(Status, L"Could not get file attributes for '%s'", Name);
		FreePool(NewFile->path);
		GrubDestroyFile(NewFile);
		return Status;
	}

	/* Finally we can call on GRUB open() if it's a regular file */
	if (!NewFile->IsDir) {
		Status = GrubOpen(NewFile);
		if (EFI_ERROR(Status)) {
			if (Status != EFI_NOT_FOUND)
				PrintStatusError(Status, L"Could not open file '%s'", Name);
			FreePool(NewFile->path);
			GrubDestroyFile(NewFile);
			return Status;
		}
	}

	NewFile->RefCount++;
	*New = &NewFile->EfiFile;

	PrintInfo(L"  RET: %llx\n", (UINT64) *New);
	return EFI_SUCCESS;
}
Пример #23
0
/**
 * Get file information
 *
 * @v This			File handle
 * @v Type			Type of information
 * @v Len			Buffer size
 * @v Data			Buffer
 * @ret Status		EFI status code
 */
static EFI_STATUS EFIAPI
FileGetInfo(EFI_FILE_HANDLE This, EFI_GUID *Type, UINTN *Len, VOID *Data)
{
	EFI_STATUS Status;
	EFI_GRUB_FILE *File = _CR(This, EFI_GRUB_FILE, EfiFile);
	EFI_FILE_SYSTEM_INFO *FSInfo = (EFI_FILE_SYSTEM_INFO *) Data;
	EFI_FILE_INFO *Info = (EFI_FILE_INFO *) Data;
	CHAR16 GuidString[36];
	EFI_TIME Time;
	CHAR8* label;

	PrintInfo(L"GetInfo(%llx|'%s', %d) %s\n", (UINT64) This,
		FileName(File), *Len, File->IsDir?L"<DIR>":L"");

	/* Determine information to return */
	if (CompareMem(Type, &GenericFileInfo, sizeof(*Type)) == 0) {

		/* Fill file information */
		PrintExtra(L"Get regular file information\n");
		if (*Len < MINIMUM_INFO_LENGTH) {
			*Len = MINIMUM_INFO_LENGTH;
			return EFI_BUFFER_TOO_SMALL;
		}

		ZeroMem(Data, sizeof(EFI_FILE_INFO));

		Info->Attribute = EFI_FILE_READ_ONLY;
		GrubTimeToEfiTime(File->Mtime, &Time);
		CopyMem(&Info->CreateTime, &Time, sizeof(Time));
		CopyMem(&Info->LastAccessTime, &Time, sizeof(Time));
		CopyMem(&Info->ModificationTime, &Time, sizeof(Time));

		if (File->IsDir) {
			Info->Attribute |= EFI_FILE_DIRECTORY;
		} else {
			Info->FileSize = GrubGetFileSize(File);
			Info->PhysicalSize = GrubGetFileSize(File);
		}

		Status = Utf8ToUtf16NoAlloc(File->basename, Info->FileName,
				(INTN)(Info->Size - sizeof(EFI_FILE_INFO)));
		if (EFI_ERROR(Status)) {
			if (Status != EFI_BUFFER_TOO_SMALL)
				PrintStatusError(Status, L"Could not convert basename to UTF-8");
			return Status;
		}

		/* The Info struct size already accounts for the extra NUL */
		Info->Size = sizeof(EFI_FILE_INFO) + 
				StrLen(Info->FileName) * sizeof(CHAR16);
		return EFI_SUCCESS;

	} else if (CompareMem(Type, &FileSystemInfo, sizeof(*Type)) == 0) {

		/* Get file system information */
		PrintExtra(L"Get file system information\n");
		if (*Len < MINIMUM_FS_INFO_LENGTH) {
			*Len = MINIMUM_FS_INFO_LENGTH;
			return EFI_BUFFER_TOO_SMALL;
		}

		ZeroMem(Data, sizeof(EFI_FILE_INFO));
		FSInfo->Size = *Len;
		FSInfo->ReadOnly = 1;
		/* NB: This should really be cluster size, but we don't have access to that */
		FSInfo->BlockSize = File->FileSystem->BlockIo->Media->BlockSize;
		if (FSInfo->BlockSize  == 0) {
			PrintWarning(L"Corrected Media BlockSize\n");
			FSInfo->BlockSize = 512;
		}
		FSInfo->VolumeSize = (File->FileSystem->BlockIo->Media->LastBlock + 1) *
			FSInfo->BlockSize;
		/* No idea if we can easily get this for GRUB, and the device is RO anyway */
		FSInfo->FreeSpace = 0;

		Status = GrubLabel(File, &label);
		if (EFI_ERROR(Status)) {
			PrintStatusError(Status, L"Could not read disk label");
		} else {
			Status = Utf8ToUtf16NoAlloc(label, FSInfo->VolumeLabel,
					(INTN)(FSInfo->Size - sizeof(EFI_FILE_SYSTEM_INFO)));
			if (EFI_ERROR(Status)) {
				if (Status != EFI_BUFFER_TOO_SMALL)
					PrintStatusError(Status, L"Could not convert label to UTF-8");
				return Status;
			}
			Info->Size = sizeof(EFI_FILE_SYSTEM_INFO) +
					StrLen(FSInfo->VolumeLabel) * sizeof(CHAR16);
		}
		return EFI_SUCCESS;

	} else {

		GuidToString(GuidString, Type);
		PrintError(L"'%s': Cannot get information of type %s\n",
				FileName(File), GuidString);
		return EFI_UNSUPPORTED;

	}
}
Пример #24
0
void CCmdCat::HandleFileReadError(TInt aError)
	{
	PrintWarning(_L("Problem reading %S: %d"), &iFiles[0], aError);
	RemoveCurrentFileName();
	ReadNextFile();
	}
Пример #25
0
Boolean
CreateHelp()
{
  struct stat fileinfo;		/* file information from fstat. */
  FILE * help_file;		/* The stream of the help file. */
  char * help_page;		/* The help text strored in memory. */
  int help_width;		/* The width of the help window. (default). */
  Arg arglist[10];		/* The arglist */
  Cardinal num_args;		/* The number of arguments. */
  Widget pane;			/* The Vpane, that will contain the help info.
				   */
  static XtCallbackRec Callbacks[] = {
    { PopdownHelp, NULL },
    { NULL, NULL },
  };
  
  if (help_widget != NULL)	/* If we already have a help widget. 
				   then do not create one. */
    return(TRUE);

/* Open help_file and read it into memory. */

/*
 * Get file size and allocate a chunk of memory for the file to be 
 * copied into.
 */

  if( (help_file = fopen(help_file_name, "r")) == NULL ) {
    PrintWarning("Could not open help file, NO HELP WILL BE AVALIABLE.");
    return(FALSE);
  }

  if ( stat(help_file_name, &fileinfo) ) {
    PrintWarning("Failure in fstat, NO HELP WILL BE AVALIABLE.");
    return(FALSE);
  }

  /* leave space for the NULL */
  help_page = (char *) malloc(fileinfo.st_size + 1);	

  if (help_page == NULL) {
    PrintWarning(
      "Could not allocate memory for help file, NO HELP WILL BE AVALIABLE.");
    return(FALSE);
  }

/*
 * Copy the file into memory. 
 */
 
  fread(help_page,sizeof(char),fileinfo.st_size,help_file); 
  fclose(help_file);
    
/* put NULL at end of buffer. */

  *(help_page + fileinfo.st_size) = '\0';

/*
 * Help file now loaded in to memory. Create widgets do display it. 
 */

  num_args = 0;
  XtSetArg(arglist[num_args], XtNallowShellResize, TRUE);
  num_args++;

  help_widget = XtCreateApplicationShell("help", applicationShellWidgetClass, 
				   arglist, num_args);

  num_args = 0;
  help_width = DisplayWidth(XtDisplay(help_widget), 
			    DefaultScreen(XtDisplay(help_widget)));
  help_width /= 2;
  XtSetArg(arglist[num_args], XtNwidth, help_width);
  num_args++;

#if XtSpecificationRelease < 4
  pane = XtCreateWidget("Help_VPaned",vPanedWidgetClass,help_widget,
			arglist,num_args);
#else
  pane = XtCreateWidget("Help_Paned",panedWidgetClass,help_widget,
			arglist,num_args);
#endif

  num_args = 0;
  XtSetArg(arglist[num_args], XtNborderWidth, 0);
  num_args++;
  XtSetArg(arglist[num_args], XtNlabel, "Done With Help");
  num_args++;
  XtSetArg(arglist[num_args], XtNcallback, Callbacks);
  num_args++;

  (void) XtCreateManagedWidget("Help_Quit",commandWidgetClass, pane,
			       arglist, num_args);

  num_args = 0;
  XtSetArg(arglist[num_args], XtNborderWidth, 0);
  num_args++;
  XtSetArg(arglist[num_args], XtNstring, help_page);
  num_args++;
#if XtSpecificationRelease < 4
  XtSetArg(arglist[num_args], XtNtextOptions, scrollVertical);
  num_args++;
#else
  XtSetArg(arglist[num_args],XtNscrollVertical,XawtextScrollAlways);
  num_args++;
  XtSetArg(arglist[num_args],XtNscrollHorizontal,XawtextScrollWhenNeeded);
  num_args++;
  XtSetArg(arglist[num_args],XtNuseStringInPlace, TRUE);
  num_args++;
#endif
  /* make the text shown a square box. */
  XtSetArg(arglist[num_args], XtNheight, help_width);
  num_args++;
  

#if XtSpecificationRelease < 4
  (void) XtCreateManagedWidget("Help_Text",asciiStringWidgetClass, pane,
			       arglist, num_args);
#else
  (void) XtCreateManagedWidget("Help_Text",asciiTextWidgetClass, pane,
			       arglist, num_args);
#endif

  XtManageChild(pane);
  XtRealizeWidget(help_widget);
  AddCursor(help_widget,help_cursor);

  return(TRUE);
}
Пример #26
0
void TLogger::PrintWarning(const TStr& Str)
{
    PrintWarning(Str.CStr());
}
Пример #27
0
unsigned int CDepSettings::Load(LPCSTR szSettingsPath)
{
	HRESULT hr = E_FAIL;
	
	if (!szSettingsPath)
		return IDS_UNEXPECTED;

	// Create the DOM
	CComPtr<IXMLDOMDocument> spDOMDoc;
	CComPtr<IXMLDOMNode> spRoot;
	CComPtr<IXMLDOMNode> spResultNode;

	hr = spDOMDoc.CoCreateInstance(L"Microsoft.XMLDOM");
	if (FAILED(hr))
		return IDS_ERR_FAILEDTOCREATEDOM;
	
	hr = spDOMDoc->put_async(VARIANT_FALSE);
	if (FAILED(hr))
		return IDS_UNEXPECTED;

	// Load the document
	CComVariant varDocPath(szSettingsPath);
	VARIANT_BOOL  vResult = VARIANT_FALSE;
	hr = spDOMDoc->load(varDocPath, &vResult);
	if (FAILED(hr) || vResult == VARIANT_FALSE)
		return IDS_ERR_FAILEDTOLOAD_SETTINGS_XML;


	// find the root element
	CComBSTR bstrSearch(L"ATLSINSTSETTINGS");
	hr = spDOMDoc->selectSingleNode(bstrSearch, &spRoot);
	if (FAILED(hr) || !spRoot)
		return IDS_ERR_BADROOTNODE;

	CStringW strWebHostNameW;
	// load the list of web hosts
	bstrSearch = L"WEBHOSTNAME";
	hr = spRoot->selectNodes(bstrSearch, &m_spHostList);
	if (FAILED(hr) || !m_spHostList)
		return IDS_ERR_WEBHOSTNAME;
	else
	{
		long len = 0;
		m_spHostList->get_length(&len);
		if (len == 0)
			return IDS_ERR_WEBHOSTNAME;
		CComPtr<IXMLDOMNode> spFirstWebHost;
		hr = m_spHostList->get_item(0,&spFirstWebHost);
		if (SUCCEEDED(hr))
		{
			hr = spFirstWebHost->get_text(&bstrSearch);
			strWebHostNameW=bstrSearch;
		}
	}

	// load the virtual directory name on the host
	bstrSearch = L"VIRTDIRNAME";
	hr = spRoot->selectSingleNode(bstrSearch, &spResultNode);
	if (FAILED(hr) || !spResultNode)
		return IDS_ERR_NOVIRTDIR;

	hr = spResultNode->get_text(&bstrSearch);
	if (FAILED(hr) || *bstrSearch == L'\0')
		return IDS_ERR_BADVIRTDIRNODE;
	m_strVirtDirName = bstrSearch;

	// load the virtual directory file system path
	spResultNode.Release();
	bstrSearch = L"VIRTDIRFSPATH";
	hr = spRoot->selectSingleNode(bstrSearch, &spResultNode);
	if (FAILED(hr) || !spResultNode)
		return IDS_ERR_NOVIRTDIRFSPATH;
	
	spResultNode->get_text(&bstrSearch);
	if (FAILED(hr) || *bstrSearch == L'\0')
		return IDS_ERR_BADVIRTDIRSFPATHNODE;

	m_strVirtDirFSPath = bstrSearch;
	if (!AtlIsFullPathT(m_strVirtDirFSPath.GetString()))
	{
		CStringW strPath;
		hr=GetWWWRootPath(strWebHostNameW,strPath);
		if (FAILED(hr) || strPath.IsEmpty() )
		{
			return IDS_ERR_BADVIRTDIRSFPATHNODE;
		}
		m_strVirtDirFSPath=strPath;
		m_strVirtDirFSPath+=m_strVirtDirName;
	}

	// load the DoNotCreateVirtDir value
	spResultNode.Release();
	bstrSearch = L"DONOTCREATEVIRTDIR";
	hr = spRoot->selectSingleNode(bstrSearch, &spResultNode);
	if (hr == S_OK && spResultNode)
	{
		hr = spResultNode->get_text(&bstrSearch);
		if (FAILED(hr))
			PrintWarning(IDS_ERR_BADDONOTCREATEVIRTDIR);
		else
		{
			if (!_wcsicmp(bstrSearch, L"false"))
				m_bDoNotCreateVirtDir = false;
			else if (!_wcsicmp(bstrSearch, L"true"))
				m_bDoNotCreateVirtDir = true;
			else
			{
				PrintWarning(IDS_ERR_INVALIDDONOTCREATEVIRTDIR);
			}
		}
	}

	// load the registerisapi value
	spResultNode.Release();
	bstrSearch = L"REGISTERISAPI";
	hr = spRoot->selectSingleNode(bstrSearch, &spResultNode);
	if (hr == S_OK && spResultNode)
	{
		hr = spResultNode->get_text(&bstrSearch);
		if (FAILED(hr))
			PrintWarning(IDS_ERR_BADREGISTERISAPI);
		else
		{
			if (!_wcsicmp(bstrSearch, L"false"))
				m_bRegIsapi = false;
			else if (!_wcsicmp(bstrSearch, L"true"))
				m_bRegIsapi = true;
			else
			{
				PrintWarning(IDS_ERR_INVALIDREGISTERISAPI);
			}
		}
	}

	// load the unload before copy value
	spResultNode.Release();
	bstrSearch = L"UNLOADBEFORECOPY";
	hr = spRoot->selectSingleNode(bstrSearch, &spResultNode);
	if (hr == S_OK && spResultNode)
	{
		hr = spResultNode->get_text(&bstrSearch);
		if (FAILED(hr))
			PrintWarning(IDS_ERR_BADUNLOADBEFORECOPY);
		else
		{
			if (!_wcsicmp(bstrSearch, L"false"))
				m_bUnloadBeforeCopy = false;
			else if (!_wcsicmp(bstrSearch, L"true"))
				m_bUnloadBeforeCopy = true;
			else
				PrintWarning(IDS_ERR_INVALIDUNLOADBEFORECOPY);
		}
	}

	// load the app isolation value
	spResultNode.Release();
	bstrSearch = L"APPISOLATION";
	hr = spRoot->selectSingleNode(bstrSearch, &spResultNode);
	if (hr == S_OK && spResultNode)
	{
		hr = spResultNode->get_text(&bstrSearch);
		if (FAILED(hr))
			PrintWarning(IDS_ERR_BADAPPISOLATION);
		else
		{
			wchar_t *szEnd = NULL;
			short nIso = (short)wcstol(bstrSearch, &szEnd, 10);
			if (errno == ERANGE || nIso < 0 || nIso > 2)
			{
                PrintWarning(IDS_ERR_INVALIDAPPISOLATION);
			}
			else
			{
				switch(nIso)
				{
				case 0:
					m_nAppIsolation = nIso;
					break;
				case 1:
					m_nAppIsolation = 2;
					break;
				case 2:
					m_nAppIsolation = 1;
					break;
				}
			}
		}
	}

	// load the list of APPMAPPING nodes
	bstrSearch = L"APPMAPPING";
	hr = spRoot->selectNodes(bstrSearch, &m_spAppMappings);

	// load list of APPFILEGROUP nodes
	bstrSearch = L"APPFILEGROUP";
	hr = spRoot->selectNodes(bstrSearch, &m_spAppFileGroups);

	// see if there is a node for the extension. There better be only one because
	// we will only select the first one we run into.
	CComPtr<IXMLDOMNode> spIsapiNode;
	hr = spRoot->selectSingleNode(CComBSTR(L"//APPFILENAME[@type=\"extension\"] "), &spIsapiNode);
	if (hr == S_OK && spIsapiNode)
	{
		// select the <DEST> node
		CComPtr<IXMLDOMNode> spDestNode;
		hr = spIsapiNode->selectSingleNode(CComBSTR(L"DEST"), &spDestNode);
		if (hr == S_OK && spDestNode)
		{
			CComBSTR bstrPath;
			hr = spDestNode->get_text(&bstrPath);
			if (hr == S_OK && bstrPath[0] != L'\0')
			{
				m_strExtFileName = bstrPath;
			}
		}
	}

	GetIISMajorVer();
#ifdef _DEBUG
	// dump the settings
	printf("loaded settings:\n");
	printf("Virtual directory name: %s\n", m_strVirtDirName);
	printf("Virtual directory fs path: %s\n", m_strVirtDirFSPath);
	printf("Virtual directory isapi extension name: %s\n",m_strExtFileName);
	printf("Do not create virtual directory: %s\n", m_bDoNotCreateVirtDir ? "true" : "false");
	printf("Register ISAPI: %s\n", m_bRegIsapi ? "true" : "false");
	printf("Unload before copy: %s\n", m_bUnloadBeforeCopy ? "true" : "false");
	printf("App Isolation: %d\n", m_nAppIsolation);
	long lCount = 0;

	if (m_spHostList)
	{
		m_spHostList->get_length(&lCount);
		printf("Host count: %d\n", lCount);
	}
	else
	{
		printf("no hosts encountered\n");
	}

	if (m_spAppMappings)
	{
		lCount = 0;
		m_spAppMappings->get_length(&lCount);
		printf("App Mapping count: %d\n", lCount);
	}
	else
	{
		printf("no app mappings\n");
	}

	if (m_spAppFileGroups)
	{
		lCount = 0;
		m_spAppFileGroups->get_length(&lCount);
		printf("App file group count: %d\n", lCount);
	}
#endif
	return S_OK;
}
Пример #28
0
 void Debug::PrintWarning(std::string& message) {
     PrintWarning((const Char *)message.c_str());
 }
Пример #29
0
void CCmdCat::DoRunL()
	{
	if (iBinary)
		{
		if (iOptions.IsPresent(&iEncoding))
			{
			PrintWarning(_L("--encoding overrides legacy --binary option"));
			}
		else
			{
			iEncoding = EBinary;
			}
		}

	if (iEncoding == EBinary || iEncoding == ELtkUtf8 || iFiles.Count() == 0)
		{
		iBuf16.CreateL(iBlockSize);
		}
	else
		{
		TUint charset;
		switch (iEncoding)
			{
			case EUtf8:
				charset = KCharacterSetIdentifierUtf8;
				break;
			case ELatin1:
				charset = KCharacterSetIdentifierIso88591;
				break;
			case EAuto:
			default:
				charset = 0;
				break;

			}
		TRAPL(iCharacterConverter = CCharacterConverter::NewL(iBlockSize, FsL(), charset), _L("Couldn't load charconv - try using --binary mode"));
		}
	iFileReader = CFileReader::NewL(iBlockSize, FsL(), iForce);

	if (iFiles.Count() > 0)
		{
		ReadNextFile();
		}
	else
		{
		TInt err = KErrNone;
		while (err == KErrNone)
			{
			err = Stdin().Read(iBuf16);
			if (err == KErrNone)
				{
				Write(iBuf16);
				}
			}
		if (err == KErrEof)
			{
			err = KErrNone;
			}
		Complete(err);
		}
	}
Пример #30
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;
	}