Example #1
0
	char_blocks.compress();
}

const SDL_Color NORMAL_COLOR = {0xDD,0xDD,0xDD,0},
                GRAY_COLOR   = {0x77,0x77,0x77,0},
                LOBBY_COLOR  = {0xBB,0xBB,0xBB,0},
                GOOD_COLOR   = {0x00,0xFF,0x00,0},
                BAD_COLOR    = {0xFF,0x00,0x00,0},
                BLACK_COLOR  = {0x00,0x00,0x00,0},
                YELLOW_COLOR = {0xFF,0xFF,0x00,0},
                BUTTON_COLOR = {0xBC,0xB0,0x88,0},
                PETRIFIED_COLOR = {0xA0,0xA0,0xA0,0},
                TITLE_COLOR  = {0xBC,0xB0,0x88,0},
				LABEL_COLOR  = {0x6B,0x8C,0xFF,0},
				BIGMAP_COLOR = {0xFF,0xFF,0xFF,0};
const SDL_Color DISABLED_COLOR = inverse(PETRIFIED_COLOR);

namespace {

static const size_t max_text_line_width = 4096;

class text_surface
{
public:
	text_surface(std::string const &str, int size, SDL_Color color, int style);
	text_surface(int size, SDL_Color color, int style);
	void set_text(std::string const &str);

	void measure() const;
	size_t width() const;
	size_t height() const;
Example #2
0
InverseKinematicsReportPtr
KinematicSolver::inverse(const btTransform& pose) {
	return inverse(pose,defaultIKOptions_);
}
Example #3
0
Box CoordinateFrame::toObjectSpace(const Box &b) const {
    return inverse().toWorldSpace(b);
}
Example #4
0
 const mat2& invert(bool *invertible=NULL)
 {
     *this = inverse(invertible);
     return *this;
 }
Example #5
0
void Mesh::ComputeMatrices() {
    xform = mat4(xform_cols[0], xform_cols[1], xform_cols[2], xform_cols[3]);
    xform_inv = inverse(xform);
    xform_inv_tr = transpose(xform_inv);
}
Example #6
0
void main()
{
    mat4 matModelViewProjection = matrixCameraToClip * matrixModelToCamera;

    // how large (in meters) is one cell?
    vec3 cellSize = vec3(
      (boundingBoxMax.x - boundingBoxMin.x) / gridCellCount.x,
      (boundingBoxMax.y - boundingBoxMin.y) / gridCellCount.y,
      (boundingBoxMax.z - boundingBoxMin.z) / gridCellCount.z
    );

    // Given the cell hash (=gl_PrimitiveIDIn), whats the 3d-grid-coordinate of the cell's center?
    // This is the reverse of particleskernel.cu -> calcGridHash(int3 gridCell).
    ivec3 gridCellCoordinate = ivec3(
      floor(mod(gl_PrimitiveIDIn, gridCellCount.x)),
      floor(mod(gl_PrimitiveIDIn, gridCellCount.x * gridCellCount.y) / gridCellCount.x),
      floor(mod(gl_PrimitiveIDIn, gridCellCount.x * gridCellCount.y * gridCellCount.z) / (gridCellCount.x * gridCellCount.y))
    );

    vec3 posCenterOfCell = vec3(
      boundingBoxMin.x + (cellSize.x * gridCellCoordinate.x) + (cellSize.x / 2.0),
      boundingBoxMin.y + (cellSize.y * gridCellCoordinate.y) + (cellSize.y / 2.0),
      boundingBoxMin.z + (cellSize.z * gridCellCoordinate.z) + (cellSize.z / 2.0)
    );

    vec4 cameraPosition = inverse(matrixModelToCamera) * vec4(0,0,0,1);

    vec3 toCamera = normalize(cameraPosition.xyz - posCenterOfCell);

    float quadSize = min(min(cellSize.x/2, cellSize.y/2),cellSize.z/2) * quadSizeFactor;

    vec3 upWorld = vec3(0.0, 1.0, 0.0);

    vec3 right = normalize(-cross(toCamera, upWorld)) * quadSize;
    vec3 up = normalize(cross(toCamera, normalize(-right))) * quadSize;

    // Don't draw completely transparent boxes. For some reason, this also fixes the problem of the quads disappearing at certain viewing-angles.
    if(cellvalue[0] == 0.0) return;
    
    float alpha = cellvalue[0];
    if(alphaExponentiation != 1.0) alpha = pow(alpha, alphaExponentiation);
    if(alpha < 1.0 && alpha > 0.993) alpha = 0.4; // show dilated cells with obvious difference.
    if(alpha > 1.0) alpha = 1.0;
    alpha *= alphaMultiplication;
    //if(cellvalue[0] > 0) alpha = 1.0;

    vec4 outColor = fixedColor;
    outColor.a = alpha;

    // bottom left
    posCenterOfCell -= right;
    posCenterOfCell -= up;
    gl_Position = matModelViewProjection * vec4(posCenterOfCell, 1.0);
    //texureCoordinate = vec2(-1.0, -1.0);
    colorGS_to_FS = outColor;
    EmitVertex();

    // top left
    posCenterOfCell += up*2;
    gl_Position = matModelViewProjection * vec4(posCenterOfCell, 1.0);
    //texureCoordinate = vec2(-1.0, 1.0);
    colorGS_to_FS = outColor;
    EmitVertex();

    // bottom right
    posCenterOfCell -= up*2;
    posCenterOfCell += right * 2;
    gl_Position = matModelViewProjection * vec4(posCenterOfCell, 1.0);
    //texureCoordinate = vec2(1.0, -1.0);
    colorGS_to_FS = outColor;
    EmitVertex();

    // top right
    posCenterOfCell += up*2;
    gl_Position = matModelViewProjection * vec4(posCenterOfCell, 1.0);
    //texureCoordinate = vec2(1.0, 1.0);
    colorGS_to_FS = outColor;
    EmitVertex();

    EndPrimitive();
}
Example #7
0
static void normaldistf_inverse(float* data, size_t count) {
    inverse(data, count);
}
Example #8
0
bool Quaternion::inverse()
{
    return inverse(this);
}
Example #9
0
void 
Scene::load(const filesystem::path &file)
{
  size_t i;
  std::string message;

  if(!filesystem::exists(file))
    throw std::runtime_error(std::string("File does not exists:") + file.string());

  this->collada = new DAE;

  message = "Start loading COLLADA DOM from ";
  message += file.string();
  this->scene_graph.printStatusMessage(message); 
  this->dae_file_name = file;

  // load with full path 
  domCOLLADA *dom = this->collada->open(file.string());
  if(!dom)
    {
      delete this->collada;	
      throw std::runtime_error(std::string("Error loading the COLLADA file ") 
			  + file.string() 
			  + ". Make sure it is COLLADA 1.4 or greater");
    }

  this->scene_graph.printStatusMessage("Begin conditioning");

  //if(kmzcleanup(this->collada, true))
  //  std::cout << "  kmzcleanup complete\n";
  int res = 0;

  this->scene_graph.printStatusMessage("  triangulating");
  res = triangulate(this->collada);
	if(res)
  {
    std::ostringstream os;
    os << "  triangulation returns error " << res << std::ends;
    this->scene_graph.printStatusMessage(os.str());
  }
  else
    this->scene_graph.printStatusMessage(std::string("  triangulation complete"));
/*
  this->scene_graph.printStatusMessage(std::string("  deindexing"));
  res = deindex(this->collada);
	if(res)
  {
    std::ostringstream os;
    os << "  deindexer returns error " << res << std::ends;
    this->scene_graph.printStatusMessage(os.str());
  }
  else
    this->scene_graph.printStatusMessage(std::string("  deindexing complete"));
*/
  this->scene_graph.printStatusMessage(std::string("Finish conditioning."));

  // Need to get the asset tag which will determine what vector x y or z is up.  Typically y or z. 
  domAssetRef asset = dom->getAsset();
  this->scene_graph.printStatusMessage(std::string("File information:"));
  const domAsset::domContributor_Array &contributors = asset->getContributor_array();
  for(i = 0; i < contributors.getCount(); ++i)
  {
    domAsset::domContributorRef c = contributors.get(i);
    this->scene_graph.printStatusMessage(std::string("  author:") + c->getAuthor()->getCharData());
    this->scene_graph.printStatusMessage(std::string("  authoring tool:") + c->getAuthoring_tool()->getCharData());
  }
  if(asset->getCreated())
    this->scene_graph.printStatusMessage(std::string("  created: ") + asset->getCreated()->getCharData());
  if(asset->getModified())
    this->scene_graph.printStatusMessage(std::string("  modified: ") + asset->getModified()->getCharData());
  if(asset->getUnit())
  {
    std::ostringstream os;
    os << "  units: " << asset->getUnit()->getMeter() << " meter (" << asset->getUnit()->getAttribute("name") << ")";
    os << std::ends;
    this->scene_graph.printStatusMessage(os.str());
  }
  if(asset->getUp_axis())
    {
      domAsset::domUp_axis *up = dom->getAsset()->getUp_axis();
      if(up)
        this->up_axis = up->getValue();
      switch(this->up_axis)
        {
        case UPAXISTYPE_X_UP:
          this->scene_graph.printStatusMessage(std::string("  X axis is UP axis.")); 
          break; 

        case UPAXISTYPE_Y_UP:
          this->scene_graph.printStatusMessage(std::string("  Y axis is UP axis.")); 
          break;

        case UPAXISTYPE_Z_UP:
          this->scene_graph.printStatusMessage(std::string("  Z axis is UP axis.")); 
          break; 

        default:
          break; 
        }
  	}

  this->scene_graph.printStatusMessage("Building libraries");
 	
  // Load the image for the default texture.

  const Image::ImageID image_key = {"default", ""};
  bool inserted;
  Image::ImageList::iterator img_iter;
  tie(img_iter, inserted) = this->scene_graph.all_images.insert(std::make_pair(image_key, Image()));

  Image &img = img_iter->second;
  img.image = IMG_Load("default.tga");
  if(!img.image)
  {
    scene_graph.all_images.erase(image_key);
    this->scene_graph.printStatusMessage("Can not load default.tga for the default texture.");
  }

  this->scene_graph.printStatusMessage("  Load image libraries");
  const domLibrary_images_Array &ia = dom->getLibrary_images_array();
	for(i = 0; i < ia.getCount(); ++i)
		this->readImageLibrary(ia[i]);

  this->scene_graph.printStatusMessage("  Load effect libraries");
  const domLibrary_effects_Array &ea = dom->getLibrary_effects_array();
	for(i = 0; i < ea.getCount(); i++)
		this->readEffectLibrary(ea[i]);

  this->scene_graph.printStatusMessage("  Load material libraries");
  const domLibrary_materials_Array &ma = dom->getLibrary_materials_array();
	for(i = 0; i < ma.getCount(); i++)
		this->readMaterialLibrary(ma[i]);

  this->scene_graph.printStatusMessage("  Load animation libraries");
  const domLibrary_animations_Array &aa = dom->getLibrary_animations_array();
	for(i = 0; i < aa.getCount(); i++)
		this->readAnimationLibrary(aa[i]);

	// Find the scene we want
	domCOLLADA::domSceneRef domScene = dom->getScene();
	daeElement* defaultScene = NULL;
	if (domScene)
		if (domScene->getInstance_visual_scene())
			if (domScene->getInstance_visual_scene())
				defaultScene = domScene->getInstance_visual_scene()->getUrl().getElement();
	if(defaultScene)
		this->readScene((domVisual_scene*)defaultScene);

	// If no lights were loaded, we need to make one so the scene won't be totally black
	if(this->scene_graph.all_lights.empty())
	{
		// new Light  
		this->scene_graph.printStatusMessage("Scene: no lights were loaded. Creating a default light");
    const Light::LightID light_key = 
      {"no_light_in_scene_default_light", dom->getDocumentURI()->getURI()};
    bool inserted;
    Light::LightList::iterator light;
    tie(light, inserted) = scene_graph.all_lights.insert(std::make_pair(light_key, Light()));
    Light &default_light = light->second;
		default_light.type = Light::DIRECTIONAL;
		default_light.color = Color4f(1, 1, 1, 1);

		// new Node
		this->scene_graph.printStatusMessage("Scene: no instance_light found creating a node with an instance");
    this->scene_graph.insertNode(this->scene_graph.root,
                                 "no_light_in_scene_default_node",
                                 "no_light_in_scene_default_node",
                                 "NONE");
    // Read node transformations
    Node &current_node = *this->scene_graph.all_nodes.find("no_light_in_scene_default_node");

    current_node.transformations.push_back(Transformation());
    Transformation &transform = 
      current_node.transformations.at(current_node.transformations.size() - 1);
		transform.type = Transformation::Translate; 
		const Vector3 trans(-40.0, 40.0, 0.0);
    transform.transform = Transform3::translation(trans);

		// new InstanceLight
    InstanceLight instance_light;
    instance_light.abstract_light_ref = light->first;
    current_node.instance_lights.push_back(instance_light);
    this->scene_graph.light_nodes.push_back("no_light_in_scene_default_node"); 
  }

  if(!this->scene_graph.all_cameras.empty())
  {
    // Search for the first camera node
    Node::NodeMap &all_nodes = this->scene_graph.all_nodes;
    for(int n = 0; n < all_nodes.size(); ++n)
    {
      Node *node = all_nodes.getAtIndex(n);
      if(node->instance_cameras.size() > 0)
      {
        this->scene_graph.active_camera_info = std::make_pair(node, &(node->instance_cameras[0]));
        break;
      }
    }
  }
  else
	{
		this->scene_graph.printStatusMessage( "Scene: create a default camera and it is the first camera to use");
		// new Camera
    const Camera::CameraID camera_key = 
      {"no_camera_in_scene_default_camera", dom->getDocumentURI()->getURI()};

	  // Make the camera
    bool inserted;
    Camera::CameraList::iterator camera;
    tie(camera, inserted) = this->scene_graph.all_cameras.insert(std::make_pair(camera_key, Camera()));
    Camera &default_camera = camera->second;
    default_camera.Xfov = 45.0f;
    default_camera.Yfov = 45.0f;

		this->scene_graph.printStatusMessage( "Scene: creating a node with an instance of default camera");
		// new Node
    this->scene_graph.insertNode(this->scene_graph.root,
                                 "no_camera_in_scene_default_node",
                                 "no_camera_in_scene_default_node",
                                 "NONE");
    // Read node transformations
    Node &current_node = *this->scene_graph.all_nodes.find("no_camera_in_scene_default_node");

    // Calculate approximate bounding box for the model
    Vector3 max(0,0,0);
    Vector3 min(0,0,0);
    for(Geometry::GeometryList::const_iterator g = this->scene_graph.all_geometries.begin();
      g != this->scene_graph.all_geometries.end(); ++g)
    {
      // Points are stored as x/y/z tripples within this array
      for(Geometry::PointList::const_iterator p = g->second.points.begin();
        p != g->second.points.end(); ++p)
      {
        // X
        if(*p > max.getX())
          max.setX(*p);
        else if(*p < min.getX())
          min.setX(*p);
        // Y
        ++p;
        if(*p > max.getY())
          max.setY(*p);
        else if(*p < min.getY())
          min.setY(*p);
        // Z
        ++p;
        if(*p > max.getZ())
          max.setZ(*p);
        else if(*p < min.getZ())
          min.setZ(*p);
      }
    }

    default_camera.ZNear = 1.0f;
		default_camera.ZFar = 1000.0f;

    current_node.transformations.push_back(Transformation());
    Transformation &transform = 
      current_node.transformations.at(current_node.transformations.size() - 1);
    transform.type = Transformation::LookAt;
    const Point3 eyePos(max.getX() * 0.5f, max.getY() * 0.5f, max.getZ() * 0.5f);
    const Point3 lookAtPos(min.getX(), min.getY(), min.getZ());
    Vector3 upVec;
    upVec.setY(0);
		if(this->up_axis == UPAXISTYPE_Z_UP)
    {
      upVec.setX(0);
      upVec.setZ(1.0f);
    }
		else if(this->up_axis == UPAXISTYPE_X_UP)
    {
      upVec.setX(1.0f);
      upVec.setZ(0);
    }
    // Store transformation
    transform.matrix = inverse(Matrix4::lookAt(eyePos, lookAtPos, upVec));
    current_node.local_matrix *= transform.matrix;

    // new InstanceCamera
    InstanceCamera instance_camera;
    instance_camera.abstract_camera_ref = camera->first;
    current_node.instance_cameras.push_back(instance_camera);
    this->scene_graph.active_camera_info = std::make_pair(&current_node,
      &(current_node.instance_cameras.at(current_node.instance_cameras.size() - 1)));
	}

  this->scene_graph.printStatusMessage(std::string("COLLADA_DOM runtime database initialized from ") + file.filename().string());
}
Example #10
0
Matrix3f Matrix3f::inverse() const
{
	bool isSingular;
	return inverse( isSingular );
}
Example #11
0
void eqnsys<nr_type_t>::solve_inverse (void) {
  *X = inverse (*A) * *B;
}
Example #12
0
bool TQualityMetric::evaluate_with_Hessian_diagonal( 
                                           PatchData& pd,
                                           size_t handle,
                                           double& value,
                                           std::vector<size_t>& indices,
                                           std::vector<Vector3D>& grad,
                                           std::vector<SymMatrix3D>& diagonal,
                                           MsqError& err )
{
  const Sample s = ElemSampleQM::sample( handle );
  const size_t e = ElemSampleQM::  elem( handle );
  MsqMeshEntity& elem = pd.element_by_index( e );
  EntityTopology type = elem.get_element_type();
  unsigned edim = TopologyInfo::dimension( type );
  size_t num_idx = 0;
  const NodeSet bits = pd.non_slave_node_set( e );
  
  bool rval;
  if (edim == 3) { // 3x3 or 3x2 targets ?
    const MappingFunction3D* mf = pd.get_mapping_function_3D( type );
    if (!mf) {
      MSQ_SETERR(err)( "No mapping function for element type", MsqError::UNSUPPORTED_ELEMENT );
      return false;
    }

    MsqMatrix<3,3> A, W, dmdT, d2mdT2[6];
    mf->jacobian( pd, e, bits, s, mIndices, mDerivs3D, num_idx, A, err );
    MSQ_ERRZERO(err);
    targetCalc->get_3D_target( pd, e, s, W, err ); MSQ_ERRZERO(err);
    const MsqMatrix<3,3> Winv = inverse(W);
    const MsqMatrix<3,3> T = A*Winv;
    rval = targetMetric->evaluate_with_hess( T, value, dmdT, d2mdT2, err ); MSQ_ERRZERO(err);
    gradient<3>( num_idx, mDerivs3D, dmdT * transpose(Winv), grad );
    second_deriv_wrt_product_factor( d2mdT2, Winv );
    
    diagonal.resize( num_idx );
    hessian_diagonal<3>(num_idx, mDerivs3D, d2mdT2, arrptr(diagonal) );
#ifdef PRINT_INFO
    print_info<3>( e, s, A, W, A * inverse(W) );
#endif
  }
  else if (edim == 2) {
#ifdef NUMERICAL_2D_HESSIAN
    // use finite diference approximation for now
    return QualityMetric::evaluate_with_Hessian_diagonal( pd, handle,
                                           value, indices, grad, diagonal,
                                           err );
#else
    MsqMatrix<2,2> W, A, dmdT, d2mdT2[3];
    MsqMatrix<3,2> M;
    rval = evaluate_surface_common( pd, s, e, bits, mIndices, num_idx,
                             mDerivs2D, W, A, M, err ); 
    if (MSQ_CHKERR(err) || !rval)
      return false;
    const MsqMatrix<2,2> Winv = inverse(W);
    const MsqMatrix<2,2> T = A*Winv;
    rval = targetMetric->evaluate_with_hess( T, value, dmdT, d2mdT2, err ); MSQ_ERRZERO(err);
    gradient<2>( num_idx, mDerivs2D, M * dmdT * transpose(Winv), grad );
    second_deriv_wrt_product_factor( d2mdT2, Winv );

    diagonal.resize( num_idx );
    for (size_t i = 0; i < num_idx; ++i) {
      MsqMatrix<2,2> block2d;
      block2d(0,0) = transpose(mDerivs2D[i]) * d2mdT2[0] * mDerivs2D[i];
      block2d(0,1) = transpose(mDerivs2D[i]) * d2mdT2[1] * mDerivs2D[i];
      block2d(1,0) = block2d(0,1);
      block2d(1,1) = transpose(mDerivs2D[i]) * d2mdT2[2] * mDerivs2D[i];
      MsqMatrix<3,2> p = M * block2d;
      
      SymMatrix3D& H = diagonal[i];
      H[0] = p.row(0) * transpose(M.row(0));
      H[1] = p.row(0) * transpose(M.row(1));
      H[2] = p.row(0) * transpose(M.row(2));
      H[3] = p.row(1) * transpose(M.row(1));
      H[4] = p.row(1) * transpose(M.row(2));
      H[5] = p.row(2) * transpose(M.row(2));
    }
#ifdef PRINT_INFO
    print_info<2>( e, s, J, Wp, A * inverse(W) );
#endif
#endif
  }
  else {
    assert(0);
    return false;
  }
  
    // pass back index list
  indices.resize( num_idx );
  std::copy( mIndices, mIndices+num_idx, indices.begin() );
  
    // apply target weight to value
  if (!num_idx) 
    weight( pd, s, e, num_idx, value, 0, 0, 0, err );
  else
    weight( pd, s, e, num_idx, value, arrptr(grad), arrptr(diagonal), 0, err ); 
  MSQ_ERRZERO(err);
  return rval;
}
Example #13
0
bool TQualityMetric::evaluate_with_Hessian( PatchData& pd,
                                            size_t handle,
                                            double& value,
                                            std::vector<size_t>& indices,
                                            std::vector<Vector3D>& grad,
                                            std::vector<Matrix3D>& Hessian,
                                            MsqError& err )
{
  const Sample s = ElemSampleQM::sample( handle );
  const size_t e = ElemSampleQM::  elem( handle );
  MsqMeshEntity& elem = pd.element_by_index( e );
  EntityTopology type = elem.get_element_type();
  unsigned edim = TopologyInfo::dimension( type );
  size_t num_idx = 0;
  const NodeSet bits = pd.non_slave_node_set( e );
  
  bool rval;
  if (edim == 3) { // 3x3 or 3x2 targets ?
    const MappingFunction3D* mf = pd.get_mapping_function_3D( type );
    if (!mf) {
      MSQ_SETERR(err)( "No mapping function for element type", MsqError::UNSUPPORTED_ELEMENT );
      return false;
    }

    MsqMatrix<3,3> A, W, dmdT, d2mdT2[6];
    mf->jacobian( pd, e, bits, s, mIndices, mDerivs3D, num_idx, A, err );
    MSQ_ERRZERO(err);
    targetCalc->get_3D_target( pd, e, s, W, err ); MSQ_ERRZERO(err);
    const MsqMatrix<3,3> Winv = inverse(W);
    const MsqMatrix<3,3> T = A*Winv;
    rval = targetMetric->evaluate_with_hess( T, value, dmdT, d2mdT2, err ); MSQ_ERRZERO(err);
    gradient<3>( num_idx, mDerivs3D, dmdT*transpose(Winv), grad );
    second_deriv_wrt_product_factor( d2mdT2, Winv );
    Hessian.resize( num_idx*(num_idx+1)/2 );
    if (num_idx)
      hessian<3>( num_idx, mDerivs3D, d2mdT2, arrptr(Hessian) );
    
#ifdef PRINT_INFO
    print_info<3>( e, s, A, W, A * inverse(W) );
#endif
  }
  else if (edim == 2) {
#ifdef NUMERICAL_2D_HESSIAN
    // return finite difference approximation for now

    return QualityMetric::evaluate_with_Hessian( pd, handle,
                                           value, indices, grad, Hessian,
                                           err );
#else
    MsqMatrix<2,2> W, A, dmdT, d2mdT2[3];
    MsqMatrix<3,2> M;
    rval = evaluate_surface_common( pd, s, e, bits, mIndices, num_idx,
                             mDerivs2D, W, A, M, err ); 
    if (MSQ_CHKERR(err) || !rval)
      return false;
    const MsqMatrix<2,2> Winv = inverse(W);
    const MsqMatrix<2,2> T = A*Winv;
    rval = targetMetric->evaluate_with_hess( T, value, dmdT, d2mdT2, err ); MSQ_ERRZERO(err);
    gradient<2>( num_idx, mDerivs2D, M * dmdT * transpose(Winv), grad );
      // calculate 2D hessian
    second_deriv_wrt_product_factor( d2mdT2, Winv );
    const size_t n = num_idx*(num_idx+1)/2;
    hess2d.resize(n);
    if (n)
      hessian<2>( num_idx, mDerivs2D, d2mdT2, arrptr(hess2d) );
      // calculate surface hessian as transform of 2D hessian
    Hessian.resize(n);
    for (size_t i = 0; i < n; ++i)
      Hessian[i] = Matrix3D( (M * hess2d[i] * transpose(M)).data() );
#ifdef PRINT_INFO
    print_info<2>( e, s, J, Wp, A * inverse(W) );
#endif
#endif
  }
  else {
    assert(0);
    return false;
  }
  
    // pass back index list
  indices.resize( num_idx );
  std::copy( mIndices, mIndices+num_idx, indices.begin() );
  
    // apply target weight to value
  if (!num_idx) 
    weight( pd, s, e, num_idx, value, 0, 0, 0, err );
  else
    weight( pd, s, e, num_idx, value, arrptr(grad), 0, arrptr(Hessian), err ); 
  MSQ_ERRZERO(err);
  return rval;
}
Example #14
0
bool TQualityMetric::evaluate_with_gradient( PatchData& pd,
                                             size_t handle,
                                             double& value,
                                             std::vector<size_t>& indices,
                                             std::vector<Vector3D>& grad,
                                             MsqError& err )
{
  const Sample s = ElemSampleQM::sample( handle );
  const size_t e = ElemSampleQM::  elem( handle );
  MsqMeshEntity& elem = pd.element_by_index( e );
  EntityTopology type = elem.get_element_type();
  unsigned edim = TopologyInfo::dimension( type );
  size_t num_idx = 0;
  const NodeSet bits = pd.non_slave_node_set( e );
  
  bool rval;
  if (edim == 3) { // 3x3 or 3x2 targets ?
    const MappingFunction3D* mf = pd.get_mapping_function_3D( type );
    if (!mf) {
      MSQ_SETERR(err)( "No mapping function for element type", MsqError::UNSUPPORTED_ELEMENT );
      return false;
    }

    MsqMatrix<3,3> A, W, dmdT;
    mf->jacobian( pd, e, bits, s, mIndices, mDerivs3D, num_idx, A, err );
    MSQ_ERRZERO(err);
    targetCalc->get_3D_target( pd, e, s, W, err ); MSQ_ERRZERO(err);
    const MsqMatrix<3,3> Winv = inverse(W);
    const MsqMatrix<3,3> T = A*Winv;
    rval = targetMetric->evaluate_with_grad( T, value, dmdT, err ); MSQ_ERRZERO(err);
    gradient<3>( num_idx, mDerivs3D, dmdT * transpose(Winv), grad );
#ifdef PRINT_INFO
    print_info<3>( e, s, A, W, A * inverse(W) );
#endif
  }
  else if (edim == 2) {
    MsqMatrix<2,2> W, A, dmdT;
    MsqMatrix<3,2> S_a_transpose_Theta;
    rval = evaluate_surface_common( pd, s, e, bits, mIndices, num_idx,
                             mDerivs2D, W, A, S_a_transpose_Theta, err ); 
    if (MSQ_CHKERR(err) || !rval)
      return false;
    const MsqMatrix<2,2> Winv = inverse(W);
    const MsqMatrix<2,2> T = A*Winv;
    rval = targetMetric->evaluate_with_grad( T, value, dmdT, err ); MSQ_ERRZERO(err);
    gradient<2>( num_idx, mDerivs2D, S_a_transpose_Theta*dmdT*transpose(Winv), grad );
#ifdef PRINT_INFO
    print_info<2>( e, s, J, Wp, A * inverse(W) );
#endif
  }
  else {
    assert(false);
    return false;
  }
  
    // pass back index list
  indices.resize( num_idx );
  std::copy( mIndices, mIndices+num_idx, indices.begin() );
  
    // apply target weight to value
  weight( pd, s, e, num_idx, value, grad.empty() ? 0 : arrptr(grad), 0, 0, err ); MSQ_ERRZERO(err);
  return rval;
}
Example #15
0
TEST(FastUpdate, BlockMatrixRemove)
{
  typedef double Scalar;
  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> matrix_t;

  std::vector<int> N_list, M_list;
  N_list.push_back(10);
  M_list.push_back(10);
  M_list.push_back(20);
  M_list.push_back(30);

  for (int n=0; n<N_list.size(); ++n) {
    for (int m=0; m<M_list.size(); ++m) {
      const int N = N_list[n];
      const int M = M_list[m];

      matrix_t BigMatrix(N+M, N+M, 0), invBigMatrix(N+M, N+M, 0);//G, G^{-1}
      matrix_t SmallMatrix(N,N,0);//G'
      std::vector<std::pair<int,int> > swapped_rows_in_G, swapped_cols_in_G;

      randomize_matrix(BigMatrix, 100);//100 is a seed
      invBigMatrix = inverse(BigMatrix);

      //which rows and cols are to be removed
      std::vector<int> rows_removed(N+M);
      std::vector<int> rows_remain(N);
      for (int i=0; i<N+M; ++i) {
        rows_removed[i] = i;
      }
      std::random_shuffle(rows_removed.begin(), rows_removed.end());
      for (int i=0; i<N; ++i) {
        rows_remain[i] = rows_removed[i+M];
      }
      rows_removed.resize(M);
      std::sort(rows_removed.begin(), rows_removed.end());
      std::sort(rows_remain.begin(), rows_remain.end());

      for (int j=0; j<N; ++j) {
        for (int i=0; i<N; ++i) {
          SmallMatrix(i,j) = BigMatrix(rows_remain[i], rows_remain[j]);
        }
      }

      //testing compute_det_ratio_down
      double det_rat = compute_det_ratio_down(M,rows_removed,invBigMatrix);
      ASSERT_TRUE(std::abs(det_rat-alps::numeric::determinant(SmallMatrix)/alps::numeric::determinant(BigMatrix))<1E-8) << "N=" << N << " M=" << M;

      matrix_t invSmallMatrix2(invBigMatrix);
      double det_rat2 = compute_inverse_matrix_down(M,rows_removed,invSmallMatrix2, swap_list);
      ASSERT_TRUE(std::abs(det_rat-det_rat2)<1E-8) << "N=" << N << " M=" << M;

      matrix_t SmallMatrix3(BigMatrix);
      for (int s=0; s<swap_list.size(); ++s) {
        SmallMatrix3.swap_cols(swap_list[s].first, swap_list[s].second);
        SmallMatrix3.swap_rows(swap_list[s].first, swap_list[s].second);
      }
      SmallMatrix3.resize(N,N);
      ASSERT_TRUE(alps::numeric::norm_square(inverse(SmallMatrix3)-invSmallMatrix2)<1E-8) << "N=" << N << " M=" << M;
    }
  }
}
Example #16
0
// Compute inverse matrices of the given matrix vector.
matvec inverse (matvec a) {
  matvec res (a.getSize (), a.getRows (), a.getCols ());
  for (int i = 0; i < a.getSize (); i++) res.set (inverse (a.get (i)), i);
  return res;
}
void inverseTranspose(akMatrix4& mat)
{
    //TODO optimise
    akMatrix4 tmp = inverse(mat);
    mat = transpose(tmp);
}
Example #18
0
void Transform::inverse(Ensemble& iEnsemble) const {
   for(int i = 0; i < iEnsemble.size(); i++) {
      iEnsemble[i] = inverse(iEnsemble[i]);
   }
}
int main () {
    // start GL context with helper libraries
    assert (glfwInit ());
    // uncomment these lines if on Apple OS X
    /*glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);*/
    GLFWwindow* window = glfwCreateWindow (
                             g_viewport_width, g_viewport_height, "GUI Panels", NULL, NULL);
    glfwSetWindowSizeCallback (window, glfw_window_size_callback);
    glfwMakeContextCurrent (window);
    glewExperimental = GL_TRUE;
    glewInit ();
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf ("Renderer: %s\n", renderer);
    printf ("OpenGL version supported %s\n", version);

    // create a 2d panel. from 2 triangles = 6 xy coords.
    float points[] = {
        -1.0f, -1.0f,
        1.0f, -1.0f,
        -1.0f,  1.0f,
        -1.0f,  1.0f,
        1.0f, -1.0f,
        1.0f,  1.0f
    };
    // for ground plane we can just re-use panel points but y is now z
    GLuint vp_vbo, vao;
    glGenBuffers (1, &vp_vbo);
    glBindBuffer (GL_ARRAY_BUFFER, vp_vbo);
    glBufferData (GL_ARRAY_BUFFER, sizeof (points), points, GL_STATIC_DRAW);
    glGenVertexArrays (1, &vao);
    glBindVertexArray (vao);
    // note: vertex buffer is already bound
    glVertexAttribPointer (0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
    glEnableVertexAttribArray (0);

    // create a 3d camera to move in 3d so that we can tell that the panel is 2d
    // keep track of some useful vectors that can be used for keyboard movement
    vec4 fwd (0.0f, 0.0f, -1.0f, 0.0f);
    vec4 rgt (1.0f, 0.0f, 0.0f, 0.0f);
    vec4 up (0.0f, 1.0f, 0.0f, 0.0f);
    vec3 cam_pos (0.0f, 1.0f, 5.0f);
    mat4 T_inv = translate (identity_mat4 (), cam_pos);
    // point slightly downwards to see the plane
    versor quaternion = quat_from_axis_deg (0.0f, 1.0f, 0.0f, 0.0f);
    mat4 R_inv = quat_to_mat4 (quaternion);
    // combine the inverse rotation and transformation to make a view matrix
    V = inverse (R_inv) * inverse (T_inv);
    // projection matrix
    P = perspective (
            67.0f, (float)g_viewport_width / (float)g_viewport_height, 0.1f, 100.0f);
    const float cam_speed = 3.0f; // 1 unit per second
    const float cam_heading_speed = 50.0f; // 30 degrees per second

    create_ground_plane_shaders ();
    create_gui_shaders ();

    // textures for ground plane and gui
    GLuint gp_tex, gui_tex;
    assert (load_texture ("tile2-diamonds256x256.png", &gp_tex));
    assert (load_texture ("skulluvmap.png", &gui_tex));

    // rendering defaults
    glDepthFunc (GL_LESS); // set depth function but don't enable yet
    glEnable (GL_CULL_FACE); // cull face
    glCullFace (GL_BACK); // cull back face
    glFrontFace (GL_CCW); // GL_CCW for counter clock-wise

    // absolute panel dimensions in pixels
    const float panel_width = 256.0f;
    const float panel_height = 256.0f;

    glViewport (0, 0, g_viewport_width, g_viewport_height);

    // start main rendering loop
    while (!glfwWindowShouldClose (window)) {
        // update timers
        static double previous_seconds = glfwGetTime ();
        double current_seconds = glfwGetTime ();
        double elapsed_seconds = current_seconds - previous_seconds;
        previous_seconds = current_seconds;

        bool cam_moved = false;
        vec3 move (0.0, 0.0, 0.0);

        // wipe the drawing surface clear
        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // draw ground plane. note: depth test is enabled here
        glEnable (GL_DEPTH_TEST);
        glActiveTexture (GL_TEXTURE0);
        glBindTexture (GL_TEXTURE_2D, gp_tex);
        glUseProgram (gp_sp);
        glBindVertexArray (vao);
        glDrawArrays (GL_TRIANGLES, 0, 6);

        // draw GUI panel. note: depth test is disabled here and drawn AFTER scene
        glDisable (GL_DEPTH_TEST);
        glActiveTexture (GL_TEXTURE0);
        glBindTexture (GL_TEXTURE_2D, gui_tex);
        glUseProgram (gui_sp);
        // resize panel to size in pixels
        float x_scale = panel_width / g_viewport_width;
        float y_scale = panel_height / g_viewport_height;
        glUniform2f (gui_scale_loc, x_scale, y_scale);
        glBindVertexArray (vao);
        glDrawArrays (GL_TRIANGLES, 0, 6);

        // update other events like input handling
        glfwPollEvents ();
        if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) {
            glfwSetWindowShouldClose (window, 1);
        }
        float cam_yaw = 0.0f; // y-rotation in degrees
        float cam_pitch = 0.0f;
        float cam_roll = 0.0;
        if (glfwGetKey (window, GLFW_KEY_A)) {
            move.v[0] -= cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_D)) {
            move.v[0] += cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_Q)) {
            move.v[1] += cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_E)) {
            move.v[1] -= cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_W)) {
            move.v[2] -= cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_S)) {
            move.v[2] += cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_LEFT)) {
            cam_yaw += cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_yaw = quat_from_axis_deg (cam_yaw, up.v[0], up.v[1], up.v[2]);
            quaternion = q_yaw * quaternion;
        }
        if (glfwGetKey (window, GLFW_KEY_RIGHT)) {
            cam_yaw -= cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_yaw = quat_from_axis_deg (cam_yaw, up.v[0], up.v[1], up.v[2]);
            quaternion = q_yaw * quaternion;
        }
        if (glfwGetKey (window, GLFW_KEY_UP)) {
            cam_pitch += cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_pitch = quat_from_axis_deg (
                                 cam_pitch, rgt.v[0], rgt.v[1], rgt.v[2]);
            quaternion = q_pitch * quaternion;
        }
        if (glfwGetKey (window, GLFW_KEY_DOWN)) {
            cam_pitch -= cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_pitch = quat_from_axis_deg (
                                 cam_pitch, rgt.v[0], rgt.v[1], rgt.v[2]);
            quaternion = q_pitch * quaternion;
        }
        if (glfwGetKey (window, GLFW_KEY_Z)) {
            cam_roll -= cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_roll = quat_from_axis_deg (
                                cam_roll, fwd.v[0], fwd.v[1], fwd.v[2]);
            quaternion = q_roll * quaternion;
        }
        if (glfwGetKey (window, GLFW_KEY_C)) {
            cam_roll += cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_roll = quat_from_axis_deg (
                                cam_roll, fwd.v[0], fwd.v[1], fwd.v[2]);
            quaternion = q_roll * quaternion;
        }
        // update view matrix
        if (cam_moved) {
            // re-calculate local axes so can move fwd in dir cam is pointing
            R_inv = quat_to_mat4 (quaternion);
            fwd = R_inv * vec4 (0.0, 0.0, -1.0, 0.0);
            rgt = R_inv * vec4 (1.0, 0.0, 0.0, 0.0);
            up = R_inv * vec4 (0.0, 1.0, 0.0, 0.0);

            cam_pos = cam_pos + vec3 (fwd) * -move.v[2];
            cam_pos = cam_pos + vec3 (up) * move.v[1];
            cam_pos = cam_pos + vec3 (rgt) * move.v[0];
            T_inv = translate (identity_mat4 (), cam_pos);

            V = inverse (R_inv) * inverse (T_inv);
            glUseProgram (gp_sp);
            glUniformMatrix4fv (gp_V_loc, 1, GL_FALSE, V.m);
        }
        // put the stuff we've been drawing onto the display
        glfwSwapBuffers (window);
    }
    // done
    glfwTerminate();
    return 0;
}
Example #20
0
	inline V3 Contact::calculate_friction_impulse(M3* inv_inertia_tensor)
	{

		F inverse_mass = bodies[0]->get_inverse_mass();
		auto o = relative_contact_position[0];

		//Usually you get a torque from an impulse by a cross product with the relative distance.
		//If we build a M3 from the relative distance in this way, we have a matrix
		//that goes from impulse to torque
		M3 impulse_to_torque = -M3(
			0, -o.z, o.y,
			o.z, 0, -o.x,
			-o.y, o.x, 0
			);
		M3 delta_vel_world = impulse_to_torque;
		delta_vel_world *= inv_inertia_tensor[0];	//Rotation generated by unit torque
		delta_vel_world *= impulse_to_torque;		//Same as crossing the relative contact pos. Gives linear vel generated by torque only
		delta_vel_world *= -1;						//M1 x M2 = - M2 x M1, thus the minus


		// Check if we need to the second body's data
		if (bodies[1])
		{
			auto o = relative_contact_position[1];
			impulse_to_torque = -M3(
				0, -o.z, o.y,
				o.z, 0, -o.x,
				-o.y, o.x, 0
				);

			M3 delta_vel_world_2 = impulse_to_torque;
			delta_vel_world_2 *= inv_inertia_tensor[1];	//Rotation generated by unit torque
			delta_vel_world_2 *= impulse_to_torque;		//Same as crossing the relative contact pos. Gives linear vel generated by torque only
			delta_vel_world_2 *= -1;						//M1 x M2 = - M2 x M1, thus the minus

			//combine velocities and masses
			delta_vel_world += delta_vel_world_2;
			inverse_mass += bodies[1]->get_inverse_mass();
		}

		//change base of matrix (B x M x B^-1) to get velocity in contact coords
		M3 delta_velocity = transpose(contact_to_world) * delta_vel_world * contact_to_world;

		//Add the linear velocity. Need to build a matrix like this:
		//m,0,0
		//0,m,0
		//0,0,m
		delta_velocity[0].x += inverse_mass;
		delta_velocity[1].y += inverse_mass;
		delta_velocity[2].z += inverse_mass;


		//From: 
		//unit velocity generated by impulse
		//To:
		//Impulse requires to generate unit velocity
		M3 impulse_matrix = inverse(delta_velocity);

		//Velocities to kill. The x element is the same as the frictionless impulse
		//and must be completely null out
		V3 vel_kill(desired_delta_velocity, -contact_velocity.y, -contact_velocity.z);

		//Get impulse necessary to kill the velocities
		V3 impulse_contact = impulse_matrix * vel_kill;

		//Get only the planar impulse
		F planar_impulse = sqrt(impulse_contact.y*impulse_contact.y + impulse_contact.z * impulse_contact.z);


		//The X of the impulse is the one along the normal.
		//This impulse, multiplied by friction, is the amount to overcome.
		//If the planar is greater, than there is enough force for dynamic friction
		if (planar_impulse > impulse_contact.x * friction) {
			impulse_contact.y /= planar_impulse;
			impulse_contact.z /= planar_impulse;

			//Recalculate delta_velocity (and store it in impulse_contact.X just for caching)
			impulse_contact.x =
				delta_velocity[0].x +
				delta_velocity[1].x * impulse_contact.y * friction +
				delta_velocity[2].x * impulse_contact.z * friction;
			impulse_contact.x = desired_delta_velocity / impulse_contact.x;
			impulse_contact.y *= friction * impulse_contact.x;
			impulse_contact.z *= friction * impulse_contact.x;

		}

		return impulse_contact;

	}
Example #21
0
static void normaldist_inverse(double* data, size_t count) {
    inverse(data, count);
}
Example #22
0
File: phong.cpp Project: bssrdf/dpt
void SamplePhong(const bool adjoint,
                 const ADFloat *buffer,
                 const ADVector3 &wi,
                 const ADVector3 &normal,
                 const ADVector2 st,
                 const ADVector2 rndParam,
                 const ADFloat uDiscrete,
                 const bool fixDiscrete,
                 ADVector3 &wo,
                 ADVector3 &contrib,
                 ADFloat &cosWo,
                 ADFloat &pdf,
                 ADFloat &revPdf) {
    ADVector3 Kd;
    ADVector3 Ks;
    ADFloat exponent;
    ADFloat KsWeight;
    buffer = Deserialize(buffer, Kd);
    buffer = Deserialize(buffer, Ks);
    buffer = Deserialize(buffer, exponent);
    buffer = Deserialize(buffer, KsWeight);

    ADFloat cosWi = Dot(normal, wi);
    std::vector<CondExprCPtr> ret = CreateCondExprVec(4);
    BeginIf(Gt(cosWi, Float(0.0)), ret);
    { SetCondOutput({normal[0], normal[1], normal[2], cosWi}); }
    BeginElse();
    { SetCondOutput({-normal[0], -normal[1], -normal[2], -cosWi}); }
    EndIf();
    ADVector3 normal_(ret[0], ret[1], ret[2]);
    cosWi = ret[3];
    ADVector3 R = Reflect(wi, normal_);
    ret = CreateCondExprVec(4);
    BeginIf(Gt(uDiscrete, KsWeight), ret);
    {
        ADVector3 localDir = SampleCosHemisphere(rndParam);
        ADVector3 b0;
        ADVector3 b1;
        CoordinateSystem(normal_, b0, b1);
        ADVector3 wo = localDir[0] * b0 + localDir[1] * b1 + localDir[2] * normal_;
        ADFloat factor = (Float(1.0) - KsWeight);
        SetCondOutput({wo[0], wo[1], wo[2], factor});
    }
    BeginElse();
    {
        ADFloat power = Float(1.0) / (exponent + Float(1.0));
        ADFloat cosAlpha = pow(rndParam[1], power);
        // Ugly hack to avoid sqrt(0) which has undefined derivatives...
        ADFloat sinAlpha = sqrt(fmax(Float(1.0) - square(cosAlpha), Float(1e-6)));
        ADFloat phi = c_TWOPI * rndParam[0];
        ADVector3 localDir = ADVector3(sinAlpha * cos(phi), sinAlpha * sin(phi), cosAlpha);
        ADVector3 b0;
        ADVector3 b1;
        CoordinateSystem(R, b0, b1);
        ADVector3 wo = localDir[0] * b0 + localDir[1] * b1 + localDir[2] * R;
        ADFloat factor = KsWeight;
        SetCondOutput({wo[0], wo[1], wo[2], factor});
    }
    EndIf();
    wo = ADVector3(ret[0], ret[1], ret[2]);
    ADFloat factor = ret[3];
    cosWo = Dot(normal_, wo);

    BeginIf(Gt(KsWeight, Float(0.0)), ret);
    {
        ADFloat alpha = fmax(Dot(Reflect(wi, normal_), wo), Float(0.0));
        ADFloat weight = pow(alpha, exponent) * c_INVTWOPI;
        ADFloat expoConst1 = (exponent + Float(1.0));
        ADFloat expoConst2 = (exponent + Float(2.0));
        std::vector<CondExprCPtr> ret = CreateCondExprVec(4);
        BeginIf(Gt(weight, Float(1e-10)), ret);
        {
            ADVector3 specContrib = Ks * (expoConst2 * weight);
            ADFloat specPdf = KsWeight * expoConst1 * weight;
            SetCondOutput({specContrib[0], specContrib[1], specContrib[2], specPdf});
        }
        BeginElse();
        {
            SetCondOutput({Const<ADFloat>(0.0),
                           Const<ADFloat>(0.0),
                           Const<ADFloat>(0.0),
                           Const<ADFloat>(0.0)});
        }
        EndIf();
        ADVector3 specContrib = ADVector3(ret[0], ret[1], ret[2]);
        ADFloat specPdf = ret[3];
        SetCondOutput({specContrib[0], specContrib[1], specContrib[2], specPdf});
    }
    BeginElse();
    {
        SetCondOutput(
            {Const<ADFloat>(0.0), Const<ADFloat>(0.0), Const<ADFloat>(0.0), Const<ADFloat>(0.0)});
    }
    EndIf();
    contrib[0] = ret[0];
    contrib[1] = ret[1];
    contrib[2] = ret[2];
    pdf = ret[3];
    revPdf = ret[3];

    ret = CreateCondExprVec(5);
    BeginIf(Lt(KsWeight, Float(1.0)), ret);
    {
        ADVector3 diffContrib = Kd * Const<ADFloat>(c_INVPI);
        ADFloat tmp = (Float(1.0) - KsWeight) * c_INVPI;
        ADFloat diffPdf = tmp * cosWo;
        ADFloat revDiffPdf = tmp * cosWi;
        SetCondOutput({diffContrib[0], diffContrib[1], diffContrib[2], diffPdf, revDiffPdf});
    }
    BeginElse();
    {
        SetCondOutput({Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0),
                       Const<ADFloat>(0.0)});
    }
    EndIf();
    contrib[0] += ret[0];
    contrib[1] += ret[1];
    contrib[2] += ret[2];
    pdf += ret[3];
    revPdf += ret[4];

    contrib *= cosWo;
    contrib *= inverse(pdf);
    if (fixDiscrete) {
        contrib *= factor;
    }
}
Example #23
0
File: encrypt3.c Project: TomYZ/hw4
void encrypt3(char *s,FILE* f,FILE* p,int decrypt){
    char PC1[56]={0};
    char PC2[48]={0};
    unsigned char input[8]={0};
    char V[16]={0};
    int K1[16][48],K2[16][48],K3[16][48];
    char IP[64]={0};
    char IP1[64]={0};
    unsigned int m[64]={0};
    int L0[32]={0},R0[32]={0};
    int i=0,j,k,temp,c,r;
    char E[48]={0};
    char S[8][64];
    char P[32];
    int Rtemp[48]={0};
    char T[32]={0};
    char fun[32]={0};
    int output[64]={0};
    int outtemp[64]={0};
    int cc;
    int flag=0;
    int count=0;
    //fseek(f,0,SEEK_SET);
    if(tablecheck(f,PC1,V,PC2,IP,E,S,P)==false){
        
        fprintf(stderr,"malformed table\n");
        return ;
    }
    if(s[0]!='1'){
        fprintf(stderr,"key too short\n");
        return ;
    }
    
    key_schedule(s,PC1,V,PC2,K1);
    key_schedule(s+16,PC1,V,PC2,K2);
    key_schedule(s+32,PC1,V,PC2,K3);
    while((cc=fgetc(p))!=EOF){
        
        input[count]=cc;
        
        
        count++;
        
        if (count==8) {
            
            array_hex_to_bin(input,m,8,0);
            
            
            
            for(i=0;i<32;i++){
                L0[i]=m[IP[i]-1];//  IP (m1m2...m64)
            }
            
            for(i=32;i<64;i++){
                R0[i-32]=m[IP[i]-1];
            }
            if (flag==0) {
                fprintf(stderr,"(L0,R0)=");
                print_hex_from_bin(L0,32);
                print_hex_from_bin(R0,32);
                fprintf(stderr,"\n");
            }
            
            for(i=0;i<16;i++){
                for(j=0;j<48;j++)
                {
                    if(decrypt==0){
                        Rtemp[j]=(R0[E[j]-1]+K1[i][j])%2;//  E(Ri-1)+ki
                    }else{
                        
                        Rtemp[j]=(R0[E[j]-1]+K3[15-i][j])%2;
                    }
                    
                }
                
                for(j=0;j<8;j++){
                    r=Rtemp[j*6]*2+Rtemp[j*6+5];//r and c
                    c=0;
                    temp=8;
                    for(k=1;k<5;k++){
                        
                        c+=Rtemp[j*6+k]*temp;
                        temp/=2;
                    }
                    temp=S[j][r*16+c];// Sbox
                    T[j*4+3]=temp%2;
                    temp/=2;
                    T[j*4+2]=temp%2;
                    temp/=2;
                    T[j*4+1]=temp%2;
                    temp/=2;
                    T[j*4]=temp%2;
                }
                for(j=0;j<32;j++){
                    fun[j]=T[P[j]-1];//P permutation
                }
                for(j=0;j<32;j++){
                    Rtemp[j]=(L0[j]+fun[j])%2;//L0 +
                }
                if (flag==0) {
                    fprintf(stderr,"(L%d,R%d)=",i+1,i+1);
                    
                    print_hex_from_bin(R0,32);
                    print_hex_from_bin(Rtemp,32);
                    fprintf(stderr,"\n");
                }
                if(i!=15){
                    for(j=0;j<32;j++){
                        L0[j]=R0[j];
                    }
                    for(j=0;j<32;j++){
                        R0[j]=Rtemp[j];
                    }
                }
            }
            inverse(IP,IP1);
            for(i=0;i<64;i++){
                if(i<32)
                    outtemp[i]=Rtemp[i];
                else
                    outtemp[i]=R0[i-32];
            }
            
            
            for(i=0;i<64;i++){
                output[i]=outtemp[IP1[i]-1];
                
            }
            //----------------------------------------------------------------------------------------------
            
            
            for(i=0;i<64;i++){
                m[i]=output[i];
            }
            
            
            
            for(i=0;i<32;i++){
                L0[i]=m[IP[i]-1];//  IP (m1m2...m64)
            }
            
            for(i=32;i<64;i++){
                R0[i-32]=m[IP[i]-1];
            }
            if (flag==0) {
                fprintf(stderr,"(L0,R0)=");
                print_hex_from_bin(L0,32);
                print_hex_from_bin(R0,32);
                fprintf(stderr,"\n");
            }
            
            for(i=0;i<16;i++){
                for(j=0;j<48;j++)
                {
                    if(decrypt==1){
                        Rtemp[j]=(R0[E[j]-1]+K2[i][j])%2;//  E(Ri-1)+ki
                    }else{
                        
                        Rtemp[j]=(R0[E[j]-1]+K2[15-i][j])%2;
                    }
                    
                }
                
                for(j=0;j<8;j++){
                    r=Rtemp[j*6]*2+Rtemp[j*6+5];//r and c
                    c=0;
                    temp=8;
                    for(k=1;k<5;k++){
                        
                        c+=Rtemp[j*6+k]*temp;
                        temp/=2;
                    }
                    temp=S[j][r*16+c];// Sbox
                    T[j*4+3]=temp%2;
                    temp/=2;
                    T[j*4+2]=temp%2;
                    temp/=2;
                    T[j*4+1]=temp%2;
                    temp/=2;
                    T[j*4]=temp%2;
                }
                for(j=0;j<32;j++){
                    fun[j]=T[P[j]-1];//P permutation
                }
                for(j=0;j<32;j++){
                    Rtemp[j]=(L0[j]+fun[j])%2;//L0 +
                }
                if (flag==0) {
                    fprintf(stderr,"(L%d,R%d)=",i+1,i+1);
                    
                    print_hex_from_bin(R0,32);
                    print_hex_from_bin(Rtemp,32);
                    fprintf(stderr,"\n");
                }
                if(i!=15){
                    for(j=0;j<32;j++){
                        L0[j]=R0[j];
                    }
                    for(j=0;j<32;j++){
                        R0[j]=Rtemp[j];
                    }
                }
            }
            inverse(IP,IP1);
            for(i=0;i<64;i++){
                if(i<32)
                    outtemp[i]=Rtemp[i];
                else
                    outtemp[i]=R0[i-32];
            }
            
            
            for(i=0;i<64;i++){
                output[i]=outtemp[IP1[i]-1];
                
            }
            
            
            
            //----------------------------------------------------------------------------------------------
            
            
            
            for(i=0;i<64;i++){
                m[i]=output[i];
            }
            
            
            
            for(i=0;i<32;i++){
                L0[i]=m[IP[i]-1];//  IP (m1m2...m64)
            }
            
            for(i=32;i<64;i++){
                R0[i-32]=m[IP[i]-1];
            }
            if (flag==0) {
                fprintf(stderr,"(L0,R0)=");
                print_hex_from_bin(L0,32);
                print_hex_from_bin(R0,32);
                fprintf(stderr,"\n");
            }
            
            for(i=0;i<16;i++){
                for(j=0;j<48;j++)
                {
                    if(decrypt==0){
                        Rtemp[j]=(R0[E[j]-1]+K3[i][j])%2;//  E(Ri-1)+ki
                    }else{
                        
                        Rtemp[j]=(R0[E[j]-1]+K1[15-i][j])%2;
                    }
                    
                }
                
                for(j=0;j<8;j++){
                    r=Rtemp[j*6]*2+Rtemp[j*6+5];//r and c
                    c=0;
                    temp=8;
                    for(k=1;k<5;k++){
                        
                        c+=Rtemp[j*6+k]*temp;
                        temp/=2;
                    }
                    temp=S[j][r*16+c];// Sbox
                    T[j*4+3]=temp%2;
                    temp/=2;
                    T[j*4+2]=temp%2;
                    temp/=2;
                    T[j*4+1]=temp%2;
                    temp/=2;
                    T[j*4]=temp%2;
                }
                for(j=0;j<32;j++){
                    fun[j]=T[P[j]-1];//P permutation
                }
                for(j=0;j<32;j++){
                    Rtemp[j]=(L0[j]+fun[j])%2;//L0 +
                }
                if (flag==0) {
                    fprintf(stderr,"(L%d,R%d)=",i+1,i+1);
                    
                    print_hex_from_bin(R0,32);
                    print_hex_from_bin(Rtemp,32);
                    fprintf(stderr,"\n");
                }
                if(i!=15){
                    for(j=0;j<32;j++){
                        L0[j]=R0[j];
                    }
                    for(j=0;j<32;j++){
                        R0[j]=Rtemp[j];
                    }
                }
            }
            inverse(IP,IP1);
            for(i=0;i<64;i++){
                if(i<32)
                    outtemp[i]=Rtemp[i];
                else
                    outtemp[i]=R0[i-32];
            }
            
            
            for(i=0;i<64;i++){
                output[i]=outtemp[IP1[i]-1];
                
            }
            
            
            
            //----------------------------------------------------------------------------------------------
            
            
            print_char_from_bin(output,64);
            
            flag=1;
            count=0;
        }
        
    }
    if(count>0){
        
        array_hex_to_bin(input,m,count,8-count);
        
        for(i=0;i<32;i++){
            L0[i]=m[IP[i]-1];//  IP (m1m2...m64)
        }
        
        for(i=32;i<64;i++){
            R0[i-32]=m[IP[i]-1];
        }
        if (flag==0) {
            fprintf(stderr,"(L0,R0)=");
            print_hex_from_bin(L0,32);
            print_hex_from_bin(R0,32);
            fprintf(stderr,"\n");
        }
        
        for(i=0;i<16;i++){
            for(j=0;j<48;j++)
            {
                if(decrypt==0){
                    Rtemp[j]=(R0[E[j]-1]+K1[i][j])%2;//  E(Ri-1)+ki
                }else{
                    
                    Rtemp[j]=(R0[E[j]-1]+K3[15-i][j])%2;
                }
                
            }
            
            for(j=0;j<8;j++){
                r=Rtemp[j*6]*2+Rtemp[j*6+5];//r and c
                c=0;
                temp=8;
                for(k=1;k<5;k++){
                    
                    c+=Rtemp[j*6+k]*temp;
                    temp/=2;
                }
                temp=S[j][r*16+c];// Sbox
                T[j*4+3]=temp%2;
                temp/=2;
                T[j*4+2]=temp%2;
                temp/=2;
                T[j*4+1]=temp%2;
                temp/=2;
                T[j*4]=temp%2;
            }
            for(j=0;j<32;j++){
                fun[j]=T[P[j]-1];//P permutation
            }
            for(j=0;j<32;j++){
                Rtemp[j]=(L0[j]+fun[j])%2;//L0 +
            }
            if (flag==0) {
                fprintf(stderr,"(L%d,R%d)=",i+1,i+1);
                
                print_hex_from_bin(R0,32);
                print_hex_from_bin(Rtemp,32);
                fprintf(stderr,"\n");
            }
            if(i!=15){
                for(j=0;j<32;j++){
                    L0[j]=R0[j];
                }
                for(j=0;j<32;j++){
                    R0[j]=Rtemp[j];
                }
            }
        }
        inverse(IP,IP1);
        for(i=0;i<64;i++){
            if(i<32)
                outtemp[i]=Rtemp[i];
            else
                outtemp[i]=R0[i-32];
        }
        
        
        for(i=0;i<64;i++){
            output[i]=outtemp[IP1[i]-1];
            
        }
        
        
        
        
        //----------------------------------------------------------------------------------------------
        
        
        for(i=0;i<64;i++){
            m[i]=output[i];
        }
        
        
        
        for(i=0;i<32;i++){
            L0[i]=m[IP[i]-1];//  IP (m1m2...m64)
        }
        
        for(i=32;i<64;i++){
            R0[i-32]=m[IP[i]-1];
        }
        if (flag==0) {
            fprintf(stderr,"(L0,R0)=");
            print_hex_from_bin(L0,32);
            print_hex_from_bin(R0,32);
            fprintf(stderr,"\n");
        }
        
        for(i=0;i<16;i++){
            for(j=0;j<48;j++)
            {
                if(decrypt==1){
                    Rtemp[j]=(R0[E[j]-1]+K2[i][j])%2;//  E(Ri-1)+ki
                }else{
                    
                    Rtemp[j]=(R0[E[j]-1]+K2[15-i][j])%2;
                }
                
            }
            
            for(j=0;j<8;j++){
                r=Rtemp[j*6]*2+Rtemp[j*6+5];//r and c
                c=0;
                temp=8;
                for(k=1;k<5;k++){
                    
                    c+=Rtemp[j*6+k]*temp;
                    temp/=2;
                }
                temp=S[j][r*16+c];// Sbox
                T[j*4+3]=temp%2;
                temp/=2;
                T[j*4+2]=temp%2;
                temp/=2;
                T[j*4+1]=temp%2;
                temp/=2;
                T[j*4]=temp%2;
            }
            for(j=0;j<32;j++){
                fun[j]=T[P[j]-1];//P permutation
            }
            for(j=0;j<32;j++){
                Rtemp[j]=(L0[j]+fun[j])%2;//L0 +
            }
            if (flag==0) {
                fprintf(stderr,"(L%d,R%d)=",i+1,i+1);
                
                print_hex_from_bin(R0,32);
                print_hex_from_bin(Rtemp,32);
                fprintf(stderr,"\n");
            }
            if(i!=15){
                for(j=0;j<32;j++){
                    L0[j]=R0[j];
                }
                for(j=0;j<32;j++){
                    R0[j]=Rtemp[j];
                }
            }
        }
        inverse(IP,IP1);
        for(i=0;i<64;i++){
            if(i<32)
                outtemp[i]=Rtemp[i];
            else
                outtemp[i]=R0[i-32];
        }
        
        
        for(i=0;i<64;i++){
            output[i]=outtemp[IP1[i]-1];
            
        }
        
        
        
        //----------------------------------------------------------------------------------------------
        
        
        
        for(i=0;i<64;i++){
            m[i]=output[i];
        }
        
        
        
        for(i=0;i<32;i++){
            L0[i]=m[IP[i]-1];//  IP (m1m2...m64)
        }
        
        for(i=32;i<64;i++){
            R0[i-32]=m[IP[i]-1];
        }
        if (flag==0) {
            fprintf(stderr,"(L0,R0)=");
            print_hex_from_bin(L0,32);
            print_hex_from_bin(R0,32);
            fprintf(stderr,"\n");
        }
        
        for(i=0;i<16;i++){
            for(j=0;j<48;j++)
            {
                if(decrypt==0){
                    Rtemp[j]=(R0[E[j]-1]+K3[i][j])%2;//  E(Ri-1)+ki
                }else{
                    
                    Rtemp[j]=(R0[E[j]-1]+K1[15-i][j])%2;
                }
                
            }
            
            for(j=0;j<8;j++){
                r=Rtemp[j*6]*2+Rtemp[j*6+5];//r and c
                c=0;
                temp=8;
                for(k=1;k<5;k++){
                    
                    c+=Rtemp[j*6+k]*temp;
                    temp/=2;
                }
                temp=S[j][r*16+c];// Sbox
                T[j*4+3]=temp%2;
                temp/=2;
                T[j*4+2]=temp%2;
                temp/=2;
                T[j*4+1]=temp%2;
                temp/=2;
                T[j*4]=temp%2;
            }
            for(j=0;j<32;j++){
                fun[j]=T[P[j]-1];//P permutation
            }
            for(j=0;j<32;j++){
                Rtemp[j]=(L0[j]+fun[j])%2;//L0 +
            }
            if (flag==0) {
                fprintf(stderr,"(L%d,R%d)=",i+1,i+1);
                
                print_hex_from_bin(R0,32);
                print_hex_from_bin(Rtemp,32);
                fprintf(stderr,"\n");
            }
            if(i!=15){
                for(j=0;j<32;j++){
                    L0[j]=R0[j];
                }
                for(j=0;j<32;j++){
                    R0[j]=Rtemp[j];
                }
            }
        }
        inverse(IP,IP1);
        for(i=0;i<64;i++){
            if(i<32)
                outtemp[i]=Rtemp[i];
            else
                outtemp[i]=R0[i-32];
        }
        
        
        for(i=0;i<64;i++){
            output[i]=outtemp[IP1[i]-1];
            
        }
        //----------------------------------------------------------------------------------------------
        
        print_char_from_bin(output,64);
        
        
    }
    return;
    
}
Example #24
0
File: phong.cpp Project: bssrdf/dpt
bool Phong::Sample(const Vector3 &wi,
                   const Vector3 &normal,
                   const Vector2 st,
                   const Vector2 rndParam,
                   const Float uDiscrete,
                   Vector3 &wo,
                   Vector3 &contrib,
                   Float &cosWo,
                   Float &pdf,
                   Float &revPdf) const {
    Float cosWi = Dot(wi, normal);
    if (fabs(cosWi) < c_CosEpsilon) {
        return false;
    }

    Vector3 normal_ = normal;
    if (cosWi < Float(0.0)) {
        if (twoSided) {
            cosWi = -cosWi;
            normal_ = -normal_;
        } else {
            return false;
        }
    }

    const Float expo = exponent->Eval(st)[0];
    const Vector3 R = Reflect(wi, normal_);
    Float g;
    Vector3 n;
    if (uDiscrete > KsWeight) {
        g = Float(1.0);
        n = normal_;
    } else {
        g = expo;
        n = R;
    }
    const Float power = Float(1.0) / (g + Float(1.0));
    const Float cosAlpha = pow(rndParam[1], power);
    assert(cosAlpha >= Float(0.0) && cosAlpha <= Float(1.0));
    const Float sinAlpha = sqrt(Float(1.0) - square(cosAlpha));
    const Float phi = c_TWOPI * rndParam[0];
    const Vector3 localDir = Vector3(sinAlpha * cos(phi), sinAlpha * sin(phi), cosAlpha);
    Vector3 b0;
    Vector3 b1;
    CoordinateSystem(n, b0, b1);
    wo = localDir[0] * b0 + localDir[1] * b1 + localDir[2] * n;

    cosWo = Dot(normal_, wo);
    if (cosWo < c_CosEpsilon) {
        return false;
    }
    contrib = Vector3::Zero();
    pdf = Float(0.0);
    if (KsWeight > Float(0.0)) {
        const Float alpha = fmax(Dot(R, wo), Float(0.0));
        const Float weight = pow(alpha, expo) * c_INVTWOPI;
        const Float expoConst1 = (expo + Float(1.0));
        const Float expoConst2 = (expo + Float(2.0));
        if (weight > Float(1e-10)) {
            contrib = Ks->Eval(st) * (expoConst2 * weight);
            pdf = KsWeight * expoConst1 * weight;
        }
        // Phong lobe sampling is symmetric
        revPdf = pdf;
    }
    if (KsWeight < Float(1.0)) {
        contrib += Kd->Eval(st) * c_INVPI;
        pdf += (Float(1.0) - KsWeight) * cosWo * c_INVPI;
        // reverse cosine hemisphere sampling is not symmetric
        revPdf += (Float(1.0) - KsWeight) * cosWi * c_INVPI;
    }
    contrib *= cosWo;

    if (pdf < Float(1e-10)) {
        return false;
    }

    assert(pdf > Float(0.0));
    contrib *= inverse(pdf);

    return true;
}
void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const
{
    ATRACE_CALL();

    if (CC_UNLIKELY(mActiveBuffer == 0)) {
        // the texture has not been created yet, this Layer has
        // in fact never been drawn into. This happens frequently with
        // SurfaceView because the WindowManager can't know when the client
        // has drawn the first time.

        // If there is nothing under us, we paint the screen in black, otherwise
        // we just skip this update.

        // figure out if there is something below us
        Region under;
        const SurfaceFlinger::LayerVector& drawingLayers(
                mFlinger->mDrawingState.layersSortedByZ);
        const size_t count = drawingLayers.size();
        for (size_t i=0 ; i<count ; ++i) {
            const sp<Layer>& layer(drawingLayers[i]);
            if (layer.get() == static_cast<Layer const*>(this))
                break;
            under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
        }
        // if not everything below us is covered, we plug the holes!
        Region holes(clip.subtract(under));
        if (!holes.isEmpty()) {
            clearWithOpenGL(hw, holes, 0, 0, 0, 1);
        }
        return;
    }

    // Bind the current buffer to the GL texture, and wait for it to be
    // ready for us to draw into.
    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
    if (err != NO_ERROR) {
        ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
        // Go ahead and draw the buffer anyway; no matter what we do the screen
        // is probably going to have something visibly wrong.
    }

    bool canAllowGPU = false;
#ifdef QCOM_BSP
    if(isProtected()) {
        char property[PROPERTY_VALUE_MAX];
        if ((property_get("persist.gralloc.cp.level3", property, NULL) > 0) &&
                (atoi(property) == 1)) {
            canAllowGPU = true;
        }
    }
#endif

    bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());

    RenderEngine& engine(mFlinger->getRenderEngine());

    if (!blackOutLayer || (canAllowGPU)) {
        // TODO: we could be more subtle with isFixedSize()
        const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();

        // Query the texture matrix given our current filtering mode.
        float textureMatrix[16];
        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);

        if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {

            /*
             * the code below applies the display's inverse transform to the texture transform
             */

            // create a 4x4 transform matrix from the display transform flags
            const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
            const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
            const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);

            mat4 tr;
            uint32_t transform = hw->getOrientationTransform();
            if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
                tr = tr * rot90;
            if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
                tr = tr * flipH;
            if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
                tr = tr * flipV;

            // calculate the inverse
            tr = inverse(tr);

            // and finally apply it to the original texture matrix
            const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
            memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
        }

        // Set things up for texturing.
        mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
        mTexture.setFiltering(useFiltering);
        mTexture.setMatrix(textureMatrix);

        engine.setupLayerTexturing(mTexture);
    } else {
        engine.setupLayerBlackedOut();
    }
    drawWithOpenGL(hw, clip);
    engine.disableTexturing();
}
Example #26
0
static void test_invert(skiatest::Reporter* reporter) {
    SkMatrix44 inverse(SkMatrix44::kUninitialized_Constructor);
    double inverseData[16];

    SkMatrix44 identity(SkMatrix44::kIdentity_Constructor);
    identity.invert(&inverse);
    inverse.asRowMajord(inverseData);
    assert16<double>(reporter, inverseData,
                     1, 0, 0, 0,
                     0, 1, 0, 0,
                     0, 0, 1, 0,
                     0, 0, 0, 1);

    SkMatrix44 translation(SkMatrix44::kUninitialized_Constructor);
    translation.setTranslate(2, 3, 4);
    translation.invert(&inverse);
    inverse.asRowMajord(inverseData);
    assert16<double>(reporter, inverseData,
                     1, 0, 0, -2,
                     0, 1, 0, -3,
                     0, 0, 1, -4,
                     0, 0, 0, 1);

    SkMatrix44 scale(SkMatrix44::kUninitialized_Constructor);
    scale.setScale(2, 4, 8);
    scale.invert(&inverse);
    inverse.asRowMajord(inverseData);
    assert16<double>(reporter, inverseData,
                     0.5, 0,    0,     0,
                     0,   0.25, 0,     0,
                     0,   0,    0.125, 0,
                     0,   0,    0,     1);

    SkMatrix44 scaleTranslation(SkMatrix44::kUninitialized_Constructor);
    scaleTranslation.setScale(10, 100, 1000);
    scaleTranslation.preTranslate(2, 3, 4);
    scaleTranslation.invert(&inverse);
    inverse.asRowMajord(inverseData);
    assert16<double>(reporter, inverseData,
                     0.1,  0,    0,   -2,
                     0,   0.01,  0,   -3,
                     0,    0,  0.001, -4,
                     0,    0,    0,   1);

    SkMatrix44 rotation(SkMatrix44::kUninitialized_Constructor);
    rotation.setRotateDegreesAbout(0, 0, 1, 90);
    rotation.invert(&inverse);
    SkMatrix44 expected(SkMatrix44::kUninitialized_Constructor);
    double expectedInverseRotation[16] =
            {0,  1, 0, 0,
             -1, 0, 0, 0,
             0,  0, 1, 0,
             0,  0, 0, 1};
    expected.setRowMajord(expectedInverseRotation);
    REPORTER_ASSERT(reporter, nearly_equal(expected, inverse));

    SkMatrix44 affine(SkMatrix44::kUninitialized_Constructor);
    affine.setRotateDegreesAbout(0, 0, 1, 90);
    affine.preScale(10, 20, 100);
    affine.preTranslate(2, 3, 4);
    affine.invert(&inverse);
    double expectedInverseAffine[16] =
            {0,    0.1,  0,   -2,
             -0.05, 0,   0,   -3,
             0,     0,  0.01, -4,
             0,     0,   0,   1};
    expected.setRowMajord(expectedInverseAffine);
    REPORTER_ASSERT(reporter, nearly_equal(expected, inverse));

    SkMatrix44 perspective(SkMatrix44::kIdentity_Constructor);
    perspective.setDouble(3, 2, 1.0);
    perspective.invert(&inverse);
    double expectedInversePerspective[16] =
            {1, 0,  0, 0,
             0, 1,  0, 0,
             0, 0,  1, 0,
             0, 0, -1, 1};
    expected.setRowMajord(expectedInversePerspective);
    REPORTER_ASSERT(reporter, nearly_equal(expected, inverse));

    SkMatrix44 affineAndPerspective(SkMatrix44::kIdentity_Constructor);
    affineAndPerspective.setDouble(3, 2, 1.0);
    affineAndPerspective.preScale(10, 20, 100);
    affineAndPerspective.preTranslate(2, 3, 4);
    affineAndPerspective.invert(&inverse);
    double expectedInverseAffineAndPerspective[16] =
            {0.1, 0,    2,   -2,
             0,  0.05,  3,   -3,
             0,   0,   4.01, -4,
             0,   0,   -1,    1};
    expected.setRowMajord(expectedInverseAffineAndPerspective);
    REPORTER_ASSERT(reporter, nearly_equal(expected, inverse));
}
Example #27
0
Twist Twist::operator-() const
{
    return inverse(*this);
}
Example #28
0
DEF_TEST(Matrix44, reporter) {
    SkMatrix44 mat(SkMatrix44::kUninitialized_Constructor);
    SkMatrix44 inverse(SkMatrix44::kUninitialized_Constructor);
    SkMatrix44 iden1(SkMatrix44::kUninitialized_Constructor);
    SkMatrix44 iden2(SkMatrix44::kUninitialized_Constructor);
    SkMatrix44 rot(SkMatrix44::kUninitialized_Constructor);

    mat.setTranslate(1, 1, 1);
    mat.invert(&inverse);
    iden1.setConcat(mat, inverse);
    REPORTER_ASSERT(reporter, is_identity(iden1));

    mat.setScale(2, 2, 2);
    mat.invert(&inverse);
    iden1.setConcat(mat, inverse);
    REPORTER_ASSERT(reporter, is_identity(iden1));

    mat.setScale(SK_MScalar1/2, SK_MScalar1/2, SK_MScalar1/2);
    mat.invert(&inverse);
    iden1.setConcat(mat, inverse);
    REPORTER_ASSERT(reporter, is_identity(iden1));

    mat.setScale(3, 3, 3);
    rot.setRotateDegreesAbout(0, 0, -1, 90);
    mat.postConcat(rot);
    REPORTER_ASSERT(reporter, mat.invert(NULL));
    mat.invert(&inverse);
    iden1.setConcat(mat, inverse);
    REPORTER_ASSERT(reporter, is_identity(iden1));
    iden2.setConcat(inverse, mat);
    REPORTER_ASSERT(reporter, is_identity(iden2));

    // test tiny-valued matrix inverse
    mat.reset();
    mat.setScale(1.0e-12, 1.0e-12, 1.0e-12);
    rot.setRotateDegreesAbout(0, 0, -1, 90);
    mat.postConcat(rot);
    mat.postTranslate(1.0e-12, 1.0e-12, 1.0e-12);
    REPORTER_ASSERT(reporter, mat.invert(NULL));
    mat.invert(&inverse);
    iden1.setConcat(mat, inverse);
    REPORTER_ASSERT(reporter, is_identity(iden1));

    // test mixed-valued matrix inverse
    mat.reset();
    mat.setScale(1.0e-10, 3.0, 1.0e+10);
    rot.setRotateDegreesAbout(0, 0, -1, 90);
    mat.postConcat(rot);
    mat.postTranslate(1.0e+10, 3.0, 1.0e-10);
    REPORTER_ASSERT(reporter, mat.invert(NULL));
    mat.invert(&inverse);
    iden1.setConcat(mat, inverse);
    REPORTER_ASSERT(reporter, is_identity(iden1));

    // test degenerate matrix
    mat.reset();
    mat.set3x3(1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    REPORTER_ASSERT(reporter, !mat.invert(NULL));

    // test rol/col Major getters
    {
        mat.setTranslate(2, 3, 4);
        float dataf[16];
        double datad[16];

        mat.asColMajorf(dataf);
        assert16<float>(reporter, dataf,
                 1, 0, 0, 0,
                 0, 1, 0, 0,
                 0, 0, 1, 0,
                 2, 3, 4, 1);
        mat.asColMajord(datad);
        assert16<double>(reporter, datad, 1, 0, 0, 0,
                        0, 1, 0, 0,
                        0, 0, 1, 0,
                        2, 3, 4, 1);
        mat.asRowMajorf(dataf);
        assert16<float>(reporter, dataf, 1, 0, 0, 2,
                        0, 1, 0, 3,
                        0, 0, 1, 4,
                        0, 0, 0, 1);
        mat.asRowMajord(datad);
        assert16<double>(reporter, datad, 1, 0, 0, 2,
                        0, 1, 0, 3,
                        0, 0, 1, 4,
                        0, 0, 0, 1);
    }

    test_concat(reporter);

    if (false) { // avoid bit rot, suppress warning (working on making this pass)
        test_common_angles(reporter);
    }

    test_constructor(reporter);
    test_gettype(reporter);
    test_determinant(reporter);
    test_invert(reporter);
    test_transpose(reporter);
    test_get_set_double(reporter);
    test_set_row_col_major(reporter);
    test_translate(reporter);
    test_scale(reporter);
    test_map2(reporter);
    test_3x3_conversion(reporter);
    test_has_perspective(reporter);
    test_preserves_2d_axis_alignment(reporter);
}
Example #29
0
inline long long int newton(const long long int &n, const long long int &k)
{
    return factorial[n] * inverse(factorial[k] * factorial[n - k]) % MOD;
}
double R_rlm_rand(double *X, double *y, int *N, int *P,
		int *Boot_Samp, int *Nres,
		int *M, int *size_boot, double *ours, double *full,
		double *Beta_m, double *Beta_s, double *Scale,
		int *Seed, int *calc_full,
		double *C, double *Psi_c, int *max_it,
		int *converged_mm,
		int *groups, int *n_group, int *k_fast_s)
{
void initialize_mat(double **a, int n, int m);
void initialize_vec(double *a, int n);
void R_S_rlm(double *X, double *y, int *n, int *P,
		int *nres, int *max_it,
		double *SCale, double *beta_s, double *beta_m,
		int *converged_mm,
		int *seed_rand, double *C, double *Psi_c,
		int *Groups, int *N_group, int *K_fast_s);
double Psi_reg(double,double);
double Psi_reg_prime(double,double);
double Chi_prime(double,double);
double Chi(double,double);
void sampler_i(int, int, int *);
int inverse(double **,double **, int);
void matias_vec_vec(double **, double *, double *, int);
void scalar_mat(double **, double, double **, int, int);
void scalar_vec(double *, double, double *, int);
void sum_mat(double **,double **, double **, int, int);
void sum_vec(double *, double *, double *, int);
void dif_mat(double **, double **, double **, int , int );
void dif_vec(double *, double *, double *, int);
void mat_vec(double **, double *, double *, int, int);
void mat_mat(double **, double **, double **, int, int, int);
// void disp_vec(double *, int);
// void disp_mat(double **, int, int);
// void disp_mat_i(int **, int, int);
// void disp_vec(double *, int);
/* double **xb; */
double *Xb, **xb;
int **boot_samp;
double **x, **x2, **x3, **x4, *beta_m, *beta_s,*beta_aux;
double *Fi, *res, *res_s, *w, *ww, dummyscale, scale;
double *v, *v2, *v_aux, *yb; // , timefinish, timestart;
double u,u2,s,c,Psi_constant;
// double test_chi=0, test_psi=0;
int n,p,m,seed; // ,*indices;
int nboot=*size_boot;
// int fake_p = 0;
register int i,j,k;
setbuf(stdout,NULL);
c = *C; Psi_constant = *Psi_c;
n = *N; p = *P; m = *M; seed = *Seed;
boot_samp = (int **) malloc(m * sizeof(int*) );
for(i=0;i<m;i++)
	boot_samp[i] = (int*) malloc(nboot *sizeof(int));
// indices = (int *) malloc( n * sizeof(int) );
v = (double *) malloc( p * sizeof(double) );
v2 = (double *) malloc( p * sizeof(double) );
v_aux = (double *) malloc( p * sizeof(double) );
yb = (double *) malloc( n * sizeof(double) );
Xb = (double*) malloc( n * p * sizeof(double) );
x =  (double **) malloc ( n * sizeof(double *) );
xb =  (double **) malloc ( n * sizeof(double *) );
Fi  = (double *) malloc ( n * sizeof(double) );
res = (double *) malloc ( n * sizeof(double) );
res_s = (double *) malloc ( n * sizeof(double) );
ww  = (double *) malloc ( n * sizeof(double) );
w   = (double *) malloc ( n * sizeof(double) );
x2 = (double **) malloc ( p * sizeof(double *) );
x3 = (double **) malloc ( p * sizeof(double *) );
x4 = (double **) malloc ( p * sizeof(double *) );
beta_aux = (double *) malloc( p * sizeof(double) );
beta_m = (double *) malloc( p * sizeof(double) );
beta_s = (double *) malloc( p * sizeof(double) );
for(i=0;i<n;i++) {
	x[i] =  (double*) malloc (p * sizeof(double) );
	xb[i] =  (double*) malloc ((p+1) * sizeof(double) );
	};
for(i=0;i<p;i++) {
	x2[i] = (double*) malloc (p * sizeof(double) );
	x3[i] = (double*) malloc (p * sizeof(double) );
	x4[i] = (double*) malloc (p * sizeof(double) );
};
/* copy X into x for easier handling */
for(i=0;i<n;i++)
        for(j=0;j<p;j++)
                x[i][j]=X[j*n+i];
/* calculate robust regression estimates */

for(i=0;i<m;i++)
	for(j=0;j<nboot;j++)
		boot_samp[i][j]=Boot_Samp[j*m+i]-1;

R_S_rlm(X, y, N, P, Nres, max_it, &scale, Beta_s, Beta_m,
		converged_mm, &seed, &c,
		Psi_c, groups, n_group, k_fast_s);

*Scale = scale;
/* get M-fitted values in Fi */
mat_vec(x,Beta_m,Fi,n,p);
/* get residuals of M-est in res */
dif_vec(y,Fi,res,n);
/* get S-fitted values in res_s */
mat_vec(x,Beta_s,res_s,n,p);
/* get residuals of S-est in res_s */
dif_vec(y,res_s,res_s,n);
/* set auxiliary matrices to zero */

initialize_mat(x3, p, p);
initialize_mat(x4, p, p);
initialize_vec(v, p);
u2 = 0.0;
/* calculate correction matrix */

for(i=0;i<n;i++) {
	u = res[i]/scale ;
	w[i]  = Psi_reg(u,Psi_constant)/res[i];
        matias_vec_vec(x2,x[i],x[i],p);
	scalar_mat(x2,Psi_reg_prime(u,Psi_constant),
                x2,p,p);
        sum_mat(x3,x2,x3,p,p);
        matias_vec_vec(x2,x[i],x[i],p);
        scalar_mat(x2,w[i],x2,p,p);
        sum_mat(x4,x2,x4,p,p);
	scalar_vec(x[i],Psi_reg_prime(u,Psi_constant)*u,v_aux,p);
	sum_vec(v,v_aux,v,p);
	u2 += Chi_prime(u, c) * u;
};

/* scalar_vec(v, .5 * (double) (n-p) * scale / u2 , v, p);  */
scalar_vec(v, .5 * (double) n * scale / u2 , v, p);
inverse(x3,x2,p);
mat_mat(x2,x4,x3,p,p,p);
mat_vec(x2,v,v2,p,p);
scalar_mat(x3,scale,x3,p,p);
/* the correction matrix is now in x3 */
/* the correction vector is now in v2 */

/* start the bootstrap replications */
for(i=0;i<m;i++) {
	/* change the seed! */
	++seed;
	// sampler_i(n,nboot,indices);
	// for(j=0;j<nboot; j++)
	// 	indices[j]=boot_samp[i][j];
	/* get pseudo observed y's */
	for(j=0;j<nboot;j++) /* xb[j][p] = */
			yb[j] = y[boot_samp[i][j]];
	for(j=0;j<nboot;j++)
		for(k=0;k<p;k++) {
			// xb[j][k] = x[boot_samp[i][j]][k];
			// Xb[k*nboot+j] = X[k*n + indices[j]];
			Xb[k*nboot+j] = x[boot_samp[i][j]][k];
			xb[j][k] = Xb[k*nboot+j];
		};

	/* calculate full bootstrap estimate */

	if( *calc_full == 1 )
	R_S_rlm(Xb,yb,&nboot,P,Nres,max_it,&dummyscale,
			beta_s,beta_m,converged_mm,&seed,&c,
			Psi_c, groups, n_group, k_fast_s);

/* void R_S_rlm(double *X, double *y, int *n, int *P,
		int *nres, int *max_it,
		double *SCale, double *beta_s, double *beta_m,
		int *converged_mm,
		int *seed_rand, double *C, double *Psi_c,
		int *Groups, int *N_group, int *K_fast_s) */

	/*	double *C, double *Psi_c, int *max_it,
		int *groups, int *n_group, int *k_fast_s); */

	// HERE

	/* disp_mat(xb, nboot,p); */
	// disp_vec(yb,nboot);
	// Rprintf("\nfull scale: %f", dummyscale);

	/* calculate robust bootsrap */

	scalar_vec(v,0.0,v,p);	 	/* v <- 0 */
	scalar_mat(x2,0.0,x2,p,p);	/* x2 <- 0 */
	s = 0.0;
	for(j=0;j<nboot;j++) {
		scalar_vec(xb[j],yb[j]*w[boot_samp[i][j]],v_aux,p);
		sum_vec(v,v_aux,v,p);
		matias_vec_vec(x4,xb[j],xb[j],p);
		scalar_mat(x4,w[boot_samp[i][j]],x4,p,p);
		sum_mat(x2,x4,x2,p,p);
		s += Chi(res_s[boot_samp[i][j]] / scale , c);
	};
	/* s = s * scale / .5 / (double) (nboot - p)  ;  */
	s = s * scale / .5 / (double) n;
	inverse(x2,x4,p);		/* x4 <- x2^-1 */
	mat_vec(x4,v,v_aux,p,p);	/* v_aux <- x4 * v */
	dif_vec(v_aux,Beta_m,v_aux,p); 	/* v_aux <- v_aux - beta_m */
	/* v has the robust bootstrapped vector, correct it */
	mat_vec(x3,v_aux,v,p,p);	/* v <- x3 * v_aux */
	scalar_vec(v2,s-scale,v_aux,p);
	sum_vec(v_aux,v,v,p);

	/* store the betas (splus-wise!) */
	for(j=0;j<p;j++) {
		ours[j*m+i]=v[j];
		if( *calc_full == 1 )
			// full[j*m+i]=beta_m[j]-Beta_m[j];
			full[j*m+i]=beta_m[j];
	};
};
for(i=0;i<m;i++)
	free(boot_samp[i]);
free(boot_samp);
for(i=0;i<n;i++) {
	free(x[i]);
	free(xb[i]);
	};
for(i=0;i<p;i++) {
	free(x2[i]);
	free(x3[i]);
	free(x4[i]);
	};
free(x) ;free(x2);free(xb);
free(x3);free(x4);
free(beta_aux);free(beta_m);free(beta_s);
free(w);free(ww);free(Fi);free(res);
free(v);free(v2);free(v_aux);free(yb);
free(res_s);
free(Xb);
return(0);
}