コード例 #1
0
void CPlayerVisTable::DoVisibilityCheck(const Vec3& localPlayerPosn, SVisTableEntry& visInfo, VisEntryIndex visIndex)
{
	Vec3 vecToTarget;

	IEntity * pEntity = gEnv->pEntitySystem->GetEntity(visInfo.entityId);

	if(pEntity)
	{
		IPhysicalEntity* pTargetPhysEnt = pEntity->GetPhysics();

		SDeferredLinetestBuffer& targetBuffer = m_linetestBuffers[GetCurrentLinetestBufferTargetIndex()];

		if(targetBuffer.m_numLinetestsCurrentlyProcessing < kMaxVisTableLinetestsPerFrame)
		{
			visInfo.framesSinceLastCheck = 0;

			SDeferredLinetestReceiver * processingEntry = GetAvailableDeferredLinetestReceiver(targetBuffer);

			assert(processingEntry);

			Vec3 targetPosn = pEntity->GetWorldPos();
			if (visInfo.flags & eVF_CheckAgainstCenter)
			{
				AABB targetBbox;
				pEntity->GetWorldBounds(targetBbox);
				if (!targetBbox.IsEmpty())
				{
					targetPosn = targetBbox.GetCenter();
				}
				float radius = min(min(targetBbox.max.x-targetBbox.min.x, targetBbox.max.y-targetBbox.min.y), targetBbox.max.z-targetBbox.min.z);
				targetPosn += (localPlayerPosn-targetPosn).GetNormalized() * radius * 0.25f;
			}
			targetPosn.z += visInfo.heightOffset;
			vecToTarget = targetPosn - localPlayerPosn;

			processingEntry->visTableIndex = visIndex;			

			ray_hit hit;
			const int rayFlags = rwi_colltype_any(geom_colltype_solid&(~geom_colltype_player)) | rwi_ignore_noncolliding | rwi_pierceability(PIERCE_GLASS);

			m_numLinetestsThisFrame++;
			targetBuffer.m_numLinetestsCurrentlyProcessing++;

			visInfo.flags |= eVF_Pending;
			visInfo.flags &= ~eVF_CheckAgainstCenter;

			processingEntry->visBufferIndex = m_currentBufferTarget;

			const int numEntries = kMaxNumIgnoreEntities + 1; 
			IPhysicalEntity* pSkipEnts[numEntries];
			int numSkipEnts = 0;

			if(pTargetPhysEnt)
			{
				pSkipEnts[numSkipEnts] = pTargetPhysEnt;
				numSkipEnts++;
			}
			if (m_currentNumIgnoreEntities)
			{
				for(int i = 0; i < m_currentNumIgnoreEntities; ++i)
				{
					SIgnoreEntity& ignoreEnt = m_globalIgnoreEntities[i];
					CRY_ASSERT(ignoreEnt.id); 

					IEntity* pIgnoreEntity = gEnv->pEntitySystem->GetEntity(ignoreEnt.id);
					IPhysicalEntity* pIgnorePhysicsEntity = pIgnoreEntity ? pIgnoreEntity->GetPhysics() : NULL;

					if (pIgnorePhysicsEntity)
					{
						pSkipEnts[numSkipEnts] = pIgnorePhysicsEntity;
						numSkipEnts++;
					}
				}
			}
			
			CRY_ASSERT(processingEntry->queuedRayID == 0);

			processingEntry->queuedRayID = g_pGame->GetRayCaster().Queue(
				RayCastRequest::HighPriority,
				RayCastRequest(localPlayerPosn, vecToTarget,
				ent_terrain|ent_static|ent_sleeping_rigid|ent_rigid,
				rayFlags,
				pSkipEnts,
				numSkipEnts, 2),
				functor(*processingEntry, &SDeferredLinetestReceiver::OnDataReceived));

#if ALLOW_VISTABLE_DEBUGGING
			m_debugDraw.UpdateDebugTarget(visInfo.entityId, targetPosn, ((visInfo.flags & eVF_Visible) != 0));
#endif

		}
	}
	else
	{
		visInfo.flags |= eVF_Remove;
	}
}
コード例 #2
0
ファイル: Atom.cpp プロジェクト: kdgerring/sigma
bool Atom::equal (Atom t) const
{
  return functor() == t.functor() &&
         args().equal(t.args());
} // Atom::equal
コード例 #3
0
ファイル: Debugger.cpp プロジェクト: nickooms/webkit
void Debugger::toggleBreakpoint(Breakpoint& breakpoint, Debugger::BreakpointState enabledOrNot)
{
    ToggleBreakpointFunctor functor(this, breakpoint, enabledOrNot);
    m_vm.heap.forEachCodeBlock(functor);
}
コード例 #4
0
ファイル: thunder.cpp プロジェクト: leohawke/bt_tool
		~sentry() noexcept {
			static_assert(noexcept(functor()),
				"Please check that the finally block cannot throw, "
				"and mark the lambda as noexcept.");
			functor();
		}
コード例 #5
0
static int
memory_usage (MonoObject *obj, GHashTable *visited, 
	      int (*functor)(MonoObject*, MonoType*, int))
{
  int total = 0;
  MonoClass *klass;
  MonoType *type;
  gpointer iter = NULL;
  MonoClassField *field;

  if (g_hash_table_lookup (visited, obj))
    return 0;

  g_hash_table_insert (visited, obj, obj);

  klass = mono_object_get_class (obj);
  type = mono_class_get_type (klass);

  /* This is an array, so drill down into it */
  if (type->type == MONO_TYPE_SZARRAY)
    total += memory_usage_array ((MonoArray *) obj, visited, functor);

  while ((field = mono_class_get_fields (klass, &iter)) != NULL) {
    MonoType *ftype = mono_field_get_type (field);
    gpointer value;

    if ((ftype->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA)) != 0)
      continue;

    /* FIXME: There are probably other types we need to drill down into */
    switch (ftype->type) {

    case MONO_TYPE_CLASS:
    case MONO_TYPE_OBJECT:
      mono_field_get_value (obj, field, &value);

      if (value != NULL)
	total += memory_usage ((MonoObject *) value, visited, functor);

      break;

    case MONO_TYPE_STRING:
      mono_field_get_value (obj, field, &value);
      if (value != NULL) 
	total += mono_object_get_size ((MonoObject *) value);
      break;

    case MONO_TYPE_SZARRAY:
      mono_field_get_value (obj, field, &value);

      if (value != NULL) {
	total += memory_usage_array ((MonoArray *) value, visited, functor);
	total += mono_object_get_size ((MonoObject *) value);
      }

      break;

    default:
      /* printf ("Got type 0x%x\n", ftype->type); */
      /* ignore, this will be included in mono_object_get_size () */
      break;
    }
  }

  total = functor(obj, type, total);

  return total;
}
コード例 #6
0
ファイル: zip.hpp プロジェクト: EVaillant/toolsbox
 template<class F, class Tuple, std::size_t ... I> auto make_iterator(F&& functor, Tuple&& tuple, std::index_sequence<I...>)
 {
   return std::make_tuple(functor(std::get<I>(tuple))...);
 }
コード例 #7
0
void Heap::collect(SweepToggle sweepToggle)
{
    SamplingRegion samplingRegion("Garbage Collection");
    
    GCPHASE(Collect);
    ASSERT(globalData()->apiLock().currentThreadIsHoldingLock());
    RELEASE_ASSERT(globalData()->identifierTable == wtfThreadData().currentIdentifierTable());
    ASSERT(m_isSafeToCollect);
    JAVASCRIPTCORE_GC_BEGIN();
    RELEASE_ASSERT(m_operationInProgress == NoOperation);
    m_operationInProgress = Collection;

    m_activityCallback->willCollect();

    double lastGCStartTime = WTF::currentTime();
    if (lastGCStartTime - m_lastCodeDiscardTime > minute) {
        deleteAllCompiledCode();
        m_lastCodeDiscardTime = WTF::currentTime();
    }

    {
        GCPHASE(Canonicalize);
        m_objectSpace.canonicalizeCellLivenessData();
    }

    markRoots();
    
    {
        GCPHASE(ReapingWeakHandles);
        m_objectSpace.reapWeakSets();
    }

    JAVASCRIPTCORE_GC_MARKED();

    {
        m_blockSnapshot.resize(m_objectSpace.blocks().set().size());
        MarkedBlockSnapshotFunctor functor(m_blockSnapshot);
        m_objectSpace.forEachBlock(functor);
    }

    copyBackingStores();

    {
        GCPHASE(FinalizeUnconditionalFinalizers);
        finalizeUnconditionalFinalizers();
    }

    {
        GCPHASE(finalizeSmallStrings);
        m_globalData->smallStrings.finalizeSmallStrings();
    }

    {
        GCPHASE(DeleteCodeBlocks);
        deleteUnmarkedCompiledCode();
    }

    {
        GCPHASE(DeleteSourceProviderCaches);
        m_globalData->clearSourceProviderCaches();
    }

    if (sweepToggle == DoSweep) {
        SamplingRegion samplingRegion("Garbage Collection: Sweeping");
        GCPHASE(Sweeping);
        m_objectSpace.sweep();
        m_objectSpace.shrink();
    }

    m_sweeper->startSweeping(m_blockSnapshot);
    m_bytesAbandoned = 0;

    {
        GCPHASE(ResetAllocators);
        m_objectSpace.resetAllocators();
    }
    
    size_t currentHeapSize = size();
    if (Options::gcMaxHeapSize() && currentHeapSize > Options::gcMaxHeapSize())
        HeapStatistics::exitWithFailure();

    m_sizeAfterLastCollect = currentHeapSize;

    // To avoid pathological GC churn in very small and very large heaps, we set
    // the new allocation limit based on the current size of the heap, with a
    // fixed minimum.
    size_t maxHeapSize = max(minHeapSize(m_heapType, m_ramSize), proportionalHeapSize(currentHeapSize, m_ramSize));
    m_bytesAllocatedLimit = maxHeapSize - currentHeapSize;

    m_bytesAllocated = 0;
    double lastGCEndTime = WTF::currentTime();
    m_lastGCLength = lastGCEndTime - lastGCStartTime;

    if (Options::recordGCPauseTimes())
        HeapStatistics::recordGCPauseTime(lastGCStartTime, lastGCEndTime);
    RELEASE_ASSERT(m_operationInProgress == Collection);

    m_operationInProgress = NoOperation;
    JAVASCRIPTCORE_GC_END();

    if (Options::useZombieMode())
        zombifyDeadObjects();

    if (Options::objectsAreImmortal())
        markDeadObjects();

    if (Options::showObjectStatistics())
        HeapStatistics::showObjectStatistics(this);
}
コード例 #8
0
ファイル: Laser.cpp プロジェクト: aronarts/FireNET
void CLaserBeam::UpdateLaser(const CLaserBeam::SLaserUpdateDesc& laserUpdateDesc)
{
	if(m_pLaserParams && m_laserOn)
	{
		IEntity* pLaserEntity = CreateLaserEntity();
		if (pLaserEntity)
		{
			m_lastLaserUpdatePosition = laserUpdateDesc.m_laserPos;
			m_lastLaserUpdateDirection = laserUpdateDesc.m_laserDir;

			m_laserUpdateTimer += laserUpdateDesc.m_frameTime;

			UpdateLaserGeometry(*pLaserEntity);

			if(m_laserUpdateTimer < LASER_UPDATE_TIME)
				return;

			m_laserUpdateTimer = Random(0.0f, LASER_UPDATE_TIME * 0.4f);

			if ((laserUpdateDesc.m_ownerCloaked && !laserUpdateDesc.m_weaponZoomed) || laserUpdateDesc.m_bOwnerHidden)
			{
				pLaserEntity->Hide(true);
				return;
			}
			pLaserEntity->Hide(false);

			const float range = m_pLaserParams->laser_range[GetIndexFromGeometrySlot()];

			// Use the same flags as the AI system uses for visbility.
			const int objects = ent_terrain|ent_static|ent_rigid|ent_sleeping_rigid|ent_independent; //ent_living;
			const int flags = (geom_colltype_ray << rwi_colltype_bit) | rwi_colltype_any | (10 & rwi_pierceability_mask) | (geom_colltype14 << rwi_colltype_bit);

			//If we did not get a result, just cancel it, we will queue a new one again
			RayCastRequest::Priority requestPriority = RayCastRequest::MediumPriority;
			if (m_queuedRayId != 0)
			{
				g_pGame->GetRayCaster().Cancel(m_queuedRayId);
				m_queuedRayId = 0;
				requestPriority = RayCastRequest::HighPriority;
			}

			IItemSystem* pItemSystem = g_pGame->GetIGameFramework()->GetIItemSystem();
			IPhysicalEntity* pSkipEntity = NULL;
			uint8 numSkips = 0;

			CItem* pItem = static_cast<CItem*>(pItemSystem->GetItem(m_ownerEntityId));

			if(pItem)
			{
				if(pItem->IsAccessory())
				{
					CItem* pParentItem = static_cast<CItem*>(pItemSystem->GetItem(pItem->GetParentId()));
				
					if(pParentItem)
					{
						pItem = pParentItem;
					}					
				}

				IEntity* pOwnerEnt = 0;
				CWeapon* pWeapon = static_cast<CWeapon*>(pItem->GetIWeapon());
				if (pWeapon && pWeapon->GetHostId() != 0)
				{
					pOwnerEnt = gEnv->pEntitySystem->GetEntity(pWeapon->GetHostId());
				}
				else
				{
					pOwnerEnt = pItem->GetOwner();
				}

				if(pOwnerEnt)
				{
					IPhysicalEntity* pOwnerPhysics = pOwnerEnt->GetPhysics();

					if(pOwnerPhysics)
					{
						pSkipEntity = pOwnerPhysics;
						numSkips++;
					}
				}
			}

			m_queuedRayId = g_pGame->GetRayCaster().Queue(
				requestPriority,
				RayCastRequest(laserUpdateDesc.m_laserPos, laserUpdateDesc.m_laserDir*range,
				objects,
				flags,
				&pSkipEntity,
				numSkips),
				functor(*this, &CLaserBeam::OnRayCastDataReceived));
		}

	}
	else if (!m_pLaserParams)
	{
		GameWarning("LASER PARAMS: Item of type CLaser is missing it's laser params!");
	}
}
コード例 #9
0
ファイル: graphics.cpp プロジェクト: Glyth/xoreos
bool GraphicsManager::setFSAA(int level) {
	// Force calling it from the main thread
	if (!Common::isMainThread()) {
		Events::MainThreadFunctor<bool> functor(boost::bind(&GraphicsManager::setFSAA, this, level));

		return RequestMan.callInMainThread(functor);
	}

	if (_fsaa == level)
		// Nothing to do
		return true;

	// Check if we have the support for that level
	if (level > _fsaaMax)
		return false;

	// Backup the old level and set the new level
	int oldFSAA = _fsaa;
	_fsaa = level;

	destroyContext();

	uint32 flags = SDL_GetWindowFlags(_screen);

	int x, y;
	SDL_GetWindowPosition(_screen, &x, &y);

	SDL_GL_DeleteContext(_glContext);
	SDL_DestroyWindow(_screen);

	// Set the multisample level
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, (_fsaa > 0) ? 1 : 0);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, _fsaa);

	// Now try to change the screen
	_screen = SDL_CreateWindow(_windowTitle.c_str(), x, y, _width, _height, flags);

	if (!_screen) {
		// Failed changing, back up

		_fsaa = oldFSAA;

		// Set the multisample level
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, (_fsaa > 0) ? 1 : 0);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, _fsaa);
		_screen = SDL_CreateWindow(_windowTitle.c_str(), x, y, _width, _height, flags);

		// There's no reason how this could possibly fail, but ok...
		if (!_screen)
			throw Common::Exception("Failed reverting to the old FSAA settings");
	}

	setWindowIcon(*_screen);

	// Initial call to setupSDLGL has already identified which GL context we can use.
	if (_gl3) {
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, _glProfile);
	} else {
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, _glProfile);
	}
	_glContext = SDL_GL_CreateContext(_screen);
	rebuildContext();

	return _fsaa == level;
}
コード例 #10
0
    int ComputeBasis_HGRAD_Vector(const ordinal_type nworkset,
                                  const ordinal_type C,
                                  const ordinal_type order,
                                  const bool verbose) {
      typedef Vector<VectorTagType> VectorType;

      typedef typename VectorTagType::value_type ValueType;
      constexpr int VectorLength = VectorTagType::length;

      Teuchos::RCP<std::ostream> verboseStream;
      Teuchos::oblackholestream bhs; // outputs nothing

      if (verbose) 
        verboseStream = Teuchos::rcp(&std::cout, false);
      else
        verboseStream = Teuchos::rcp(&bhs,       false);

      Teuchos::oblackholestream oldFormatState;
      oldFormatState.copyfmt(std::cout);

      typedef typename
        Kokkos::Impl::is_space<DeviceSpaceType>::host_mirror_space::execution_space HostSpaceType ;

      *verboseStream << "DeviceSpace::  "; DeviceSpaceType::print_configuration(*verboseStream, false);
      *verboseStream << "HostSpace::    ";   HostSpaceType::print_configuration(*verboseStream, false);
      *verboseStream << "VectorLength::  " << (VectorLength) << "\n";

      using BasisTypeHost = Basis_HGRAD_HEX_C1_FEM<HostSpaceType,ValueType,ValueType>;
      using ImplBasisType = Impl::Basis_HGRAD_HEX_C1_FEM;
      using range_type = Kokkos::pair<ordinal_type,ordinal_type>;

      constexpr size_t LLC_CAPACITY = 32*1024*1024;
      Intrepid2::Test::Flush<LLC_CAPACITY,DeviceSpaceType> flush;
      
      Kokkos::Impl::Timer timer;
      double t_vectorize = 0;
      int errorFlag = 0;

      BasisTypeHost hostBasis;
      const auto cellTopo = hostBasis.getBaseCellTopology();

      auto cubature = DefaultCubatureFactory::create<DeviceSpaceType,ValueType,ValueType>(cellTopo, order);

      const ordinal_type 
        numCells = C,
        numCellsAdjusted = C/VectorLength + (C%VectorLength > 0),
        numVerts = cellTopo.getVertexCount(),
        numDofs = hostBasis.getCardinality(),
        numPoints = cubature->getNumPoints(), 
        spaceDim = cubature->getDimension();

      Kokkos::DynRankView<ValueType,HostSpaceType> dofCoordsHost("dofCoordsHost", numDofs, spaceDim);
      hostBasis.getDofCoords(dofCoordsHost);
      const auto refNodesHost = Kokkos::subview(dofCoordsHost, range_type(0, numVerts), Kokkos::ALL());
      
      // pertub nodes
      Kokkos::DynRankView<VectorType,HostSpaceType> worksetCellsHost("worksetCellsHost", numCellsAdjusted, numVerts, spaceDim);
      for (ordinal_type cell=0;cell<numCells;++cell) {
        for (ordinal_type i=0;i<numVerts;++i)
          for (ordinal_type j=0;j<spaceDim;++j) {
            ValueType val = (rand()/(RAND_MAX + 1.0))*0.2 -0.1;
            worksetCellsHost(cell/VectorLength, i, j)[cell%VectorLength] = refNodesHost(i, j) + val; 
          }
      }

      auto worksetCells = Kokkos::create_mirror_view(typename DeviceSpaceType::memory_space(), worksetCellsHost);
      Kokkos::deep_copy(worksetCells, worksetCellsHost);

      Kokkos::DynRankView<ValueType,DeviceSpaceType> refPoints("refPoints", numPoints, spaceDim), refWeights("refWeights", numPoints);
      cubature->getCubature(refPoints, refWeights);

      std::cout
        << "===============================================================================\n" 
        << " Performance Test evaluating ComputeBasis \n"
        << " # of workset = " << nworkset << "\n" 
        << " Test Array Structure (C,F,P,D) = " << numCells << ", " << numDofs << ", " << numPoints << ", " << spaceDim << "\n"
        << "===============================================================================\n";

      *verboseStream
        << "\n"
        << "===============================================================================\n"
        << "TEST 1: evaluateFields vector version\n"
        << "===============================================================================\n";
      
      try {
        Kokkos::DynRankView<ValueType,DeviceSpaceType> 
          refBasisValues("refBasisValues", numDofs, numPoints),
          refBasisGrads ("refBasisGrads",  numDofs, numPoints, spaceDim);
        
        ImplBasisType::getValues<DeviceSpaceType>(refBasisValues, refPoints, OPERATOR_VALUE);
        ImplBasisType::getValues<DeviceSpaceType>(refBasisGrads,  refPoints, OPERATOR_GRAD);
        
        const ordinal_type ibegin = -3;

        // testing vertical approach
        {          
          Kokkos::DynRankView<VectorType,DeviceSpaceType> 
            weightedBasisValues("weightedBasisValues", numCellsAdjusted, numDofs, numPoints),
            weightedBasisGrads ("weightedBasisGrads",  numCellsAdjusted, numDofs, numPoints, spaceDim);

          typedef F_hgrad_eval<VectorType,ValueType,DeviceSpaceType> FunctorType;

          using range_policy_type = Kokkos::Experimental::MDRangePolicy
            < DeviceSpaceType, Kokkos::Experimental::Rank<2>, Kokkos::IndexType<ordinal_type> >;
          range_policy_type policy( {                0,         0 },
                                    { numCellsAdjusted, numPoints } );

          FunctorType functor(weightedBasisValues,
                              weightedBasisGrads,
                              refBasisGrads,
                              worksetCells,
                              refWeights,
                              refBasisValues,
                              refBasisGrads);
          
          for (ordinal_type iwork=ibegin;iwork<nworkset;++iwork) {
            flush.run();

            DeviceSpaceType::fence();
            timer.reset();
            
            Kokkos::parallel_for(policy, functor);

            DeviceSpaceType::fence();
            t_vectorize += (iwork >= 0)*timer.seconds();
          }

        }

      } catch (std::exception err) {
        *verboseStream << "UNEXPECTED ERROR !!! ----------------------------------------------------------\n";
        *verboseStream << err.what() << '\n';
        *verboseStream << "-------------------------------------------------------------------------------" << "\n\n";
        errorFlag = -1000;
      }

      std::cout 
        << "TEST HGRAD " 
        << " t_vectorize = " << (t_vectorize/nworkset)
        << std::endl;
      
      if (errorFlag != 0)
        std::cout << "End Result: TEST FAILED\n";
      else
        std::cout << "End Result: TEST PASSED\n";
      
      // reset format state of std::cout
      std::cout.copyfmt(oldFormatState);
      
      return errorFlag;
    }
コード例 #11
0
ファイル: cgdbrc.c プロジェクト: ArnaudValensi/cgdb
int command_parse_set(void)
{
    /* commands could look like the following:
     * set ignorecase
     * set noignorecase
     * set focus=gdb
     * set tabstop=8
     */

    int rv = 1;
    int boolean = 1;
    const char *value = NULL;

    switch ((rv = yylex())) {
        case EOL:{
            /* TODO: Print out all the variables that have been set. */
        }
            break;
        case IDENTIFIER:{
            const char *token = get_token();
            int length = strlen(token);
            struct ConfigVariable *variable = NULL;

            if (length > 2 && token[0] == 'n' && token[1] == 'o') {
                value = token + 2;
                boolean = 0;
            } else {
                value = token;
            }

            if ((variable = get_variable(value)) != NULL) {
                rv = 0;
                if (boolean == 0 && variable->type != CONFIG_TYPE_BOOL) {
                    /* this is an error, you cant' do:
                     * set notabstop 
                     */
                    rv = 1;
                }

                switch (variable->type) {
                    case CONFIG_TYPE_BOOL:
                        *(int *) (variable->data) = boolean;
                        break;
                    case CONFIG_TYPE_INT:{
                        if (yylex() == '=' && yylex() == NUMBER) {
                            int data = strtol(get_token(), NULL, 10);

                            *(int *) (variable->data) = data;
                        } else {
                            rv = 1;
                        }
                    }
                        break;
                    case CONFIG_TYPE_STRING:{
                        if (yylex() == '=' &&
                                (rv = yylex(), rv == STRING
                                        || rv == IDENTIFIER)) {
                            /* BAM! comma operator */
                            char *data = (char *) get_token();

                            if (rv == STRING) {
                                /* get rid of quotes */
                                data = data + 1;
                                data[strlen(data) - 1] = '\0';
                            }
                            if (variable->data) {
                                free(variable->data);
                            }
                            variable->data = strdup(data);
                        } else {
                            rv = 1;
                        }
                    }
                        break;
                    case CONFIG_TYPE_FUNC_VOID:{
                        int (*functor) (void) = (int (*)(void)) variable->data;

                        if (functor) {
                            rv = functor();
                        } else {
                            rv = 1;
                        }
                    }
                        break;
                    case CONFIG_TYPE_FUNC_BOOL:{
                        int (*functor) (int) = (int (*)(int)) variable->data;

                        if (functor) {
                            rv = functor(boolean);
                        } else {
                            rv = 1;
                        }
                    }
                        break;
                    case CONFIG_TYPE_FUNC_INT:{
                        int (*functor) (int) = (int (*)(int)) variable->data;

                        if (yylex() == '=' && yylex() == NUMBER) {
                            int data = strtol(get_token(), NULL, 10);

                            if (functor) {
                                rv = functor(data);
                            } else {
                                rv = 1;
                            }
                        } else {
                            rv = 1;
                        }
                    }
                        break;
                    case CONFIG_TYPE_FUNC_STRING:{
                        int (*functor) (const char *) =
                                (int (*)(const char *)) variable->data;
                        if (yylex() == '=' && (rv = yylex(), rv == STRING
                                        || rv == IDENTIFIER)) {
                            /* BAM! comma operator */
                            char *data = (char *) get_token();

                            if (rv == STRING) {
                                /* get rid of quotes */
                                data = data + 1;
                                data[strlen(data) - 1] = '\0';
                            }
                            if (functor) {
                                rv = functor(data);
                            } else {
                                rv = 1;
                            }
                        } else {
                            rv = 1;
                        }
                    }
                        break;
                    default:
                        rv = 1;
                        break;
                }
            }
        }
            break;
        default:
            break;
    }

    return rv;
}
コード例 #12
0
ファイル: random.hpp プロジェクト: Alienfeel/graphchi-cpp
 void shuffle(Iterator begin, Iterator end) {
     mut.lock();
     shuffle_functor functor(*this);
     std::random_shuffle(begin, end, functor);
     mut.unlock();
 } // end of shuffle
コード例 #13
0
void DOF<typename TRAITS::Jacobian, TRAITS>::
evaluateFields(typename TRAITS::EvalData workset)
{ 
  panzer::BasisValues2<double> & basisValues = *workset.bases[basis_index];

  if(is_vector_basis) {
    if(accelerate_jacobian) {
      int spaceDim  = basisValues.basis_vector.dimension(3);
      if(spaceDim==3) {
        dof_functors::EvaluateDOFFastSens_Vector<ScalarT,typename BasisValues2<double>::Array_CellBasisIPDim,3> functor(dof_basis,dof_ip_vector,offsets_array,basisValues.basis_vector);
        Kokkos::parallel_for(workset.num_cells,functor);
      }
      else {
        dof_functors::EvaluateDOFFastSens_Vector<ScalarT,typename BasisValues2<double>::Array_CellBasisIPDim,2> functor(dof_basis,dof_ip_vector,offsets_array,basisValues.basis_vector);
        Kokkos::parallel_for(workset.num_cells,functor);
      }
    }
    else {
      int spaceDim  = basisValues.basis_vector.dimension(3);
      if(spaceDim==3) {
        dof_functors::EvaluateDOFWithSens_Vector<ScalarT,typename BasisValues2<double>::Array_CellBasisIPDim,3> functor(dof_basis,dof_ip_vector,basisValues.basis_vector);
        Kokkos::parallel_for(workset.num_cells,functor);
      }
      else {
        dof_functors::EvaluateDOFWithSens_Vector<ScalarT,typename BasisValues2<double>::Array_CellBasisIPDim,2> functor(dof_basis,dof_ip_vector,basisValues.basis_vector);
        Kokkos::parallel_for(workset.num_cells,functor);
      }
    }
  }
  else {
    if(accelerate_jacobian) {
      dof_functors::EvaluateDOFFastSens_Scalar<ScalarT,typename BasisValues2<double>::Array_CellBasisIP> functor(dof_basis,dof_ip_scalar,offsets_array,basisValues.basis_scalar);
      Kokkos::parallel_for(workset.num_cells,functor);
    }
    else {
      dof_functors::EvaluateDOFWithSens_Scalar<ScalarT,typename BasisValues2<double>::Array_CellBasisIP> functor(dof_basis,dof_ip_scalar,basisValues.basis_scalar);
      Kokkos::parallel_for(workset.num_cells,functor);
    }
  }
}
void CFlowNode_AISequenceAction_ApproachAndEnterVehicle::HandleSequenceEvent(AIActionSequence::SequenceEvent sequenceEvent)
{
	switch(sequenceEvent)
	{
	case AIActionSequence::StartAction:
		{
			if (!m_actInfo.pEntity)
			{
				// the entity has gone for some reason, at least make sure the action gets finished properly and the FG continues
				UnregisterFromVehicleEvent(NULL);
				CancelSequenceAndActivateOutputPort(OutputPort_Done);
				return;
			}

			m_entityId = m_actInfo.pEntity->GetId();
			m_vehicleId = GetPortEntityId(&m_actInfo, InputPort_VehicleId);
			m_seatNumber = GetPortInt(&m_actInfo, InputPort_SeatNumber);
			m_fast = GetPortBool(&m_actInfo, InputPort_Fast);

			const bool alsoCheckForCrewHostility = true;
			IVehicle* pVehicle = GetVehicle(alsoCheckForCrewHostility);
			if (!pVehicle)
			{
				CryLog("Actor %s failed to enter vehicle (specified vehicle not found or its crew is hostile towards the actor returned true)", m_actInfo.pEntity->GetName());
				CancelSequenceAndActivateOutputPort(OutputPort_Done);
				return;
			}

			IVehicleSeat* pSeat = GetVehicleSeat(pVehicle);
			if (!pSeat)
			{
				CryLog("Actor %s failed to enter vehicle (bad seat number provided: %i)", m_actInfo.pEntity->GetName(), m_seatNumber);
				CancelSequenceAndActivateOutputPort(OutputPort_Done);
				return;
			}

			const IVehicleHelper* pEnterHelper = static_cast<CVehicleSeat*>(pSeat)->GetEnterHelper();
			if (!pEnterHelper)
			{
				CryLog("Actor %s failed to enter vehicle (vehicle has no enter-helper)", m_actInfo.pEntity->GetName());
				CancelSequenceAndActivateOutputPort(OutputPort_Done);
				return;
			}

			m_vehicleSeatEnterPosition = pEnterHelper->GetWorldSpaceTranslation();

			assert(gEnv && gEnv->pGame && gEnv->pGame->GetIGameFramework() && gEnv->pGame->GetIGameFramework()->GetIActorSystem());
			IActor* pActor = gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(m_actInfo.pEntity->GetId());

			// if it's the player, have him enter quickly (we assume that the user moved him close enough to the vehicle)
			if (pActor && pActor->IsPlayer())
			{
				EnterVehicleSeat(true, pSeat);
			}
			else if (m_actInfo.pEntity->GetAI())
			{
				if (m_fast)
				{
					TeleportToVehicleSeat();
					EnterVehicleSeat(false, pSeat);
				}
				else
				{
					MovementRequest request;
					request.callback = functor(*this, &CFlowNode_AISequenceAction_ApproachAndEnterVehicle::MovementRequestCallback);
					request.entityID = m_actInfo.pEntity->GetId();
					request.type = MovementRequest::MoveTo;
					request.destination = m_vehicleSeatEnterPosition;
					request.style.SetSpeed((MovementStyle::Speed)GetPortInt(&m_actInfo, InputPort_Speed));
					request.style.SetStance((MovementStyle::Stance)GetPortInt(&m_actInfo, InputPort_Stance));
					m_movementRequestID = gEnv->pAISystem->GetMovementSystem()->QueueRequest(request);
				}
			}
			else if (pActor)
			{
				pActor->HolsterItem(true);
				pActor->MountedGunControllerEnabled(false);
				pActor->GetGameObject()->SetAspectProfile(eEA_Physics, eAP_Alive);
				TeleportToVehicleSeat();
				EnterVehicleSeat(GetAnimationTransitionEnabled(), pSeat);
			}
			else
			{
				CRY_ASSERT_MESSAGE(0, "no compatible entity was provided");
				CryWarning(VALIDATOR_MODULE_AI, VALIDATOR_WARNING, "Actor %s failed to enter vehicle (no compatible entity was provided)", m_actInfo.pEntity->GetName());
				CancelSequenceAndActivateOutputPort(OutputPort_Done);
			}
		}
		break;

	case AIActionSequence::SequenceStopped:
		{
			if (m_movementRequestID)
			{
				gEnv->pAISystem->GetMovementSystem()->CancelRequest(m_movementRequestID);
				m_movementRequestID = MovementRequestID::Invalid();
				UnregisterFromVehicleEvent(NULL);
			}
		}
		break;
	}
}
コード例 #15
0
		static GLM_FUNC_QUALIFIER T apply(F functor, const T& val)
		{
			return functor(val);
		}
コード例 #16
0
CBirdsFlock::CBirdsFlock( IEntity *pEntity ) : CFlock( pEntity,EFLOCK_BIRDS ), m_bAttractOutput(false)
{ 
	m_boidEntityName = "BirdBoid";  
	m_landCollisionCallback = functor(*this,&CBirdsFlock::LandCollisionCallback);

};
コード例 #17
0
	inline result operator () (command_reference rReference, command_event eEvent,
	  command_event cCumulative, const struct command_info *iInfo)
	{ return functor(rReference, eEvent, cCumulative, iInfo); }
コード例 #18
0
ファイル: CameraRayScan.cpp プロジェクト: super-nova/NovaRepo
QueuedRayID CCameraRayScan::ShootRay(const Vec3 &rayPos, const Vec3 &rayDir, int objTypes /*= g_objTypes*/, int geomFlags /*= g_geomFlags*/, IPhysicalEntity **pSkipEnts /*= NULL*/, int numSkipEnts /*= 0*/)
{
	return g_pGame->GetRayCaster().Queue(RayCastRequest::MediumPriority,
										 RayCastRequest(rayPos, rayDir, objTypes, geomFlags, pSkipEnts, numSkipEnts),
										 functor(*this, &CCameraRayScan::OnRayCastResult));
}
コード例 #19
0
void Heap::collect(SweepToggle sweepToggle)
{
#if ENABLE(ALLOCATION_LOGGING)
    dataLogF("JSC GC starting collection.\n");
#endif
    
    double before = 0;
    if (Options::logGC()) {
        dataLog("[GC", sweepToggle == DoSweep ? " (eager sweep)" : "", ": ");
        before = currentTimeMS();
    }
    
    SamplingRegion samplingRegion("Garbage Collection");
    
    RELEASE_ASSERT(!m_deferralDepth);
    GCPHASE(Collect);
    ASSERT(vm()->currentThreadIsHoldingAPILock());
    RELEASE_ASSERT(vm()->identifierTable == wtfThreadData().currentIdentifierTable());
    ASSERT(m_isSafeToCollect);
    JAVASCRIPTCORE_GC_BEGIN();
    RELEASE_ASSERT(m_operationInProgress == NoOperation);
    
    m_deferralDepth++; // Make sure that we don't GC in this call.
    m_vm->prepareToDiscardCode();
    m_deferralDepth--; // Decrement deferal manually, so we don't GC when we do so, since we are already GCing!.
    
    m_operationInProgress = Collection;
    m_extraMemoryUsage = 0;

    m_activityCallback->willCollect();

    double lastGCStartTime = WTF::monotonicallyIncreasingTime();
    if (lastGCStartTime - m_lastCodeDiscardTime > minute) {
        deleteAllCompiledCode();
        m_lastCodeDiscardTime = WTF::monotonicallyIncreasingTime();
    }

    {
        GCPHASE(Canonicalize);
        m_objectSpace.canonicalizeCellLivenessData();
    }

    markRoots();
    
    {
        GCPHASE(ReapingWeakHandles);
        m_objectSpace.reapWeakSets();
    }

    JAVASCRIPTCORE_GC_MARKED();
    
    {
        GCPHASE(SweepingArrayBuffers);
        m_arrayBuffers.sweep();
    }

    {
        m_blockSnapshot.resize(m_objectSpace.blocks().set().size());
        MarkedBlockSnapshotFunctor functor(m_blockSnapshot);
        m_objectSpace.forEachBlock(functor);
    }

    copyBackingStores();

    {
        GCPHASE(FinalizeUnconditionalFinalizers);
        finalizeUnconditionalFinalizers();
    }

    {
        GCPHASE(DeleteCodeBlocks);
        deleteUnmarkedCompiledCode();
    }

    {
        GCPHASE(DeleteSourceProviderCaches);
        m_vm->clearSourceProviderCaches();
    }

    if (sweepToggle == DoSweep) {
        SamplingRegion samplingRegion("Garbage Collection: Sweeping");
        GCPHASE(Sweeping);
        m_objectSpace.sweep();
        m_objectSpace.shrink();
    }

    m_sweeper->startSweeping(m_blockSnapshot);
    m_bytesAbandoned = 0;

    {
        GCPHASE(ResetAllocators);
        m_objectSpace.resetAllocators();
    }
    
    size_t currentHeapSize = sizeAfterCollect();
    if (Options::gcMaxHeapSize() && currentHeapSize > Options::gcMaxHeapSize())
        HeapStatistics::exitWithFailure();

    m_sizeAfterLastCollect = currentHeapSize;

    // To avoid pathological GC churn in very small and very large heaps, we set
    // the new allocation limit based on the current size of the heap, with a
    // fixed minimum.
    size_t maxHeapSize = max(minHeapSize(m_heapType, m_ramSize), proportionalHeapSize(currentHeapSize, m_ramSize));
    m_bytesAllocatedLimit = maxHeapSize - currentHeapSize;

    m_bytesAllocated = 0;
    double lastGCEndTime = WTF::monotonicallyIncreasingTime();
    m_lastGCLength = lastGCEndTime - lastGCStartTime;

    if (Options::recordGCPauseTimes())
        HeapStatistics::recordGCPauseTime(lastGCStartTime, lastGCEndTime);
    RELEASE_ASSERT(m_operationInProgress == Collection);

    m_operationInProgress = NoOperation;
    JAVASCRIPTCORE_GC_END();

    if (Options::useZombieMode())
        zombifyDeadObjects();

    if (Options::objectsAreImmortal())
        markDeadObjects();

    if (Options::showObjectStatistics())
        HeapStatistics::showObjectStatistics(this);
    
    if (Options::logGC()) {
        double after = currentTimeMS();
        dataLog(after - before, " ms, ", currentHeapSize / 1024, " kb]\n");
    }

#if ENABLE(ALLOCATION_LOGGING)
    dataLogF("JSC GC finishing collection.\n");
#endif
}
コード例 #20
0
void PinchGestureProcessor::Process( const Integration::PinchGestureEvent& pinchEvent )
{
  switch ( pinchEvent.state )
  {
    case Gesture::Started:
    {
      // The pinch gesture should only be sent to the gesture detector which first received it so that
      // it can be told when the gesture ends as well.

      mCurrentPinchEmitters.clear();
      ResetActor();

      HitTestAlgorithm::Results hitTestResults;
      if( HitTest( mStage, pinchEvent.centerPoint, hitTestResults ) )
      {
        // Record the current render-task for Screen->Actor coordinate conversions
        mCurrentRenderTask = hitTestResults.renderTask;

        PinchEventFunctor functor( pinchEvent, *this ); // Sets mCurrentGesturedActor
        GestureDetectorContainer gestureDetectors;
        UpCastContainer<PinchGestureDetector>( mGestureDetectors, gestureDetectors );
        ProcessAndEmit( hitTestResults, gestureDetectors, functor );
      }
      break;
    }

    case Gesture::Continuing:
    case Gesture::Finished:
    case Gesture::Cancelled:
    {
      // Only send subsequent pinch gesture signals if we processed the pinch gesture when it started.
      // Check if actor is still touchable.

      if ( mCurrentGesturedActor )
      {
        if ( mCurrentGesturedActor->IsHittable() && !mCurrentPinchEmitters.empty() && mCurrentRenderTask )
        {
          // Ensure actor is still attached to the emitters, if it is not then remove the emitter.
          PinchGestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPinchEmitters.begin(), mCurrentPinchEmitters.end(), IsNotAttachedFunctor(mCurrentGesturedActor) );
          mCurrentPinchEmitters.erase( endIter, mCurrentPinchEmitters.end() );

          if ( !mCurrentPinchEmitters.empty() )
          {
            Vector2 actorCoords;
            RenderTask& renderTaskImpl( GetImplementation(mCurrentRenderTask) );
            mCurrentGesturedActor->ScreenToLocal( renderTaskImpl, actorCoords.x, actorCoords.y, pinchEvent.centerPoint.x, pinchEvent.centerPoint.y );

            EmitPinchSignal( Dali::Actor(mCurrentGesturedActor), mCurrentPinchEmitters, pinchEvent, actorCoords );
          }
          else
          {
            // If we have no current emitters then clear pinched actor as well.
            ResetActor();
          }

          // Clear current emitters if pinch gesture has ended or been cancelled.
          if ( pinchEvent.state == Gesture::Finished || pinchEvent.state == Gesture::Cancelled )
          {
            mCurrentPinchEmitters.clear();
            ResetActor();
          }
        }
        else
        {
          mCurrentPinchEmitters.clear();
          ResetActor();
        }
      }
      break;
    }

    case Gesture::Clear:
      DALI_ASSERT_ALWAYS( false && "Incorrect state received from Integration layer: Clear\n" );
      break;

    case Gesture::Possible:
      DALI_ASSERT_ALWAYS( false && "Incorrect state received from Integration layer: Possible\n" );
      break;
  }
}
コード例 #21
0
ファイル: Edge.cpp プロジェクト: quano1/Cpp
Edge::Edge(Vertex * * const ppv, Vertex * * const ppw, F const & functor):_ppv(ppv), _ppw(ppw) {
    _weight = functor(**ppv, **ppw);
    hashKey=this->toString();
}
コード例 #22
0
ファイル: JSFunction.cpp プロジェクト: B-Stefan/webkit
static JSValue retrieveArguments(ExecState* exec, JSFunction* functionObj)
{
    RetrieveArgumentsFunctor functor(functionObj);
    exec->iterate(functor);
    return functor.result();
}
コード例 #23
0
ファイル: variant_utils.hpp プロジェクト: wichtounet/eddic
void if_type(Variant& variant, Functor&& functor){
    if(auto* ptr = boost::get<T>(&*variant)){
        functor(*ptr);
    }
}
コード例 #24
0
ファイル: JSFunction.cpp プロジェクト: B-Stefan/webkit
static JSValue retrieveCallerFunction(ExecState* exec, JSFunction* functionObj)
{
    RetrieveCallerFunctionFunctor functor(functionObj);
    exec->iterate(functor);
    return functor.result();
}
コード例 #25
0
    void ImplicitCapillarity<GI, RP, BC, IP>::transportSolve(std::vector<double>& saturation,
                                                             const double /*time*/,
                                                             const typename GI::Vector& gravity,
                                                             const PressureSolution& pressure_sol,
                                                             const Opm::SparseVector<double>& injection_rates) const
    {
        // Start a timer.
	Opm::time::StopWatch clock;
        clock.start();

        // Compute capillary mobilities.
        typedef typename RP::Mobility Mob;
        int num_cells = saturation.size();
        std::vector<Mob> cap_mob(num_cells);
        for (int c = 0; c < num_cells; ++c) {
            Mob& m = cap_mob[c];
            residual_.reservoirProperties().phaseMobility(0, c, saturation[c], m.mob);
            Mob mob2;
            residual_.reservoirProperties().phaseMobility(1, c, saturation[c], mob2.mob);
            Mob mob_tot;
            mob_tot.setToSum(m, mob2);
            Mob mob_totinv;
            mob_totinv.setToInverse(mob_tot);
            m *= mob_totinv;
            m *= mob2;
            ImplicitCapillarityDetails::thresholdMobility(m.mob, 1e-10); // @@TODO: User-set limit.
            // std::cout << m.mob(0,0) << '\n';
        }
        ReservoirPropertyFixedMobility<Mob> capillary_mobilities(cap_mob);

        // Set up boundary conditions.
        BC cap_press_bcs(residual_.boundaryConditions());
        for (int i = 0; i < cap_press_bcs.size(); ++i) {
            if (cap_press_bcs.flowCond(i).isPeriodic()) {
                cap_press_bcs.flowCond(i) = FlowBC(FlowBC::Periodic, 0.0);
            }
        }

        // Compute injection rates from residual.
        std::vector<double> injection_rates_residual(num_cells);
	residual_.computeResidual(saturation, gravity, pressure_sol, injection_rates,
                                  method_viscous_, method_gravity_, false,
                                  injection_rates_residual);
        for (int i = 0; i < num_cells; ++i) {
            injection_rates_residual[i] = -injection_rates_residual[i];
        }

        // Compute capillary pressure.
        // Note that the saturation is just a dummy for this call, since the mobilities are fixed.
        psolver_.solve(capillary_mobilities, saturation, cap_press_bcs, injection_rates_residual,
                       residual_tolerance_, linsolver_verbosity_, linsolver_type_);

        // Solve for constant to change capillary pressure solution by.
        std::vector<double> cap_press(num_cells);
        const PressureSolution& pcapsol = psolver_.getSolution();
        for (CIt c = residual_.grid().cellbegin(); c != residual_.grid().cellend(); ++c) {
            cap_press[c->index()] = pcapsol.pressure(c);
        }
        MatchSaturatedVolumeFunctor<GI, RP> functor(residual_.grid(),
                                                    residual_.reservoirProperties(),
                                                    saturation,
                                                    cap_press);
        double min_cap_press = *std::min_element(cap_press.begin(), cap_press.end());
        double max_cap_press = *std::max_element(cap_press.begin(), cap_press.end());
        double cap_press_range = max_cap_press - min_cap_press;
        double mod_low = 1e100;
        double mod_high = -1e100;
	Opm::bracketZero(functor, 0.0, cap_press_range, mod_low, mod_high);
        const int max_iter = 40;
        const double nonlinear_tolerance = 1e-12;
        int iterations_used = -1;
        typedef Opm::RegulaFalsi<Opm::ThrowOnError> RootFinder;
        double mod_correct = RootFinder::solve(functor, mod_low, mod_high, max_iter, nonlinear_tolerance, iterations_used);
        std::cout << "Moved capillary pressure solution by " << mod_correct << " after "
                  << iterations_used << " iterations." << std::endl;
        // saturation = functor.lastSaturations();
        const std::vector<double>& sat_new = functor.lastSaturations();
        for (int i = 0; i < num_cells; ++i) {
            saturation[i] = (1.0 - update_relaxation_)*saturation[i] + update_relaxation_*sat_new[i];
        }

        // Optionally check and/or clamp results.
	if (check_sat_ || clamp_sat_) {
	    checkAndPossiblyClampSat(saturation);
	}

        // Stop timer and optionally print seconds taken.
        clock.stop();
#ifdef VERBOSE
        std::cout << "Seconds taken by transport solver: " << clock.secsSinceStart() << std::endl;
#endif // VERBOSE
    }
コード例 #26
0
void create_edges( BulkData & mesh, const Selector & element_selector, Part * part_to_insert_new_edges )
{

  //  static size_t next_edge = static_cast<size_t>(mesh.parallel_rank()+1) << 32;
  // NOTE: This is a workaround to eliminate some bad behavior with the equation above when
  //       the #proc is a power of two.  The 256 below is the bin size of the Distributed Index.
  static size_t next_edge = (static_cast<size_t>(mesh.parallel_rank()+1) << 32) + 256 * mesh.parallel_rank();

  mesh.modification_begin();

  {
    {
      edge_map_type        edge_map;
      //populate the edge_map with existing edges
      {
        BucketVector const & edge_buckets = mesh.buckets(stk::topology::EDGE_RANK);

        for (size_t i=0, ie=edge_buckets.size(); i<ie; ++i) {
          Bucket &b = *edge_buckets[i];

          const unsigned num_nodes = b.topology().num_nodes();
          EntityVector edge_nodes(num_nodes);

          for (size_t j=0, je=b.size(); j<je; ++j) {
            Entity edge = b[j];
            Entity const *nodes_rel = b.begin_nodes(j);

            for (unsigned n=0; n<num_nodes; ++n) {
              edge_nodes[n] = nodes_rel[n];
            }

            edge_map[edge_nodes] = edge;
          }

        }
      }

      // create edges and connect them to elements
      {
        BucketVector const& element_buckets = mesh.get_buckets(stk::topology::ELEMENT_RANK, element_selector & mesh.mesh_meta_data().locally_owned_part());

        //create the edges for the elements in each bucket
        for (size_t i=0, e=element_buckets.size(); i<e; ++i) {
          Bucket &b = *element_buckets[i];

          create_edge_impl functor( next_edge, edge_map, b, part_to_insert_new_edges);
          stk::topology::apply_functor< create_edge_impl > apply(functor);
          apply( b.topology() );
        }
      }

      // connect existing faces to edges
      if (mesh.mesh_meta_data().spatial_dimension() == 3u) {

        BucketVector const& face_buckets = mesh.get_buckets(stk::topology::FACE_RANK, element_selector & (mesh.mesh_meta_data().locally_owned_part() | mesh.mesh_meta_data().globally_shared_part()));

        //create the edges for the faces in each bucket
        for (size_t i=0, e=face_buckets.size(); i<e; ++i) {
          Bucket &b = *face_buckets[i];

          connect_face_impl functor(edge_map, b);
          stk::topology::apply_functor< connect_face_impl > apply(functor);
          apply( b.topology() );
        }
      }
    }
  }

  mesh.modification_end( BulkData::MOD_END_COMPRESS_AND_SORT );
}
コード例 #27
0
ファイル: Atom.cpp プロジェクト: kdgerring/sigma
// the atom is a renaming of a
// sbst is a previously computed substitution
// 03/10/2002 Manchester
bool Atom::isRenamingOf (Atom a, Substitution& sbst) const
{
  return functor() == a.functor() &&
         args().isRenamingOf(a.args(), sbst);
} // Literal::isRenamingOf
コード例 #28
0
ファイル: grow_array.hpp プロジェクト: arielzn/lammps
void grow_array( int array_length , int search_length , int print = 1 )
{
  typedef GrowArrayFunctor< ExecSpace > FunctorType ;

  FunctorType functor( array_length , search_length , print );

  typename Kokkos::View<int,ExecSpace>::HostMirror  count = Kokkos::create_mirror_view( functor.m_search_count );
  typename Kokkos::View<int*,ExecSpace>::HostMirror flags = Kokkos::create_mirror_view( functor.m_search_flags );

  // Set at most 'array_length' random bits over the search length.
  for ( int i = 0 ; i < array_length ; ++i ) {
    // 'lrand48()' generates random number between [0..2^31]
    // index = ( lrand48() * search_length ) / ( 2^31 )
    const long int index = ( lrand48() * search_length ) >> 31 ;
    // set the bit within the flags:
    flags( index >> FunctorType::SHIFT ) |= ( 1 << ( index & FunctorType::MASK ) );
  }

  Kokkos::deep_copy( functor.m_search_flags , flags );

  // Each team works on 'functor.m_search_team_chunk' span of the search_length
  Kokkos::TeamPolicy< ExecSpace >
    work( /* #teams */ ( search_length + functor.m_search_team_chunk - 1 ) / functor.m_search_team_chunk
        , /* threads/team */ Kokkos::TeamPolicy< ExecSpace >::team_size_max( functor ) );

  // Fill array:
  Kokkos::parallel_for( work , functor );

  // How much was filled:
  Kokkos::deep_copy( count , functor.m_search_count );

  // Sort array:
  SortView< ExecSpace >( functor.m_search_array , 0 , *count );

  // Mirror the results:
  typename Kokkos::View<int*,ExecSpace>::HostMirror results = Kokkos::create_mirror_view( functor.m_search_array );
  Kokkos::deep_copy( results , functor.m_search_array );

  // Verify results:
  int result_error_count = 0 ;
  int flags_error_count = 0 ;
  for ( int i = 0 ; i < *count ; ++i ) {
    const int index = results(i);
    const int entry = index >> FunctorType::SHIFT ;
    const int bit   = 1 << ( index & FunctorType::MASK );
    const bool flag = 0 != ( flags( entry ) & bit );
    if ( ! flag ) {
      if ( print ) std::cerr << "result( " << i << " : " << index << " )";
      ++result_error_count ;
    }
    flags( entry ) &= ~bit ; // Clear that verified bit
  }

  for ( int i = 0 ; i < int(flags.dimension_0()) ; ++i ) {
    // If any uncleared bits then an error
    if ( flags(i) ) {
      if ( print ) std::cerr << "flags( " << i << " : " << flags(i) << " )" ;
      ++flags_error_count ;
    }
  }

  if ( result_error_count || flags_error_count ) {
    std::cerr << std::endl << "Example::GrowArrayFunctor( " << array_length
              << " , " << search_length
              << " ) result_error_count( " << result_error_count << " )"
              << " ) flags_error_count( " << flags_error_count << " )"
              << std::endl ;
  }
}
コード例 #29
0
ファイル: Debugger.cpp プロジェクト: nickooms/webkit
void Debugger::clearDebuggerRequests(JSGlobalObject* globalObject)
{
    ClearDebuggerRequestsFunctor functor(globalObject);
    m_vm.heap.forEachCodeBlock(functor);
}
コード例 #30
0
	//: Call
	virtual void call(PARAM1 param1, PARAM2 param2, PARAM3 param3, PARAM4 param4, PARAM5 param5) { functor(param1, param2, param3, param4, param5); }