Esempio n. 1
0
void JMXStartRemoteDCmd::execute(DCmdSource source, TRAPS) {
    ResourceMark rm(THREAD);
    HandleMark hm(THREAD);

    // Load and initialize the sun.management.Agent class
    // invoke startRemoteManagementAgent(string) method to start
    // the remote management server.
    // throw java.lang.NoSuchMethodError if the method doesn't exist

    Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
    Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::sun_management_Agent(), loader, Handle(), true, CHECK);
    instanceKlassHandle ik (THREAD, k);

    JavaValue result(T_VOID);

    // Pass all command line arguments to java as key=value,...
    // All checks are done on java side

    int len = 0;
    stringStream options;
    char comma[2] = {0,0};

    // Leave default values on Agent.class side and pass only
    // agruments explicitly set by user. All arguments passed
    // to jcmd override properties with the same name set by
    // command line with -D or by managmenent.properties
    // file.
#define PUT_OPTION(a) \
    do { \
        if ( (a).is_set() ){ \
            if ( *((a).type()) == 'I' ) { \
                options.print("%scom.sun.management.%s=" JLONG_FORMAT, comma, (a).name(), (jlong)((a).value())); \
            } else { \
                options.print("%scom.sun.management.%s=%s", comma, (a).name(), (char*)((a).value())); \
            } \
            comma[0] = ','; \
        }\
    } while(0);


    PUT_OPTION(_config_file);
    PUT_OPTION(_jmxremote_host);
    PUT_OPTION(_jmxremote_port);
    PUT_OPTION(_jmxremote_rmi_port);
    PUT_OPTION(_jmxremote_ssl);
    PUT_OPTION(_jmxremote_registry_ssl);
    PUT_OPTION(_jmxremote_authenticate);
    PUT_OPTION(_jmxremote_password_file);
    PUT_OPTION(_jmxremote_access_file);
    PUT_OPTION(_jmxremote_login_config);
    PUT_OPTION(_jmxremote_ssl_enabled_cipher_suites);
    PUT_OPTION(_jmxremote_ssl_enabled_protocols);
    PUT_OPTION(_jmxremote_ssl_need_client_auth);
    PUT_OPTION(_jmxremote_ssl_config_file);
    PUT_OPTION(_jmxremote_autodiscovery);
    PUT_OPTION(_jdp_port);
    PUT_OPTION(_jdp_address);
    PUT_OPTION(_jdp_source_addr);
    PUT_OPTION(_jdp_ttl);
    PUT_OPTION(_jdp_pause);
    PUT_OPTION(_jdp_name);

#undef PUT_OPTION

    Handle str = java_lang_String::create_from_str(options.as_string(), CHECK);
    JavaCalls::call_static(&result, ik, vmSymbols::startRemoteAgent_name(), vmSymbols::string_void_signature(), str, CHECK);
}
Esempio n. 2
0
Handle Bytecode_invoke::appendix(TRAPS) {
  ConstantPoolCacheEntry* cpce = cpcache_entry();
  if (cpce->has_appendix())
    return Handle(THREAD, cpce->appendix_if_resolved(constants()));
  return Handle();  // usual case
}
Esempio n. 3
0
void Movie::HandlePadAndCircleStatus(Service::HID::PadState& pad_state, s16& circle_pad_x,
                                     s16& circle_pad_y) {
    Handle(pad_state, circle_pad_x, circle_pad_y);
}
Esempio n. 4
0
 const Session::Handle Session::proxy ( ::HINTERNET object )
 {
     return (Handle(object, &::abandon));
 }
Esempio n. 5
0
	myAISContext->NextCurrent())            
		myAISContext->SetDisplayMode(myAISContext->Current(), 0);	
		 
TCollection_AsciiString Message ("\
\n\
for (myAISContext->InitCurrent(); myAISContext->MoreCurrent ();  \n\
	myAISContext->NextCurrent ())	    \n\
	myAISContext->SetDisplayMode(myAISContext->Current(), 0);  \n\
\n");

	CString text(Message.ToCString());
	(*myCResultDialog).SetTitle(CString("Wireframe"));
	(*myCResultDialog).SetText(text);
}

void DlgAttributes::Set(Handle ( AIS_InteractiveContext ) & acontext, CResultDialog& aResultDialog)
{
	myAISContext = acontext;
	myCResultDialog=&aResultDialog;
}

void DlgAttributes::OnTransparency() 
{
/*
	for (myAISContext->InitCurrent(); myAISContext->MoreCurrent ();
		 myAISContext->NextCurrent ()) {
			
	
		int ival = (int) ((double) myAISContext->Current()->Transparency()*10.) ;
		double rval = ((double) ival)/10.;
		CDialogTransparency Dlg(NULL, rval);
		{
			/* Set a tab to be active and activate associated window
			(if one exists).*/
			VINT nOldTab = m_nActiveTab;

			/* Save cache of active tab.*/
			m_nActiveTab = nIndex;

			/* Make tab control same setting.*/
			Selection(m_nActiveTab);

			/* Show active tab window and set position.*/
			SetActiveChildPosition();

			/* Hide old window.*/
			HWND hWndOld = (nOldTab != -1) ? Handle(nOldTab) : NULL;

			if ( hWndOld && ::IsWindow(hWndOld) )
				::ShowWindow(hWndOld, SW_HIDE);
		}

		return Selection();
	}

	/** Add a tab and associated window. It is valid to use a temporary or
	non-initialized window here, as it can be set at a later time. Returns
	the index of the tab associated with the window, or -1 on failure. If
	nIndex is -1, the tab will be added to end of existing tabs.*/
	VINT			AddTab(	VSTRING_CONST	pszText,
							VWindow const&	window,
							VINT			nIndex = -1)
 *  destructor
 */
//=============================================================================
GEOMImpl_ILocalOperations::~GEOMImpl_ILocalOperations()
{
  //MESSAGE("GEOMImpl_ILocalOperations::~GEOMImpl_ILocalOperations");
}


//=============================================================================
/*!
 *  MakeFilletAll
 */
//=============================================================================
Handle(GEOM_Object) GEOMImpl_ILocalOperations::MakeFilletAll
									(Handle(GEOM_Object) theShape, const GEOM_Parameter& theR)
{
  SetErrorCode(GEOM_KO);

 #ifdef LOCAL_OPS_CREATE_NEW_OBJECT
  //Add a new Fillet object
  Handle(GEOM_Object) aFillet = GetEngine()->AddObject(GetDocID(), GEOM_FILLET);
 #else
  Handle(GEOM_Object) aFillet = theShape;
 #endif

  Handle(GEOM_Function) aRefShape = theShape->GetLastFunction();
  if (aRefShape.IsNull()) return NULL;

  //Add a new Fillet function
  Handle(GEOM_Function) aFunction =
//=======================================================================
//function : Execute
//purpose  :
//=======================================================================
Standard_Integer GEOMImpl_Fillet1dDriver::Execute(TFunction_Logbook& log) const
{
  if (Label().IsNull()) return 0;
  Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());

  GEOMImpl_IFillet1d aCI (aFunction);

  Handle(GEOM_Function) aRefShape = aCI.GetShape();
  TopoDS_Shape aShape = aRefShape->GetValue();
  if (aShape.IsNull())
    return 0;
  if (aShape.ShapeType() != TopAbs_WIRE)
    Standard_ConstructionError::Raise("Wrong arguments: polyline as wire must be given");

  TopoDS_Wire aWire = TopoDS::Wire(aShape);

  double rad = aCI.GetR();

  if ( rad < Precision::Confusion())
    return 0;

  // collect vertices for make fillet
  TopTools_ListOfShape aVertexList;
  TopTools_MapOfShape mapShape;
  int aLen = aCI.GetLength();
  if ( aLen > 0 ) {
    for (int ind = 1; ind <= aLen; ind++) {
      TopoDS_Shape aShapeVertex;
      if (GEOMImpl_ILocalOperations::GetSubShape
          (aWire, aCI.GetVertex(ind), aShapeVertex))
        if (mapShape.Add(aShapeVertex))
          aVertexList.Append( aShapeVertex );
    }
  } else { // get all vertices from wire
    TopExp_Explorer anExp( aWire, TopAbs_VERTEX );
    for ( ; anExp.More(); anExp.Next() ) {
      if (mapShape.Add(anExp.Current()))
        aVertexList.Append( anExp.Current() );
    }
  }
  if (aVertexList.IsEmpty())
    Standard_ConstructionError::Raise("Invalid input no vertices to make fillet");

  //INFO: this algorithm implemented in assumption that user can select both
  //  vertices of some edges to make fillet. In this case we should remember
  //  already modified initial edges to take care in next fillet step
  TopTools_DataMapOfShapeShape anEdgeToEdgeMap;

  //iterates on vertices, and make fillet on each couple of edges
  //collect result fillet edges in list
  TopTools_ListOfShape aListOfNewEdge;
  // remember relation between initial and modified map
  TopTools_IndexedDataMapOfShapeListOfShape aMapVToEdges;
  TopExp::MapShapesAndAncestors( aWire, TopAbs_VERTEX, TopAbs_EDGE, aMapVToEdges );
  TopTools_ListIteratorOfListOfShape anIt( aVertexList );
  for ( ; anIt.More(); anIt.Next() ) {
    TopoDS_Vertex aV = TopoDS::Vertex( anIt.Value() );
    if ( aV.IsNull() || !aMapVToEdges.Contains( aV ) )
      continue;
    const TopTools_ListOfShape& aVertexEdges = aMapVToEdges.FindFromKey( aV );
    if ( aVertexEdges.Extent() != 2 )
      continue; // no input data to make fillet
    TopoDS_Edge anEdge1 = TopoDS::Edge( aVertexEdges.First() );
    TopoDS_Edge anEdge2 = TopoDS::Edge( aVertexEdges.Last() );
    // check if initial edges already modified in previous fillet operation
    if ( anEdgeToEdgeMap.IsBound( anEdge1 ) ) anEdge1 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge1 ));
    if ( anEdgeToEdgeMap.IsBound( anEdge2 ) ) anEdge2 = TopoDS::Edge(anEdgeToEdgeMap.Find( anEdge2 ));
    if ( anEdge1.IsNull() || anEdge2.IsNull() || anEdge1.IsSame( anEdge2 ) )
      continue; //no input data to make fillet

    // create plane on 2 edges
    gp_Pln aPlane;
    if ( !takePlane(anEdge1, anEdge2, aV, aPlane) )
      continue; // seems edges does not belong to same plane or parallel (fillet can not be build)

    GEOMImpl_Fillet1d aFilletAlgo(anEdge1, anEdge2, aPlane);
    if ( !aFilletAlgo.Perform(rad) )
      continue; // can not create fillet with given radius

    // take fillet result in given vertex
    TopoDS_Edge aModifE1, aModifE2;
    TopoDS_Edge aNewE = aFilletAlgo.Result(BRep_Tool::Pnt(aV), aModifE1, aModifE2);
    if (aNewE.IsNull())
      continue; // no result found

    // add  new created edges and take modified edges
    aListOfNewEdge.Append( aNewE );

    // check if face edges modified,
    // if yes, than map to original edges (from vertex-edges list), because edges can be modified before
    if (aModifE1.IsNull() || !anEdge1.IsSame( aModifE1 ))
      addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.First()), aModifE1 );
    if (aModifE2.IsNull() || !anEdge2.IsSame( aModifE2 ))
      addEdgeRelation( anEdgeToEdgeMap, TopoDS::Edge(aVertexEdges.Last()), aModifE2 );
  }

  if ( anEdgeToEdgeMap.IsEmpty() && aListOfNewEdge.IsEmpty() ) {
    StdFail_NotDone::Raise("1D Fillet can't be computed on the given shape with the given radius");
    return 0;
  }

  // create new wire instead of original
  for ( TopExp_Explorer anExp( aWire, TopAbs_EDGE ); anExp.More(); anExp.Next() ) {
    TopoDS_Shape anEdge = anExp.Current();
    if ( !anEdgeToEdgeMap.IsBound( anEdge ) )
      aListOfNewEdge.Append( anEdge );
    else if (!anEdgeToEdgeMap.Find( anEdge ).IsNull())
      aListOfNewEdge.Append( anEdgeToEdgeMap.Find( anEdge ) );
  }

  GEOMImpl_IShapesOperations::SortShapes( aListOfNewEdge );

  BRepBuilderAPI_MakeWire aWireTool;
  aWireTool.Add( aListOfNewEdge );
  aWireTool.Build();
  if (!aWireTool.IsDone())
    return 0;

  aWire = aWireTool.Wire();
  aFunction->SetValue(aWire);
  log.SetTouched(Label());

  return 1;
}
instanceOop MemoryManager::get_memory_manager_instance(TRAPS) {
  // Must do an acquire so as to force ordering of subsequent
  // loads from anything _memory_mgr_obj points to or implies.
  instanceOop mgr_obj = (instanceOop)OrderAccess::load_ptr_acquire(&_memory_mgr_obj);
  if (mgr_obj == NULL) {
    // It's ok for more than one thread to execute the code up to the locked region.
    // Extra manager instances will just be gc'ed.
    klassOop k = Management::sun_management_ManagementFactory_klass(CHECK_0);
    instanceKlassHandle ik(THREAD, k);

    Handle mgr_name = java_lang_String::create_from_str(name(), CHECK_0);

    JavaValue result(T_OBJECT);
    JavaCallArguments args;
    args.push_oop(mgr_name);    // Argument 1

    Symbol* method_name = NULL;
    Symbol* signature = NULL;
    if (is_gc_memory_manager()) {
      method_name = vmSymbols::createGarbageCollector_name();
      signature = vmSymbols::createGarbageCollector_signature();
      args.push_oop(Handle());      // Argument 2 (for future extension)
    } else {
      method_name = vmSymbols::createMemoryManager_name();
      signature = vmSymbols::createMemoryManager_signature();
    }

    JavaCalls::call_static(&result,
                           ik,
                           method_name,
                           signature,
                           &args,
                           CHECK_0);

    instanceOop m = (instanceOop) result.get_jobject();
    instanceHandle mgr(THREAD, m);

    {
      // Get lock before setting _memory_mgr_obj
      // since another thread may have created the instance
      MutexLocker ml(Management_lock);

      // Check if another thread has created the management object.  We reload
      // _memory_mgr_obj here because some other thread may have initialized
      // it while we were executing the code before the lock.
      //
      // The lock has done an acquire, so the load can't float above it, but
      // we need to do a load_acquire as above.
      mgr_obj = (instanceOop)OrderAccess::load_ptr_acquire(&_memory_mgr_obj);
      if (mgr_obj != NULL) {
         return mgr_obj;
      }

      // Get the address of the object we created via call_special.
      mgr_obj = mgr();

      // Use store barrier to make sure the memory accesses associated
      // with creating the management object are visible before publishing
      // its address.  The unlock will publish the store to _memory_mgr_obj
      // because it does a release first.
      OrderAccess::release_store_ptr(&_memory_mgr_obj, mgr_obj);
    }
  }

  return mgr_obj;
}
Esempio n. 10
0
//=======================================================================
//function : Execute
//purpose  :
//=======================================================================
Standard_Integer GEOMImpl_ConeDriver::Execute(TFunction_Logbook& log) const
{
  if (Label().IsNull()) return 0;
  Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());

  GEOMImpl_ICone aCI (aFunction);
  Standard_Integer aType = aFunction->GetType();

  gp_Pnt aP;
  gp_Vec aV;

  Standard_Real aR1 = aCI.GetR1();
  Standard_Real aR2 = aCI.GetR2();

  if (aType == CONE_R1_R2_H) {
    aP = gp::Origin();
    aV = gp::DZ();

  } else if (aType == CONE_PNT_VEC_R1_R2_H) {
    Handle(GEOM_Function) aRefPoint  = aCI.GetPoint();
    Handle(GEOM_Function) aRefVector = aCI.GetVector();
    TopoDS_Shape aShapePnt = aRefPoint->GetValue();
    TopoDS_Shape aShapeVec = aRefVector->GetValue();
    if (aShapePnt.IsNull() || aShapeVec.IsNull()) {
      Standard_NullObject::Raise
        ("Cone creation aborted: point or vector is not defined");
    }
    if (aShapePnt.ShapeType() != TopAbs_VERTEX ||
        aShapeVec.ShapeType() != TopAbs_EDGE) {
      Standard_TypeMismatch::Raise
        ("Cone creation aborted: point or vector shapes has wrong type");
    }

    aP = BRep_Tool::Pnt(TopoDS::Vertex(aShapePnt));

    TopoDS_Edge anE = TopoDS::Edge(aShapeVec);
    TopoDS_Vertex V1, V2;
    TopExp::Vertices(anE, V1, V2, Standard_True);
    if (V1.IsNull() || V2.IsNull()) {
      Standard_NullObject::Raise
        ("Cylinder creation aborted: vector is not defined");
    }
    aV = gp_Vec(BRep_Tool::Pnt(V1), BRep_Tool::Pnt(V2));

  } else {
    return 0;
  }

  if (aCI.GetH() < 0.0) aV.Reverse();
  gp_Ax2 anAxes (aP, aV);

  double theAngle = aCI.GetAngle();
  if (theAngle == 0.)
	theAngle = PI*2.;

  TopoDS_Shape aShape;
  // Cone does not work if same radius
  if (fabs(aR1 - aR2) <= Precision::Confusion()) {
  
	BRepPrimAPI_MakeCylinder MC (anAxes, (aR1 + aR2)/2.0, Abs(aCI.GetH()), theAngle);

	MC.Build();
    if (!MC.IsDone()) {
      StdFail_NotDone::Raise("Cylinder can't be computed from the given parameters");
    }
    aShape = MC.Shape();
  } else {
    BRepPrimAPI_MakeCone MC (anAxes, aCI.GetR1(), aCI.GetR2(), Abs(aCI.GetH()), theAngle);
    MC.Build();
    if (!MC.IsDone()) {
      StdFail_NotDone::Raise("Cylinder can't be computed from the given parameters");
    }
    aShape = MC.Shape();
  }
  if (aShape.IsNull()) return 0;

  log.SetTouched(Label());

  aFunction->SetValue(aShape);
  return 1;
}
Esempio n. 11
0
    SALOME_WNT_EXPORT
    int Export( const TopoDS_Shape& theShape,
                const TCollection_AsciiString& theFileName,
                const TCollection_AsciiString& theFormatName)
    {
        MESSAGE("Export OBJ into file " << theFileName.ToCString());

        std::ofstream fout(theFileName.ToCString());

        Standard_Real Umin, Umax, Vmin, Vmax, dUmax, dVmax;
        TopExp_Explorer ExpFace;
        StdPrs_ToolShadedShape SST;

        //Triangulate
        BRepMesh::Mesh(theShape, DEFAULT_DEVIATION);

        Standard_Integer ShapeId = 1;

        Standard_Integer baseV = 0;
        Standard_Integer baseN = 0;
        Standard_Integer baseT = 0;

        for(ExpFace.Init(theShape, TopAbs_FACE); ExpFace.More(); ExpFace.Next()) {

            TopoDS_Face myFace = TopoDS::Face(ExpFace.Current());
            TopLoc_Location aLocation;

            Handle(Poly_Triangulation) myT = BRep_Tool::Triangulation(myFace, aLocation);

            if (!myT.IsNull()) {

                Poly_Connect pc(myT);

                //write vertex buffer
                const TColgp_Array1OfPnt& Nodes = myT->Nodes();
                for (int i = Nodes.Lower(); i <= Nodes.Upper(); i++) {
                    gp_Pnt p = Nodes(i).Transformed(aLocation.Transformation());
                    fout << "v " << p.X() << " " << p.Y() << " " << p.Z() << std::endl;
                }
                fout << std::endl;

                //write normal buffer
                TColgp_Array1OfDir myNormal(Nodes.Lower(), Nodes.Upper());
                SST.Normal(myFace, pc, myNormal);
                //myNormal.Length();
                for (int i = myNormal.Lower(); i <= myNormal.Upper(); i++) {
                    gp_Dir d = myNormal(i).Transformed(aLocation.Transformation());
                    fout << "vn " << d.X() << " " << d.Y() << " " << d.Z() << std::endl;
                }
                fout << std::endl;

                //write uvcoord buffer
                BRepTools::UVBounds(myFace,Umin, Umax, Vmin, Vmax);
                dUmax = (Umax - Umin);
                dVmax = (Vmax - Vmin);
                const TColgp_Array1OfPnt2d& UVNodes = myT->UVNodes();
                for (int i = UVNodes.Lower(); i <= UVNodes.Upper(); i++) {
                    gp_Pnt2d d = UVNodes(i);

                    Standard_Real u = (-UOrigin+(URepeat*(d.X()-Umin))/dUmax)/ScaleU;
                    Standard_Real v = (-VOrigin+(VRepeat*(d.Y()-Vmin))/dVmax)/ScaleV;

                    fout << "vt " << u << " " << v << " 0" << std::endl;
                }
                fout << std::endl;

                //write triangle buffer
                if (Interface_Static::IVal("write.obj.groups"))
                    fout << "g face_" << ShapeId++ << std::endl;

                Standard_Integer n1 , n2 , n3;
                const Poly_Array1OfTriangle& triangles = myT->Triangles();

                for (int nt = 1; nt <= myT->NbTriangles(); nt++) {
                    if (SST.Orientation(myFace) == TopAbs_REVERSED)
                        triangles(nt).Get(n1,n3,n2);
                    else
                        triangles(nt).Get(n1,n2,n3);
                    if (TriangleIsValid (Nodes(n1),Nodes(n2),Nodes(n3)) ) {

                        fout << "f " <<n1 + baseV<<"/"<<n1 + baseT<<"/"<<n1 + baseN<<" "
                             <<n2 + baseV<<"/"<<n2 + baseT<<"/"<<n2 + baseN<<" "
                             <<n3 + baseV<<"/"<<n3 + baseT<<"/"<<n3 + baseN<<" "
                             <<std::endl;
                    }
                }
                fout << std::endl;

                baseV += Nodes.Length();
                baseN += myNormal.Length();
                baseT += UVNodes.Length();
            }
        }

        fout << std::flush;
        fout.close();

        return 1;
    }
Esempio n. 12
0
jvmtiError
JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
  HandleMark hm;
  Handle hobj;

  bool at_safepoint = SafepointSynchronize::is_at_safepoint();

  // Check arguments
  {
    oop mirror = JNIHandles::resolve_external_guard(object);
    NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
    NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);

    hobj = Handle(mirror);
  }

  JavaThread *owning_thread = NULL;
  ObjectMonitor *mon = NULL;
  jvmtiMonitorUsage ret = {
      NULL, 0, 0, NULL, 0, NULL
  };

  uint32_t debug_bits = 0;
  // first derive the object's owner and entry_count (if any)
  {
    // Revoke any biases before querying the mark word
    if (SafepointSynchronize::is_at_safepoint()) {
      BiasedLocking::revoke_at_safepoint(hobj);
    } else {
      BiasedLocking::revoke_and_rebias(hobj, false, calling_thread);
    }

    address owner = NULL;
    {
      markOop mark = hobj()->mark();

      if (!mark->has_monitor()) {
        // this object has a lightweight monitor

        if (mark->has_locker()) {
          owner = (address)mark->locker(); // save the address of the Lock word
        }
        // implied else: no owner
      } else {
        // this object has a heavyweight monitor
        mon = mark->monitor();

        // The owner field of a heavyweight monitor may be NULL for no
        // owner, a JavaThread * or it may still be the address of the
        // Lock word in a JavaThread's stack. A monitor can be inflated
        // by a non-owning JavaThread, but only the owning JavaThread
        // can change the owner field from the Lock word to the
        // JavaThread * and it may not have done that yet.
        owner = (address)mon->owner();
      }
    }

    if (owner != NULL) {
      // This monitor is owned so we have to find the owning JavaThread.
      // Since owning_thread_from_monitor_owner() grabs a lock, GC can
      // move our object at this point. However, our owner value is safe
      // since it is either the Lock word on a stack or a JavaThread *.
      owning_thread = Threads::owning_thread_from_monitor_owner(owner, !at_safepoint);
      assert(owning_thread != NULL, "sanity check");
      if (owning_thread != NULL) {  // robustness
        // The monitor's owner either has to be the current thread, at safepoint
        // or it has to be suspended. Any of these conditions will prevent both
        // contending and waiting threads from modifying the state of
        // the monitor.
        if (!at_safepoint && !JvmtiEnv::is_thread_fully_suspended(owning_thread, true, &debug_bits)) {
          return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
        }
        HandleMark hm;
        Handle     th(owning_thread->threadObj());
        ret.owner = (jthread)jni_reference(calling_thread, th);
      }
      // implied else: no owner
    }

    if (owning_thread != NULL) {  // monitor is owned
      if ((address)owning_thread == owner) {
        // the owner field is the JavaThread *
        assert(mon != NULL,
          "must have heavyweight monitor with JavaThread * owner");
        ret.entry_count = mon->recursions() + 1;
      } else {
        // The owner field is the Lock word on the JavaThread's stack
        // so the recursions field is not valid. We have to count the
        // number of recursive monitor entries the hard way. We pass
        // a handle to survive any GCs along the way.
        ResourceMark rm;
        ret.entry_count = count_locked_objects(owning_thread, hobj);
      }
    }
    // implied else: entry_count == 0
  }

  int nWant,nWait;
  if (mon != NULL) {
    // this object has a heavyweight monitor
    nWant = mon->contentions(); // # of threads contending for monitor
    nWait = mon->waiters();     // # of threads in Object.wait()
    ret.waiter_count = nWant + nWait;
    ret.notify_waiter_count = nWait;
  } else {
    // this object has a lightweight monitor
    ret.waiter_count = 0;
    ret.notify_waiter_count = 0;
  }

  // Allocate memory for heavyweight and lightweight monitor.
  jvmtiError err;
  err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
  if (err != JVMTI_ERROR_NONE) {
    return err;
  }
  err = allocate(ret.notify_waiter_count * sizeof(jthread *),
                 (unsigned char**)&ret.notify_waiters);
  if (err != JVMTI_ERROR_NONE) {
    deallocate((unsigned char*)ret.waiters);
    return err;
  }

  // now derive the rest of the fields
  if (mon != NULL) {
    // this object has a heavyweight monitor

    // Number of waiters may actually be less than the waiter count.
    // So NULL out memory so that unused memory will be NULL.
    memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
    memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));

    if (ret.waiter_count > 0) {
      // we have contending and/or waiting threads
      HandleMark hm;
      if (nWant > 0) {
        // we have contending threads
        ResourceMark rm;
        // get_pending_threads returns only java thread so we do not need to
        // check for  non java threads.
        GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(
          nWant, (address)mon, !at_safepoint);
        if (wantList->length() < nWant) {
          // robustness: the pending list has gotten smaller
          nWant = wantList->length();
        }
        for (int i = 0; i < nWant; i++) {
          JavaThread *pending_thread = wantList->at(i);
          // If the monitor has no owner, then a non-suspended contending
          // thread could potentially change the state of the monitor by
          // entering it. The JVM/TI spec doesn't allow this.
          if (owning_thread == NULL && !at_safepoint &
              !JvmtiEnv::is_thread_fully_suspended(pending_thread, true, &debug_bits)) {
            if (ret.owner != NULL) {
              destroy_jni_reference(calling_thread, ret.owner);
            }
            for (int j = 0; j < i; j++) {
              destroy_jni_reference(calling_thread, ret.waiters[j]);
            }
            deallocate((unsigned char*)ret.waiters);
            deallocate((unsigned char*)ret.notify_waiters);
            return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
          }
          Handle th(pending_thread->threadObj());
          ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
        }
      }
      if (nWait > 0) {
        // we have threads in Object.wait()
        int offset = nWant;  // add after any contending threads
        ObjectWaiter *waiter = mon->first_waiter();
        for (int i = 0, j = 0; i < nWait; i++) {
          if (waiter == NULL) {
            // robustness: the waiting list has gotten smaller
            nWait = j;
            break;
          }
          Thread *t = mon->thread_of_waiter(waiter);
          if (t != NULL && t->is_Java_thread()) {
            JavaThread *wjava_thread = (JavaThread *)t;
            // If the thread was found on the ObjectWaiter list, then
            // it has not been notified. This thread can't change the
            // state of the monitor so it doesn't need to be suspended.
            Handle th(wjava_thread->threadObj());
            ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
            ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
          }
          waiter = mon->next_waiter(waiter);
        }
      }
    }

    // Adjust count. nWant and nWait count values may be less than original.
    ret.waiter_count = nWant + nWait;
    ret.notify_waiter_count = nWait;
  } else {
    // this object has a lightweight monitor and we have nothing more
    // to do here because the defaults are just fine.
  }

  // we don't update return parameter unless everything worked
  *info_ptr = ret;

  return JVMTI_ERROR_NONE;
}
Esempio n. 13
0
void CConsoleWindow::HandleMouseEvent(UINT aMessage, WPARAM aWParam, LPARAM aLParam)
	{
	if (!iNoSelection)
		{
		switch(aMessage)
			{
			case WM_LBUTTONDOWN:
				{
				SetCapture(Handle());
				iView->StartSelection(GET_X_LPARAM(aLParam), GET_Y_LPARAM(aLParam));
				break;
				}
			case WM_LBUTTONDBLCLK:
				{
				iView->SelectWord(GET_X_LPARAM(aLParam), GET_Y_LPARAM(aLParam));
				break;
				}
			case WM_MOUSEMOVE:
				{
				RECT clientRect;
				GetClientRect(Handle(), &clientRect);
				POINT mousePos = { GET_X_LPARAM(aLParam), GET_Y_LPARAM(aLParam) };
				if ((mousePos.x > clientRect.right) || (mousePos.x < clientRect.left))
					{
					SCROLLINFO scrollInfo;
					scrollInfo.cbSize = sizeof(scrollInfo);
					scrollInfo.fMask = SIF_POS;
					GetScrollInfo(Handle(), SB_HORZ, &scrollInfo);
					if (mousePos.x > clientRect.right)
						{
						scrollInfo.nPos += iView->CharWidth();
						}
					else
						{
						scrollInfo.nPos -= iView->CharWidth();
						}
					SetScrollInfo (Handle(), SB_HORZ, &scrollInfo, TRUE);
					GetScrollInfo (Handle(), SB_HORZ, &scrollInfo);
					iView->SetHorzScrollPosition(scrollInfo.nPos);
					}
				if ((mousePos.y < clientRect.top) || (mousePos.y > clientRect.bottom))
					{
					SCROLLINFO scrollInfo;
					scrollInfo.cbSize = sizeof(scrollInfo);
					scrollInfo.fMask = SIF_POS;
					GetScrollInfo(Handle(), SB_VERT, &scrollInfo);
					if (mousePos.y < clientRect.top)
						{
						scrollInfo.nPos -= iView->CharHeight();
						}
					else
						{
						scrollInfo.nPos += iView->CharHeight();
						}
					SetScrollInfo (Handle(), SB_VERT, &scrollInfo, TRUE);
					GetScrollInfo (Handle(), SB_VERT, &scrollInfo);
					iView->SetVertScrollPosition(scrollInfo.nPos);
					}

				iView->AdjustSelection(GET_X_LPARAM(aLParam), GET_Y_LPARAM(aLParam));
				break;
				}
			case WM_LBUTTONUP:
				{
				ReleaseCapture();
				iView->EndSelection(GET_X_LPARAM(aLParam), GET_Y_LPARAM(aLParam));
				break;
				}
			default:
				{
				break;
				}
			}
		}
	}
Esempio n. 14
0
//=======================================================================
//function : Execute
//purpose  :
//======================================================================= 
Standard_Integer GEOMImpl_PlateDriver::Execute(TFunction_Logbook& log) const
{
	if (Label().IsNull()) return 0;
	Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
	if(aFunction.IsNull()) return 0;

	GEOMImpl_IPlate aPI (aFunction);
	Standard_Integer aType = aFunction->GetType();

	TopoDS_Shape aShape;

	if (aType == PLATE_BY_SHAPES_LIST) {
		int ind, aLen = aPI.GetLength();

		if (aLen < 1)
			return 0;

		GeomPlate_BuildPlateSurface aPlate;
		Handle(GeomPlate_Surface) myPlateSurf;

		Handle(GEOM_Function) aRefInitialShape = aPI.GetInitialShape();
		if (!aRefInitialShape.IsNull()) {
			TopoDS_Shape anInitialShape = aRefInitialShape->GetValue();
			if (!anInitialShape.IsNull() && anInitialShape.ShapeType() == TopAbs_FACE)
			{
				aPlate.LoadInitSurface(BRep_Tool::Surface(TopoDS::Face(anInitialShape)));

				TopExp_Explorer exp (anInitialShape, TopAbs_EDGE); //in case we have an init surface we must pass all of it's edges as constrains
				for (; exp.More(); exp.Next()) {                   //otherwise exception is risen from the plate driver
					BRepAdaptor_Curve aCurve(TopoDS::Edge(exp.Current()));
					Handle(BRepAdaptor_HCurve) aHCurve = new BRepAdaptor_HCurve(aCurve);
					Handle(GeomPlate_CurveConstraint) aCrvConstr = new GeomPlate_CurveConstraint(aHCurve, DEFAULT_CONTINUITY);
					aPlate.Add(aCrvConstr);
				}
			}
		}

		for (ind = 1; ind <= aLen; ind++) {
			Handle(GEOM_Function) aRefShape = aPI.GetShape(ind);
			TopoDS_Shape aShape = aRefShape->GetValue();
			if (aShape.ShapeType() == TopAbs_VERTEX) { //case a simple point
				gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
				Handle(GeomPlate_PointConstraint) aPntConstr = new GeomPlate_PointConstraint(aP, DEFAULT_CONTINUITY);
				aPlate.Add(aPntConstr);
			}
			else {
				TopExp_Explorer exp (aShape, TopAbs_EDGE); //this case treats all cases where edges can be found
				Standard_Boolean hasEdge = Standard_False;
				for (; exp.More(); exp.Next()) {
					BRepAdaptor_Curve aCurve(TopoDS::Edge(exp.Current()));
					Handle(BRepAdaptor_HCurve) aHCurve = new BRepAdaptor_HCurve(aCurve);
					Handle(GeomPlate_CurveConstraint) aCrvConstr = new GeomPlate_CurveConstraint(aHCurve, DEFAULT_CONTINUITY);
					aPlate.Add(aCrvConstr);
					hasEdge = Standard_True;
				}
				if (!hasEdge) { //this case treats a compound of points
					exp.Init(aShape, TopAbs_VERTEX);
					for (; exp.More(); exp.Next()) {
						gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()));
						Handle(GeomPlate_PointConstraint) aPntConstr = new GeomPlate_PointConstraint(aP, DEFAULT_CONTINUITY);
						aPlate.Add(aPntConstr);
					}
				}
			}
		}
		aPlate.Perform();
		if (!aPlate.IsDone())
			Standard_ConstructionError::Raise("Plate surface cannot be created using the specific shapes !");
		else
			myPlateSurf = aPlate.Surface();
		GeomPlate_MakeApprox aMKS( myPlateSurf, Precision::Approximation(), DEFAULT_Nbmax, DEFAULT_dgmax, DEFAULT_dmax);
		BRepBuilderAPI_MakeFace MK (aMKS.Surface());
		MK.Build();
		if (!MK.IsDone())
			Standard_ConstructionError::Raise("Plate topology cannot be created !");
		else {
			aShape = MK.Shape();
			BRepCheck_Analyzer ana (aShape, false);
			if (!ana.IsValid()) {
			  Standard_CString anErrStr("Plate algorithm has produced an invalid shape result");
			  #ifdef THROW_ON_INVALID_SH
				Standard_ConstructionError::Raise(anErrStr);
			  #else
				MESSAGE(anErrStr);
				//further processing can be performed here
				//...
				//in case of failure of automatic treatment
				//mark the corresponding GEOM_Object as problematic
				TDF_Label aLabel = aFunction->GetOwnerEntry();
				if (!aLabel.IsRoot()) {
				  Handle(GEOM_Object) aMainObj = GEOM_Object::GetObject(aLabel);
				  if (!aMainObj.IsNull())
				    aMainObj->SetDirty(Standard_True);
				}
			  #endif
			}
		}
	}
	if (aShape.IsNull()) return 0;
	aFunction->SetValue(aShape);
	log.SetTouched(Label());
	return 1;
}
Esempio n. 15
0
void GWindow::Pour()
{
	bool SafeToLock = false;

	if (Wnd->IsLocked())
	{
		// I'm already locked... this could be bad if it's not me
		thread_id Thread = WindowHandle()->LockingThread();
		if (Thread != -1)
		{
			if (Thread == find_thread(NULL))
			{
				// it's all ok, I'm locking me
				SafeToLock = true;
			}
			else
			{
				// someone else is locking us
				// ok who is locking me?
				thread_info Info;
				if (get_thread_info(Thread, &Info) == B_OK)
				{
					printf("Evil locking thread: %i (%s)\n", Thread, Info.name);
				}
				else
				{
					printf("Couldn't get evil thread info\n");
				}
			}
		}
	}
	else
	{
		SafeToLock = true;
	}
	
	if (!SafeToLock)
	{
		printf("%s:%i - Not safe to lock for ::Pour.\n", __FILE__, __LINE__);
		return;
	}
	
	bool Lock = Wnd->Lock();
	Wnd->BeginViewTransaction();
	GRect r(Handle()->Frame());
	r.Offset(-r.x1, -r.y1);

	GRegion Client(r);
	GRegion Update;

	if (Menu)
	{
		GRect Mp = Menu->GetPos();
		Mp.x2 = 10000;
		Client.Subtract(&Mp);
	}

	for (GViewI *w = Children.First(); w; w = Children.Next())
	{
		GRect OldPos = w->GetPos();
		Update.Union(&OldPos);

		if (w->Pour(Client))
		{
			if (!w->Visible())
			{
				w->Visible(true);
			}

			Client.Subtract(&w->GetPos());
			Update.Subtract(&w->GetPos());
		}
		else
		{
			// non-pourable
		}
	}

	Wnd->EndViewTransaction();
	Wnd->Sync();

	// Handle()->Invalidate();
	if (Lock) Wnd->Unlock();
}
  STEPIMPORT_EXPORT
  TopoDS_Shape ImportSTEP (const TCollection_AsciiString& theFileName,
                       const TCollection_AsciiString& /*theFormatName*/,
                       TCollection_AsciiString&       theError,
                       const TDF_Label&               theShapeLabel)
  {
    MESSAGE("Import STEP model from file " << theFileName.ToCString());
    // Set "C" numeric locale to save numbers correctly
    //Kernel_Utils::Localizer loc;
    TopoDS_Shape aResShape;
    //VRV: OCC 4.0 migration
    STEPControl_Reader aReader;
    //VSR: 16/09/09: Convert to METERS
    Interface_Static::SetCVal("xstep.cascade.unit","M");
    Interface_Static::SetIVal("read.step.ideas", 1);
    Interface_Static::SetIVal("read.step.nonmanifold", 1);
    //VRV: OCC 4.0 migration
    TopoDS_Compound compound;
    BRep_Builder B;
    B.MakeCompound(compound);
    try {
#if OCC_VERSION_LARGE > 0x06010000
      OCC_CATCH_SIGNALS;
#endif
      IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());

      if (status == IFSelect_RetDone) {
        Standard_Boolean failsonly = Standard_False;
        aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
        /* Root transfers */
        Standard_Integer nbr = aReader.NbRootsForTransfer();
        aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity);

        for (Standard_Integer n = 1; n <= nbr; n++) {
          Standard_Boolean ok = aReader.TransferRoot(n);
          /* Collecting resulting entities */
          Standard_Integer nbs = aReader.NbShapes();
          if (!ok || nbs == 0)
          {
            // THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
            continue; // skip empty root
          }
          /* For a single entity */
          else if (nbr == 1 && nbs == 1) {
            aResShape = aReader.Shape(1);
            // ATTENTION: this is a workaround for mantis issue 0020442 remark 0010776
            // It should be removed after patching OCCT for bug OCC22436
            // (fix for OCCT is expected in service pack next to OCCT6.3sp12)
            if (aResShape.ShapeType() == TopAbs_COMPOUND) {
              int nbSub1 = 0;
              TopoDS_Shape currShape;
              TopoDS_Iterator It (aResShape, Standard_True, Standard_True);
              for (; It.More(); It.Next()) {
                nbSub1++;
                currShape = It.Value();
              }
              if (nbSub1 == 1)
                aResShape = currShape;
            }
            // END workaround
            break;
          }

          for (Standard_Integer i = 1; i <= nbs; i++) {
            TopoDS_Shape aShape = aReader.Shape(i);
            if (aShape.IsNull()) {
              // THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;
              //return aResShape;
              continue;
            }
            else {
              B.Add(compound, aShape);
            }
          }
        }
        if (aResShape.IsNull())
          aResShape = compound;

        // BEGIN: Store names of sub-shapes from file
        TopTools_IndexedMapOfShape anIndices;
        TopExp::MapShapes(aResShape, anIndices);

        Handle(Interface_InterfaceModel) Model = aReader.WS()->Model();
        Handle(XSControl_TransferReader) TR = aReader.WS()->TransferReader();
        if (!TR.IsNull()) {
          Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
          Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
          Handle(Standard_Type) tShape  = STANDARD_TYPE(StepShape_TopologicalRepresentationItem);
          Handle(Standard_Type) tGeom  = STANDARD_TYPE(StepGeom_GeometricRepresentationItem);

          Standard_Integer nb = Model->NbEntities();
          for (Standard_Integer ie = 1; ie <= nb; ie++) {
            Handle(Standard_Transient) enti = Model->Value(ie);
            Handle(TCollection_HAsciiString) aName;
            if ( enti->IsKind( tShape ) || enti->IsKind(tGeom))
            {
              aName = Handle(StepRepr_RepresentationItem)::DownCast(enti)->Name();
            }
            else if (enti->DynamicType() == tPD)
            {
              Handle(StepBasic_ProductDefinition) PD =
                Handle(StepBasic_ProductDefinition)::DownCast(enti);
              if (PD.IsNull()) continue;

              Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
              aName = Prod->Name();
            }
            else
            {
              continue;
            }
            if ( aName->UsefullLength() < 1 )
              continue;
            // skip 'N0NE' name
            if ( aName->UsefullLength() == 4 &&
                 toupper (aName->Value(1)) == 'N' &&
                 toupper (aName->Value(2)) == 'O' &&
                 toupper (aName->Value(3)) == 'N' &&
                 toupper (aName->Value(4)) == 'E')
              continue;

            // special check to pass names like "Open CASCADE STEP translator 6.3 1"
            TCollection_AsciiString aSkipName ("Open CASCADE STEP translator");
            if (aName->Length() >= aSkipName.Length()) {
              if (aName->String().SubString(1, aSkipName.Length()).IsEqual(aSkipName))
                continue;
            }
            TCollection_ExtendedString aNameExt (aName->ToCString());

            // find target shape
            Handle(Transfer_Binder) binder = TP->Find(enti);
            if (binder.IsNull()) continue;
            TopoDS_Shape S = TransferBRep::ShapeResult(binder);
            if (S.IsNull()) continue;

            // as PRODUCT can be included in the main shape
            // several times, we look here for all iclusions.
            Standard_Integer isub, nbSubs = anIndices.Extent();
            for (isub = 1; isub <= nbSubs; isub++)
            {
              TopoDS_Shape aSub = anIndices.FindKey(isub);
              if (aSub.IsPartner(S)) {
                TDF_Label L;
                if (enti->IsKind(tGeom)) {
                  // check all named shapes using iterator
                  TDF_ChildIDIterator anIt (theShapeLabel, TDataStd_Name::GetID(), Standard_True);
                  for (; anIt.More(); anIt.Next()) {
                    Handle(TDataStd_Name) nameAttr =
                      Handle(TDataStd_Name)::DownCast(anIt.Value());
                    if (nameAttr.IsNull()) continue;
                    TDF_Label Lab = nameAttr->Label();
                    Handle(TNaming_NamedShape) shAttr; 
                    if (Lab.FindAttribute(TNaming_NamedShape::GetID(), shAttr) && shAttr->Get().IsEqual(aSub))
                      L = Lab;
                  }
                }
                // create label and set shape
                if (L.IsNull())
                {
                  TDF_TagSource aTag;
                  L = aTag.NewChild(theShapeLabel);
                  TNaming_Builder tnBuild (L);
                  //tnBuild.Generated(S);
                  tnBuild.Generated(aSub);
                }
                // set a name
                TDataStd_Name::Set(L, aNameExt);
              }
            }
          }
        }
        // END: Store names
      }
      else {
//        switch (status) {
//        case IFSelect_RetVoid:
//          theError = "Nothing created or No data to process";
//          break;
//        case IFSelect_RetError:
//          theError = "Error in command or input data";
//          break;
//        case IFSelect_RetFail:
//          theError = "Execution was run, but has failed";
//          break;
//        case IFSelect_RetStop:
//          theError = "Execution has been stopped. Quite possible, an exception was raised";
//          break;
//        default:
//          break;
//        }
        theError = "Wrong format of the imported file. Can't import file.";
        aResShape.Nullify();
      }
    }
    catch (Standard_Failure) {
      Handle(Standard_Failure) aFail = Standard_Failure::Caught();
      theError = aFail->GetMessageString();
      aResShape.Nullify();
    }
    // Return previous locale
    return aResShape;
  }
Esempio n. 17
0
 void                        set_value(oop value)      { _value = Handle(value); }
//=======================================================================
//function : GlueEdgesWithPCurves
//purpose  : Glues the pcurves of the sequence of edges
//           and glues their 3d curves
//=======================================================================
static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
                                        const TopoDS_Vertex& FirstVertex,
                                        const TopoDS_Vertex& LastVertex)
{
  Standard_Integer i, j;

  TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
  //TColGeom2d_SequenceOfCurve PCurveSeq;
  TColGeom_SequenceOfSurface SurfSeq;
  //TopTools_SequenceOfShape LocSeq;
  
  BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
  for (; itr.More(); itr.Next())
  {
    Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
    if (CurveRep->IsCurveOnSurface())
    {
      //PCurveSeq.Append(CurveRep->PCurve());
      SurfSeq.Append(CurveRep->Surface());
      /*
      TopoDS_Shape aLocShape;
      aLocShape.Location(CurveRep->Location());
      LocSeq.Append(aLocShape);
      */
    }
  }

  Standard_Real fpar, lpar;
  BRep_Tool::Range(FirstEdge, fpar, lpar);
  TopoDS_Edge PrevEdge = FirstEdge;
  TopoDS_Vertex CV;
  Standard_Real MaxTol = 0.;
  
  TopoDS_Edge ResEdge;
  BRep_Builder BB;

  Standard_Integer nb_curve = aChain.Length();   //number of curves
  TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1);                    //array of the curves
  TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
    
  TopoDS_Vertex PrevVertex = FirstVertex;
  for (i = 1; i <= nb_curve; i++)
  {
    TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
    TopoDS_Vertex VF, VL;
    TopExp::Vertices(anEdge, VF, VL);
    Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
    
    Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
    Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
    if (Tol1 > MaxTol)
      MaxTol = Tol1;
    if (Tol2 > MaxTol)
      MaxTol = Tol2;
    
    if (i > 1)
    {
      TopExp::CommonVertex(PrevEdge, anEdge, CV);
      Standard_Real Tol = BRep_Tool::Tolerance(CV);
      tabtolvertex(i-2) = Tol;
    }
    
    Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
    Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
    tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
    GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
    if (ToReverse)
      tab_c3d(i-1)->Reverse();
    PrevVertex = (ToReverse)? VF : VL;
    PrevEdge = anEdge;
  }
  Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
  Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
  GeomConvert::ConcatC1(tab_c3d,
                        tabtolvertex,
                        ArrayOfIndices,
                        concatcurve,
                        Standard_False,
                        Precision::Confusion());   //C1 concatenation
  
  if (concatcurve->Length() > 1)
  {
    GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
    
    for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
      Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
    
    concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
  }
  Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
  
  TColGeom2d_SequenceOfBoundedCurve ResPCurves;
  TopLoc_Location aLoc;
  for (j = 1; j <= SurfSeq.Length(); j++)
  {
    TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
    
    PrevVertex = FirstVertex;
    PrevEdge = FirstEdge;
    //TopLoc_Location theLoc = LocSeq(j).Location();
    for (i = 1; i <= nb_curve; i++)
    {
      TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
      TopoDS_Vertex VF, VL;
      TopExp::Vertices(anEdge, VF, VL);
      Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));

      /*
      Handle(Geom2d_Curve) aPCurve =
        BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
      */
      Handle(Geom2d_Curve) aPCurve =
        BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
      Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
      tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
      Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
      if (ToReverse)
        tab_c2d(i-1)->Reverse();
      PrevVertex = (ToReverse)? VF : VL;
      PrevEdge = anEdge;
    }
    Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
    Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
    Geom2dConvert::ConcatC1(tab_c2d,
                            tabtolvertex,
                            ArrayOfInd2d,
                            concatc2d,
                            Standard_False,
                            Precision::Confusion());   //C1 concatenation
    
    if (concatc2d->Length() > 1)
    {
      Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
      
      for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
        Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
      
      concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
    }
    Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
    ResPCurves.Append(aResPCurve);
  }
  
  ResEdge = BRepLib_MakeEdge(ResCurve,
                             FirstVertex, LastVertex,
                             ResCurve->FirstParameter(), ResCurve->LastParameter());
  BB.SameRange(ResEdge, Standard_False);
  BB.SameParameter(ResEdge, Standard_False);
  for (j = 1; j <= ResPCurves.Length(); j++)
  {
    BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
    BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
  }

  BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
  
  return ResEdge;
}
Esempio n. 19
0
void ReadWholeRequest::operator()(boost::system::error_code const& errc)
{
    cb(Handle(this), errc);
}
//=======================================================================
//function : MergeEdges
//purpose  : auxilary
//=======================================================================
static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
                                   const TopoDS_Face& aFace,
                                   const Standard_Real Tol,
                                   TopoDS_Edge& anEdge)
{
  // make chain for union
  BRep_Builder B;
  ShapeAnalysis_Edge sae;
  TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
  TopoDS_Edge LastE = FirstE;
  TopoDS_Vertex VF = sae.FirstVertex(FirstE);
  TopoDS_Vertex VL = sae.LastVertex(LastE);
  TopTools_SequenceOfShape aChain;
  aChain.Append(FirstE);
  TColStd_MapOfInteger IndUsedEdges;
  IndUsedEdges.Add(1);
  Standard_Integer j;
  for(j=2; j<=SeqEdges.Length(); j++) {
    for(Standard_Integer k=2; k<=SeqEdges.Length(); k++) {
      if(IndUsedEdges.Contains(k)) continue;
      TopoDS_Edge edge = TopoDS::Edge(SeqEdges.Value(k));
      TopoDS_Vertex VF2 = sae.FirstVertex(edge);
      TopoDS_Vertex VL2 = sae.LastVertex(edge);
      if(sae.FirstVertex(edge).IsSame(VL)) {
        aChain.Append(edge);
        LastE = edge;
        VL = sae.LastVertex(LastE);
        IndUsedEdges.Add(k);
      }
      else if(sae.LastVertex(edge).IsSame(VF)) {
        aChain.Prepend(edge);
        FirstE = edge;
        VF = sae.FirstVertex(FirstE);
        IndUsedEdges.Add(k);
      }
    }
  }
  if(aChain.Length()<SeqEdges.Length()) {
    MESSAGE ("can not create correct chain...");
    return Standard_False;
  }
  // union edges in chain
  // first step: union lines and circles
  TopLoc_Location Loc;
  Standard_Real fp1,lp1,fp2,lp2;
  for(j=1; j<aChain.Length(); j++) {
    TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
    Handle(Geom_Curve) c3d1 = BRep_Tool::Curve(edge1,Loc,fp1,lp1);
    if(c3d1.IsNull()) break;
    while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
      Handle(Geom_TrimmedCurve) tc =
        Handle(Geom_TrimmedCurve)::DownCast(c3d1);
      c3d1 = tc->BasisCurve();
    }
    TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
    Handle(Geom_Curve) c3d2 = BRep_Tool::Curve(edge2,Loc,fp2,lp2);
    if(c3d2.IsNull()) break;
    while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
      Handle(Geom_TrimmedCurve) tc =
        Handle(Geom_TrimmedCurve)::DownCast(c3d2);
      c3d2 = tc->BasisCurve();
    }
    if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
      // union lines
      Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
      Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
      gp_Dir Dir1 = L1->Position().Direction();
      gp_Dir Dir2 = L2->Position().Direction();
      //if(!Dir1.IsEqual(Dir2,Precision::Angular())) {
      //if(!Dir1.IsParallel(Dir2,Precision::Angular())) {
      if(!Dir1.IsParallel(Dir2,Tol)) {
        continue;
      }
      // can union lines => create new edge
      TopoDS_Vertex V1 = sae.FirstVertex(edge1);
      gp_Pnt PV1 = BRep_Tool::Pnt(V1);
      TopoDS_Vertex V2 = sae.LastVertex(edge2);
      gp_Pnt PV2 = BRep_Tool::Pnt(V2);
      gp_Vec Vec(PV1,PV2);
      Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
      Standard_Real dist = PV1.Distance(PV2);
      Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
      TopoDS_Edge E;
      B.MakeEdge (E,tc,Precision::Confusion());
      B.Add (E,V1);  B.Add (E,V2);
      B.UpdateVertex(V1, 0., E, 0.);
      B.UpdateVertex(V2, dist, E, 0.);
      //ShapeFix_Edge sfe;
      //sfe.FixAddPCurve(E,aFace,Standard_False);
      //sfe.FixSameParameter(E);
      aChain.Remove(j);
      aChain.SetValue(j,E);
      j--;
    }
    if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
      // union circles
      Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
      Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
      gp_Pnt P01 = C1->Location();
      gp_Pnt P02 = C2->Location();
      if (P01.Distance(P02) > Precision::Confusion()) continue;
      // can union circles => create new edge
      TopoDS_Vertex V1 = sae.FirstVertex(edge1);
      gp_Pnt PV1 = BRep_Tool::Pnt(V1);
      TopoDS_Vertex V2 = sae.LastVertex(edge2);
      gp_Pnt PV2 = BRep_Tool::Pnt(V2);
      TopoDS_Vertex VM = sae.LastVertex(edge1);
      gp_Pnt PVM = BRep_Tool::Pnt(VM);
      GC_MakeCircle MC (PV1,PVM,PV2);
      Handle(Geom_Circle) C = MC.Value();
      TopoDS_Edge E;
      if (!MC.IsDone() || C.IsNull()) {
        // jfa for Mantis issue 0020228
        if (PV1.Distance(PV2) > Precision::Confusion()) continue;
        // closed chain
        C = C1;
        B.MakeEdge (E,C,Precision::Confusion());
        B.Add(E,V1);
        B.Add(E,V2);
      }
      else {
        gp_Pnt P0 = C->Location();
        gp_Dir D1(gp_Vec(P0,PV1));
        gp_Dir D2(gp_Vec(P0,PV2));
        Standard_Real fpar = C->XAxis().Direction().Angle(D1);
        if(fabs(fpar)>Precision::Confusion()) {
          // check orientation
          gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
          if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
            fpar = -fpar;
          }
        }
        Standard_Real lpar = C->XAxis().Direction().Angle(D2);
        if(fabs(lpar)>Precision::Confusion()) {
          // check orientation
          gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
          if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
            lpar = -lpar;
          }
        }
        if (lpar < fpar) lpar += 2*M_PI;
        Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
        B.MakeEdge (E,tc,Precision::Confusion());
        B.Add(E,V1);
        B.Add(E,V2);
        B.UpdateVertex(V1, fpar, E, 0.);
        B.UpdateVertex(V2, lpar, E, 0.);
      }
      aChain.Remove(j);
      aChain.SetValue(j,E);
      j--;
    }
  }
  if (j < aChain.Length()) {
    MESSAGE ("null curve3d in edge...");
    return Standard_False;
  }
  if (aChain.Length() > 1) {
    // second step: union edges with various curves
    // skl for bug 0020052 from Mantis: perform such unions
    // only if curves are bspline or bezier
    bool NeedUnion = true;
    for(j=1; j<=aChain.Length(); j++) {
      TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
      Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
      if(c3d.IsNull()) continue;
      while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
        Handle(Geom_TrimmedCurve) tc =
          Handle(Geom_TrimmedCurve)::DownCast(c3d);
        c3d = tc->BasisCurve();
      }
      if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
            c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
      NeedUnion = false;
      break;
    }
    if(NeedUnion) {
      MESSAGE ("can not make analitical union => make approximation");
      TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
      /*
      TopoDS_Wire W;
      B.MakeWire(W);
      for(j=1; j<=aChain.Length(); j++) {
        TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
        B.Add(W,edge);
      }
      Handle(BRepAdaptor_HCompCurve) Adapt = new BRepAdaptor_HCompCurve(W);
      Approx_Curve3d Conv(Adapt,Tol,GeomAbs_C1,9,1000);
      Handle(Geom_BSplineCurve) bc = Conv.Curve();
      TopoDS_Edge E;
      B.MakeEdge (E,bc,Precision::Confusion());
      B.Add (E,VF);
      B.Add (E,VL);
      */
      aChain.SetValue(1,E);
    }
    else {
      MESSAGE ("can not make approximation for such types of curves");
      return Standard_False;
    }
  }

  anEdge = TopoDS::Edge(aChain.Value(1));
  return Standard_True;
}
Esempio n. 21
0
 const Session::Handle Session::claim ( ::HINTERNET object )
 {
     return (Handle(object, &::destroy));
 }
//=======================================================================
//function : Perform
//purpose  :
//=======================================================================
TopoDS_Shape BlockFix_UnionEdges::Perform(const TopoDS_Shape& Shape,
                                          const Standard_Real Tol)
{
  myContext = new ShapeBuild_ReShape;
  myTolerance = Tol;
  TopoDS_Shape aResult = myContext->Apply(Shape);

  // processing each solid
  TopAbs_ShapeEnum aType = TopAbs_SOLID;
  TopExp_Explorer exps (Shape, aType);
  if (!exps.More()) {
    aType = TopAbs_SHELL;
    exps.Init(Shape, aType);
  }
  for (; exps.More(); exps.Next()) {
    //TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
    TopoDS_Shape aSolid = exps.Current();

    TopTools_IndexedMapOfShape ChangedFaces;

    // creating map of edge faces
    TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
    TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);

    Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
    TopoDS_Shape aRes = aSolid;
    aRes = aContext->Apply(aSolid);

    // processing each face
    TopExp_Explorer exp;
    for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
      TopoDS_Face aFace =
        TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
      TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;

      for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
        TopoDS_Edge edge = TopoDS::Edge(expe.Current());
        if (!aMapEdgeFaces.Contains(edge)) continue;
        const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
        TopTools_ListIteratorOfListOfShape anIter(aList);
        for ( ; anIter.More(); anIter.Next()) {
          TopoDS_Face face = TopoDS::Face(anIter.Value());
          TopoDS_Face face1 = TopoDS::Face(aContext->Apply(anIter.Value()));
          if (face1.IsSame(aFace)) continue;
          if (aMapFacesEdges.Contains(face)) {
            aMapFacesEdges.ChangeFromKey(face).Append(edge);
          }
          else {
            TopTools_ListOfShape ListEdges;
            ListEdges.Append(edge);
            aMapFacesEdges.Add(face,ListEdges);
          }
        }
      }

      for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++) {
        const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
        TopTools_SequenceOfShape SeqEdges;
        TopTools_ListIteratorOfListOfShape anIter(ListEdges);
        for ( ; anIter.More(); anIter.Next()) {
          SeqEdges.Append(anIter.Value());
        }
        if (SeqEdges.Length()==1) continue;
        TopoDS_Edge E;
        if ( MergeEdges(SeqEdges,aFace,Tol,E) ) {
          // now we have only one edge - aChain.Value(1)
          // we have to replace old ListEdges with this new edge
          aContext->Replace(SeqEdges(1),E);
          for (Standard_Integer j=2; j<=SeqEdges.Length(); j++) {
            aContext->Remove(SeqEdges(j));
          }
          TopoDS_Face tmpF = TopoDS::Face(exp.Current());
          if ( !ChangedFaces.Contains(tmpF) )
            ChangedFaces.Add(tmpF);
          tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
          if ( !ChangedFaces.Contains(tmpF) )
            ChangedFaces.Add(tmpF);
        }
      }

    } // end processing each face

    // fix changed faces and replace them in the local context
    for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
      TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
      Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
      sff->SetContext(myContext);
      sff->SetPrecision(myTolerance);
      sff->SetMinTolerance(myTolerance);
      sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
      sff->Perform();
      aContext->Replace(aFace,sff->Face());
    }

    if (ChangedFaces.Extent() > 0) {
      // fix changed shell and replace it in the local context
      TopoDS_Shape aRes1 = aContext->Apply(aRes);
      TopExp_Explorer expsh;
      for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
        TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
        Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
        sfsh->FixFaceOrientation(aShell);
        aContext->Replace(aShell,sfsh->Shell());
      }
      TopoDS_Shape aRes2 = aContext->Apply(aRes1);
      // put new solid into global context
      myContext->Replace(aSolid,aRes2);
    }

  } // end processing each solid

  aResult = myContext->Apply(Shape);
  return aResult;
}
Esempio n. 23
0
// Returns the results of the function
void SimpleDriver::Results(TDF_LabelList& res) const
{
    // References to other functions through TDF_Reference
    res.Append(Label());
    TDF_ChildIterator itr(Label().FindChild(2), false);
    for (; itr.More(); itr.Next())
    {
        Handle(TDF_Reference) ref;
        if (itr.Value().FindAttribute(TDF_Reference::GetID(), ref))
            res.Append(ref->Get());
    }
}

// Execution.
Standard_Integer SimpleDriver::Execute(Handle(TFunction_Logbook)& log) const
{
	// Check initialization
	if (Label().IsNull())
		return 1;

    // Take the double argument
    Handle(TDataStd_Real) time_keeper;
    if (!Label().FindAttribute(TDataStd_Real::GetID(), time_keeper))
        return 2;
    double times = time_keeper->Get();

    // Make a sphere 10000 * "times" times (it takes about a second on a simple computer).
    int i = 0;
    while (++i < 10000 * times)
    {
Esempio n. 24
0
 /**
  * Gets the singleton HotSpotJVMCIRuntime instance, initializing it if necessary
  */
 static Handle get_HotSpotJVMCIRuntime(TRAPS) {
     initialize_JVMCI(CHECK_(Handle()));
     return Handle(JNIHandles::resolve_non_null(_HotSpotJVMCIRuntime_instance));
 }
Esempio n. 25
0
	EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override {
		Handle(Nick.GetNick());
		return CONTINUE;
	}
Esempio n. 26
0
bool IfcGeom::Kernel::convert(const IfcSchema::IfcSurfaceCurveSweptAreaSolid* l, TopoDS_Shape& shape) {
	gp_Trsf directrix, position;
	TopoDS_Shape face;
	TopoDS_Wire wire, section;

	if (!l->ReferenceSurface()->is(IfcSchema::Type::IfcPlane)) {
		Logger::Message(Logger::LOG_WARNING, "Reference surface not supported", l->ReferenceSurface()->entity);
		return false;
	}
	
	if (!IfcGeom::Kernel::convert(l->Position(), position)   || 
		!convert_face(l->SweptArea(), face) || 
		!convert_wire(l->Directrix(), wire)    ) {
		return false;
	}

	gp_Pln pln;
	gp_Pnt directrix_origin;
	gp_Vec directrix_tangent;
	bool directrix_on_plane = true;
	IfcGeom::Kernel::convert((IfcSchema::IfcPlane*) l->ReferenceSurface(), pln);

	// As per Informal propositions 2: The Directrix shall lie on the ReferenceSurface.
	// This is not always the case with the test files in the repository. I am not sure
	// how to deal with this and whether my interpretation of the propositions is
	// correct. However, if it has been asserted that the vertices of the directrix do
	// not conform to the ReferenceSurface, the ReferenceSurface is ignored.
	{ 
		for (TopExp_Explorer exp(wire, TopAbs_VERTEX); exp.More(); exp.Next()) {
			if (pln.Distance(BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()))) > ALMOST_ZERO) {
				directrix_on_plane = false;
				Logger::Message(Logger::LOG_WARNING, "The Directrix does not lie on the ReferenceSurface", l->entity);
				break;
			}
		}
	}

	{ 
		TopExp_Explorer exp(wire, TopAbs_EDGE);
		TopoDS_Edge edge = TopoDS::Edge(exp.Current());
		double u0, u1;
		Handle(Geom_Curve) crv = BRep_Tool::Curve(edge, u0, u1);
		crv->D1(u0, directrix_origin, directrix_tangent);
	}

	if (pln.Axis().Direction().IsNormal(directrix_tangent, Precision::Approximation()) && directrix_on_plane) {
		directrix.SetTransformation(gp_Ax3(directrix_origin, directrix_tangent, pln.Axis().Direction()), gp::XOY());
	} else {
		directrix.SetTransformation(gp_Ax3(directrix_origin, directrix_tangent), gp::XOY());
	}
	face = BRepBuilderAPI_Transform(face, directrix);

	// NB: Note that StartParam and EndParam param are ignored and the assumption is
	// made that the parametric range over which to be swept matches the IfcCurve in
	// its entirety.
	BRepOffsetAPI_MakePipeShell builder(wire);

	{ TopExp_Explorer exp(face, TopAbs_WIRE);
	section = TopoDS::Wire(exp.Current()); }

	builder.Add(section);
	builder.SetTransitionMode(BRepBuilderAPI_RightCorner);
	if (directrix_on_plane) {
		builder.SetMode(pln.Axis().Direction());
	}
	builder.Build();
	builder.MakeSolid();
	shape = builder.Shape();
	shape.Move(position);

	return true;
}
Esempio n. 27
0
int OCCEdge::createNURBS(OCCVertex *start, OCCVertex *end, std::vector<OCCStruct3d> points,
                          DVec knots, DVec weights, IVec mult)
{
    try {
        Standard_Boolean periodic = false;
        
        int vertices = 0;
        if (start != NULL && end != NULL) {
            vertices = 2;
            periodic = true;
        }
        
        int nbControlPoints = points.size() + vertices;
        TColgp_Array1OfPnt  ctrlPoints(1, nbControlPoints);
        
        TColStd_Array1OfReal _knots(1, knots.size());
        TColStd_Array1OfReal _weights(1, weights.size());
        TColStd_Array1OfInteger  _mult(1, mult.size());
        
        for (unsigned i = 0; i < knots.size(); i++) {
            _knots.SetValue(i+1, knots[i]);
        }
        
        for (unsigned i = 0; i < weights.size(); i++) {
            _weights.SetValue(i+1, weights[i]);
        }
        
        int totKnots = 0;
        for (unsigned i = 0; i < mult.size(); i++) {
            _mult.SetValue(i+1, mult[i]);   
            totKnots += mult[i];
        }

        const int degree = totKnots - nbControlPoints - 1;

        int index = 1;
        
        if (!periodic) {
            ctrlPoints.SetValue(index++, gp_Pnt(start->X(), start->Y(), start->Z()));
        }
        
        for (unsigned i = 0; i < points.size(); i++) {
            gp_Pnt aP(points[i].x,points[i].y,points[i].z);
            ctrlPoints.SetValue(index++, aP);
        }
        
        if (!periodic) {
            ctrlPoints.SetValue(index++, gp_Pnt(end->X(), end->Y(), end->Z()));
        }
        
        Handle(Geom_BSplineCurve) NURBS = new Geom_BSplineCurve
        (ctrlPoints, _weights, _knots, _mult, degree, periodic);
        
        if (!periodic) {
            this->setShape(BRepBuilderAPI_MakeEdge(NURBS, start->vertex, end->vertex));
        } else {
            this->setShape(BRepBuilderAPI_MakeEdge(NURBS));
        }
    } catch(Standard_Failure &err) {
        Handle_Standard_Failure e = Standard_Failure::Caught();
        const Standard_CString msg = e->GetMessageString();
        if (msg != NULL && strlen(msg) > 1) {
            setErrorMessage(msg);
        } else {
            setErrorMessage("Failed to create nurbs");
        }
        return 1;
    }
    return 0;
}
Esempio n. 28
0
bool IfcGeom::Kernel::convert(const IfcSchema::IfcSweptDiskSolid* l, TopoDS_Shape& shape) {
	TopoDS_Wire wire, section1, section2;

	bool hasInnerRadius = l->hasInnerRadius();

	if (!convert_wire(l->Directrix(), wire)) {
		return false;
	}
	
	gp_Ax2 directrix;
	{
		gp_Pnt directrix_origin;
		gp_Vec directrix_tangent;
		TopExp_Explorer exp(wire, TopAbs_EDGE);
		TopoDS_Edge edge = TopoDS::Edge(exp.Current());
		double u0, u1;
		Handle(Geom_Curve) crv = BRep_Tool::Curve(edge, u0, u1);
		crv->D1(u0, directrix_origin, directrix_tangent);
		directrix = gp_Ax2(directrix_origin, directrix_tangent);
	}

	const double r1 = l->Radius() * getValue(GV_LENGTH_UNIT);
	Handle(Geom_Circle) circle = new Geom_Circle(directrix, r1);
	section1 = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle));

	if (hasInnerRadius) {
		const double r2 = l->InnerRadius() * getValue(GV_LENGTH_UNIT);
		if (r2 < getValue(GV_PRECISION)) {
			// Subtraction of pipes with small radii is unstable.
			hasInnerRadius = false;
		} else {
			Handle(Geom_Circle) circle2 = new Geom_Circle(directrix, r2);
			section2 = BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle2));
		}
	}

	// NB: Note that StartParam and EndParam param are ignored and the assumption is
	// made that the parametric range over which to be swept matches the IfcCurve in
	// its entirety.
	// NB2: Contrary to IfcSurfaceCurveSweptAreaSolid the transition mode has been
	// set to create round corners as this has proven to work better with the types
	// of directrices encountered, which do not necessarily conform to a surface.
	{ BRepOffsetAPI_MakePipeShell builder(wire);
	builder.Add(section1);
	builder.SetTransitionMode(BRepBuilderAPI_RoundCorner);
	builder.Build();
	builder.MakeSolid();
	shape = builder.Shape(); }

	if (hasInnerRadius) {
		BRepOffsetAPI_MakePipeShell builder(wire);
		builder.Add(section2);
		builder.SetTransitionMode(BRepBuilderAPI_RoundCorner);
		builder.Build();
		builder.MakeSolid();
		TopoDS_Shape inner = builder.Shape();

		BRepAlgoAPI_Cut brep_cut(shape, inner);
		bool is_valid = false;
		if (brep_cut.IsDone()) {
			TopoDS_Shape result = brep_cut;

			ShapeFix_Shape fix(result);
			fix.Perform();
			result = fix.Shape();
		
			is_valid = BRepCheck_Analyzer(result).IsValid() != 0;
			if (is_valid) {
				shape = result;
			}
		}

		if (!is_valid) {
			Logger::Message(Logger::LOG_WARNING, "Failed to subtract inner radius void for:", l->entity);
		}
	}

	return true;
}
Esempio n. 29
0
void Movie::HandleTouchStatus(Service::HID::TouchDataEntry& touch_data) {
    Handle(touch_data);
}
Esempio n. 30
0
 Timer::Handle Timer::proxy ( ::PTP_TIMER object )
 {
     return (Handle(object, &::abandon));
 }