wxString wxChoice::GetString(unsigned int n) const { wxCHECK_MSG( IsValid(n), wxEmptyString, wxT("wxChoice::GetString(): invalid index") ); return m_strings[n] ; }
void CompoundMatrix::MultVectorImpl(Number alpha, const Vector &x, Number beta, Vector &y) const { if (!matrices_valid_) { matrices_valid_ = MatricesValid(); } DBG_ASSERT(matrices_valid_); // The vectors are assumed to be compound Vectors as well const CompoundVector* comp_x = dynamic_cast<const CompoundVector*>(&x); CompoundVector* comp_y = dynamic_cast<CompoundVector*>(&y); #ifndef ALLOW_NESTED // A few sanity checks if (comp_x) { DBG_ASSERT(NComps_Cols()==comp_x->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } if (comp_y) { DBG_ASSERT(NComps_Rows()==comp_y->NComps()); } else { DBG_ASSERT(NComps_Rows() == 1); } #endif if (comp_x) { if (NComps_Cols()!=comp_x->NComps()) { comp_x = NULL; } } if (comp_y) { if (NComps_Rows()!=comp_y->NComps()) { comp_y = NULL; } } // Take care of the y part of the addition if ( beta!=0.0 ) { y.Scal(beta); } else { y.Set(0.0); // In case y hasn't been initialized yet } for ( Index irow = 0; irow < NComps_Rows(); irow++ ) { SmartPtr<Vector> y_i; if (comp_y) { y_i = comp_y->GetCompNonConst(irow); } else { y_i = &y; } DBG_ASSERT(IsValid(y_i)); for ( Index jcol = 0; jcol < NComps_Cols(); jcol++ ) { if ( (owner_space_->Diagonal() && irow == jcol) || (!owner_space_->Diagonal() && ConstComp(irow,jcol)) ) { SmartPtr<const Vector> x_j; if (comp_x) { x_j = comp_x->GetComp(jcol); } else if (NComps_Cols() == 1) { x_j = &x; } DBG_ASSERT(IsValid(x_j)); ConstComp(irow, jcol)->MultVector(alpha, *x_j, 1., *y_i); } } } }
bool CFantomAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); }
inline SmartPtr<SymMatrix> SymScaledMatrix::GetUnscaledMatrixNonConst() { DBG_ASSERT(IsValid(nonconst_matrix_)); ObjectChanged(); return nonconst_matrix_; }
// Specialized method (overloaded from IpMatrix) void CompoundMatrix::AddMSinvZImpl(Number alpha, const Vector& S, const Vector& Z, Vector& X) const { // The vectors are assumed to be compound Vectors as well (unless they // are assumed to consist of only one component const CompoundVector* comp_S = dynamic_cast<const CompoundVector*>(&S); const CompoundVector* comp_Z = dynamic_cast<const CompoundVector*>(&Z); CompoundVector* comp_X = dynamic_cast<CompoundVector*>(&X); #ifndef ALLOW_NESTED // A few sanity checks for sizes if (comp_S) { DBG_ASSERT(NComps_Cols()==comp_S->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } if (comp_Z) { DBG_ASSERT(NComps_Cols()==comp_Z->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } if (comp_X) { DBG_ASSERT(NComps_Rows()==comp_X->NComps()); } else { DBG_ASSERT(NComps_Rows() == 1); } #endif if (comp_S) { if (NComps_Cols()!=comp_S->NComps()) { comp_S = NULL; } } if (comp_Z) { if (NComps_Cols()!=comp_Z->NComps()) { comp_Z = NULL; } } if (comp_X) { if (NComps_Rows()!=comp_X->NComps()) { comp_X = NULL; } } for ( Index irow = 0; irow < NComps_Rows(); irow++ ) { SmartPtr<Vector> X_i; if (comp_X) { X_i = comp_X->GetCompNonConst(irow); } else { X_i = &X; } DBG_ASSERT(IsValid(X_i)); for ( Index jcol = 0; jcol < NComps_Cols(); jcol++ ) { if ( (owner_space_->Diagonal() && irow == jcol) || (!owner_space_->Diagonal() && ConstComp(irow, jcol)) ) { SmartPtr<const Vector> S_j; if (comp_S) { S_j = comp_S->GetComp(jcol); } else { S_j = &S; } DBG_ASSERT(IsValid(S_j)); SmartPtr<const Vector> Z_j; if (comp_Z) { Z_j = comp_Z->GetComp(jcol); } else { Z_j = &Z; } DBG_ASSERT(IsValid(Z_j)); ConstComp(irow, jcol)->AddMSinvZ(alpha, *S_j, *Z_j, *X_i); } } } }
CFile::FILESIZE CWinFile::GetPos() const { ASSERT(IsValid()); return _telli64(m_hFile); }
void APlayerHUD::DrawMinimap() { ARealmPlayerController* pc = Cast<ARealmPlayerController>(PlayerOwner); if (!IsValid(pc) || (IsValid(pc) && !IsValid(pc->GetPlayerCharacter())) || !IsValid(gameMinimap)) return; float trueNorth, playerHeading, actualMapRange; FVector2D playerPos, displayPlayerPos, startPos; const APlayerHUD* defaultHUD = GetDefault<APlayerHUD>(); if (!IsValid(defaultHUD)) return; mapPosition.X = defaultHUD->mapPosition.X * Canvas->ClipX; mapPosition.Y = defaultHUD->mapPosition.Y * Canvas->ClipY; actualMapRange = FMath::Max(gameMinimap->mapSizeMax.X - gameMinimap->mapSizeMin.X, gameMinimap->mapSizeMax.Y - gameMinimap->mapSizeMin.Y); playerPos = FVector2D::ZeroVector; FVector pp = pc->GetPlayerCharacter()->GetActorLocation(); pp.X = pp.X / actualMapRange; pp.Y = pp.Y / actualMapRange; playerPos.X = pp.X; playerPos.Y = pp.Y; trueNorth = gameMinimap->GetRadianHeading(); playerHeading = GetUnitHeading(pc->GetPlayerCharacter()); displayPlayerPos.X = playerPos.Size() * FMath::Cos(FMath::Atan2(playerPos.Y, playerPos.X)); displayPlayerPos.Y = playerPos.Size() * FMath::Sin(FMath::Atan2(playerPos.Y, playerPos.X)); startPos.X = displayPlayerPos.X; startPos.Y = displayPlayerPos.Y; //draw the back Canvas->SetDrawColor(FColor::Black); Canvas->K2_DrawMaterial(gameMinimap->mapBackground, mapPosition, FVector2D(mapDimensions / 1920.f * Canvas->ClipX, mapDimensions / 1080.f * Canvas->ClipY), FVector2D::ZeroVector); //draw map back //draw this player Canvas->SetDrawColor(FColor::Yellow); FVector2D pdp = FVector2D(mapPosition.X + mapDimensions * (displayPlayerPos.X), mapPosition.Y + mapDimensions * (displayPlayerPos.Y)); Canvas->K2_DrawBox(pdp, FVector2D(32.f / 1920.f * Canvas->ClipX, 32.f / 1080.f * Canvas->ClipY)); //draw other units for (TActorIterator<AGameCharacter> unititr(GetWorld()); unititr; ++unititr) { AGameCharacter* gc = (*unititr); if (gc->IsAlive() && !gc->bHidden) //draw visible and alive units { playerHeading = GetUnitHeading(gc); pp = gc->GetActorLocation(); pp.X = pp.X / actualMapRange; pp.Y = pp.Y / actualMapRange; displayPlayerPos.X = pp.Size() * FMath::Cos(FMath::Atan2(pp.Y, pp.X)); displayPlayerPos.Y = pp.Size() * FMath::Sin(FMath::Atan2(pp.Y, pp.X)); Canvas->SetDrawColor(FColor::Green); pdp = FVector2D(mapPosition.X + mapDimensions * (displayPlayerPos.X), mapPosition.Y + mapDimensions * (displayPlayerPos.Y)); Canvas->K2_DrawBox(pdp, FVector2D(20.f / 1920.f * Canvas->ClipX, 20.f / 1080.f * Canvas->ClipY)); } } }
bool PngImage::Save(FILE *pStream) { if (pStream && IsValid()) { bool success = false; png_structp pPngStruct = NULL; png_infop pPngInfo = NULL; int bpp = IMAGE_BPP_8; int colorType = PNG_COLOR_TYPE_RGB; png_bytep *pImageRows = NULL; uint rowSize; uint offset = 0; //create png write struct pPngStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pPngStruct) { //png struct allocation failed goto Exit_Save; } //create png info struct pPngInfo = png_create_info_struct(pPngStruct); if (!pPngInfo) { //png info allocation failed goto Exit_Save; } //required for png library use if (setjmp(pPngStruct->jmpbuf)) { //handle png write error goto Exit_Save; } //initialize png io png_init_io(pPngStruct, pStream); //use paeth filtering png_set_filter(pPngStruct, 0, PNG_FILTER_PAETH); //set compression level png_set_compression_level(pPngStruct, Z_BEST_COMPRESSION); //write png image info header png_set_IHDR(pPngStruct, pPngInfo, m_width, m_height, bpp, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(pPngStruct, pPngInfo); //allocate space for image row pointers pImageRows = new png_bytep [m_height]; if (!pImageRows) { //allocation failed goto Exit_Save; } //set individual row pointers to correct offsets rowSize = png_get_rowbytes(pPngStruct, pPngInfo); for (uint i = 0; i < m_height; ++i) { pImageRows[i] = m_pImageData + offset; offset += rowSize; } //write image data png_write_image(pPngStruct, pImageRows); png_write_end(pPngStruct, NULL); //image successfully saved success = true; Exit_Save: delete pImageRows; if (pPngStruct && pPngInfo) { //free png struct and png info png_destroy_write_struct(&pPngStruct, &pPngInfo); } else if (pPngStruct) { //free png struct only png_destroy_write_struct(&pPngStruct, NULL); } return success; } return false; }
Zip::Zip(Control &control_, char *zipfile_name) : control(control_), magic(0), zipbuffer(NULL) { #ifdef UNIX_FILE_SYSTEM zipfile = SystemFopen(zipfile_name, "rb"); if (zipfile) { int rc = fseek(zipfile, -END_SIZE, SEEK_END); if (rc == 0) { zipbuffer = new char[END_SIZE]; buffer_ptr = zipbuffer; SystemFread(buffer_ptr, sizeof(char), END_SIZE, zipfile); magic = GetU4(); } } #elif defined(WIN32_FILE_SYSTEM) zipfile = CreateFile(zipfile_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL); if (zipfile != INVALID_HANDLE_VALUE) { mapfile = CreateFileMapping(zipfile, NULL, PAGE_READONLY, 0, 0, NULL); zipbuffer = (mapfile == INVALID_HANDLE_VALUE ? NULL : (char *) MapViewOfFile(mapfile, FILE_MAP_READ, 0, 0, 0) ); if (zipbuffer) { buffer_ptr = &zipbuffer[GetFileSize(zipfile, NULL) - END_SIZE]; magic = GetU4(); } } #endif // The following was posted to the dev list, but was just // too good to not put in here, the next person to have to // deal with this crap will appreciate it. -=Chris // // From: Mo DeJong <*****@*****.**> // // Ode to a zip file: // // I can't read it forwards // I can't read it backwards // I must know where to begin // so I need to look in the middle // to find the middle, I must know the end // but I don't know where that is, so I guess // // ------------------------------------------------- // This may or may not be a valid zip file. The zip file might have // a file comment so we can't be sure where the END header is located. // We check for the LOC header at byte 0 to make sure this is a valid // zip file and then scan over the file backwards in search of the // END header. if (zipbuffer != NULL && ! IsValid()) { u4 sig = 0; #ifdef UNIX_FILE_SYSTEM int res = fseek(zipfile, 0, SEEK_SET); assert(res == 0); char *tmpbuffer = new char[LOC_SIZE]; buffer_ptr = tmpbuffer; SystemFread(buffer_ptr, sizeof(char), LOC_SIZE, zipfile); sig = GetU4(); delete [] tmpbuffer; buffer_ptr = NULL; if (sig == LOC_SIG) { int block_size = 8192; tmpbuffer = new char[block_size]; char *holdbuffer = new char[8]; char *index_ptr; res = fseek(zipfile, 0, SEEK_END); assert(res == 0); long zip_file_size = ftell(zipfile); int num_loops = zip_file_size / block_size; magic = 0; for (; magic == 0 && num_loops >= 0 ; num_loops--) { if ((ftell(zipfile) - block_size) < 0) { block_size = ftell(zipfile); res = fseek(zipfile, 0L, SEEK_SET); } else { res = fseek(zipfile, -block_size, SEEK_CUR); } assert(res == 0); SystemFread(tmpbuffer, sizeof(char), block_size, zipfile); res = fseek(zipfile, -block_size, SEEK_CUR); // undo fread assert(res == 0); for (index_ptr = tmpbuffer + block_size - 1; index_ptr >= tmpbuffer; index_ptr--) { if (*index_ptr == 'P') { // Check for header signature that spans buffer int span = (tmpbuffer + block_size) - index_ptr; if (span < 4) { memmove(holdbuffer+span, holdbuffer, 3); memmove(holdbuffer, index_ptr, span); buffer_ptr = holdbuffer; } else { buffer_ptr = index_ptr; } sig = GetU4(); if (sig == END_SIG) { // Found the END header, put it in zipbuffer. buffer_ptr = zipbuffer; fseek(zipfile, block_size-span, SEEK_CUR); SystemFread(buffer_ptr, sizeof(char), END_SIZE, zipfile); magic = GetU4(); break; } } } // Copy first 3 bytes into holdbuffer in case sig spans holdbuffer[0] = tmpbuffer[0]; holdbuffer[1] = tmpbuffer[1]; holdbuffer[2] = tmpbuffer[2]; } delete [] tmpbuffer; delete [] holdbuffer; } #elif defined(WIN32_FILE_SYSTEM) buffer_ptr = &zipbuffer[0]; sig = GetU4(); if (sig == LOC_SIG) { buffer_ptr = &zipbuffer[GetFileSize(zipfile, NULL) - END_SIZE]; for ( ; buffer_ptr >= zipbuffer; buffer_ptr--) { if (*buffer_ptr == 'P') { sig = GetU4(); if (sig == END_SIG) { magic = sig; break; } else buffer_ptr -= 4; } } } #endif } ReadDirectory(); }
FReply FKismetDelegateDragDropAction::DroppedOnPanel(const TSharedRef< SWidget >& Panel, FVector2D ScreenPosition, FVector2D GraphPosition, UEdGraph& Graph) { if(IsValid()) { FNodeConstructionParams NewNodeParams; NewNodeParams.Property = GetVariableProperty(); const UClass* VariableSourceClass = CastChecked<UClass>(NewNodeParams.Property->GetOuter()); const UBlueprint* DropOnBlueprint = FBlueprintEditorUtils::FindBlueprintForGraph(&Graph); NewNodeParams.Graph = &Graph; NewNodeParams.GraphPosition = GraphPosition; NewNodeParams.bSelfContext = VariableSourceClass == NULL || DropOnBlueprint->SkeletonGeneratedClass->IsChildOf(VariableSourceClass);; NewNodeParams.AnalyticCallback = AnalyticCallback; FMenuBuilder MenuBuilder(true, NULL); const FText VariableNameText = FText::FromName( VariableName ); MenuBuilder.BeginSection("BPDelegateDroppedOn", VariableNameText ); { const bool bBlueprintCallable = NewNodeParams.Property->HasAllPropertyFlags(CPF_BlueprintCallable); if(bBlueprintCallable) { MenuBuilder.AddMenuEntry( LOCTEXT("CallDelegate", "Call"), FText::Format( LOCTEXT("CallDelegateToolTip", "Call {0}"), VariableNameText ), FSlateIcon(), FUIAction( FExecuteAction::CreateStatic(&FKismetDelegateDragDropAction::MakeMCDelegateNode<UK2Node_CallDelegate>,NewNodeParams) )); } if(NewNodeParams.Property->HasAllPropertyFlags(CPF_BlueprintAssignable)) { MenuBuilder.AddMenuEntry( LOCTEXT("AddDelegate", "Bind"), FText::Format( LOCTEXT("AddDelegateToolTip", "Bind event to {0}"), VariableNameText ), FSlateIcon(), FUIAction( FExecuteAction::CreateStatic(&FKismetDelegateDragDropAction::MakeMCDelegateNode<UK2Node_AddDelegate>,NewNodeParams) )); MenuBuilder.AddMenuEntry( LOCTEXT("AddRemove", "Unbind"), FText::Format( LOCTEXT("RemoveDelegateToolTip", "Unbind event from {0}"), VariableNameText ), FSlateIcon(), FUIAction( FExecuteAction::CreateStatic(&FKismetDelegateDragDropAction::MakeMCDelegateNode<UK2Node_RemoveDelegate>, NewNodeParams) )); MenuBuilder.AddMenuEntry( LOCTEXT("AddClear", "Unbind all"), FText::Format( LOCTEXT("ClearDelegateToolTip", "Unbind all events from {0}"), VariableNameText ), FSlateIcon(), FUIAction( FExecuteAction::CreateStatic(&FKismetDelegateDragDropAction::MakeMCDelegateNode<UK2Node_ClearDelegate>, NewNodeParams) )); const UEdGraphSchema_K2* Schema = GetDefault<UEdGraphSchema_K2>(); check(Schema); const EGraphType GraphType = Schema->GetGraphType(&Graph); const bool bSupportsEventGraphs = (DropOnBlueprint && FBlueprintEditorUtils::DoesSupportEventGraphs(DropOnBlueprint)); const bool bAllowEvents = ((GraphType == GT_Ubergraph) && bSupportsEventGraphs); if(bAllowEvents) { MenuBuilder.AddMenuEntry( LOCTEXT("AddEvent", "Event"), FText::Format( LOCTEXT("EventDelegateToolTip", "Create event with the {0} signature"), VariableNameText ), FSlateIcon(), FUIAction( FExecuteAction::CreateStatic(&FKismetDelegateDragDropAction::MakeEvent, NewNodeParams) )); MenuBuilder.AddMenuEntry( LOCTEXT("AssignEvent", "Assign"), LOCTEXT("AssignDelegateToolTip", "Create and bind event"), FSlateIcon(), FUIAction( FExecuteAction::CreateStatic(&FKismetDelegateDragDropAction::AssignEvent, NewNodeParams) )); } } } MenuBuilder.EndSection(); FSlateApplication::Get().PushMenu(Owner, MenuBuilder.MakeWidget(), ScreenPosition, FPopupTransitionEffect( FPopupTransitionEffect::ContextMenu)); } return FReply::Handled(); }
bool PngImage::Load(FILE *pStream) { if (pStream && !IsValid()) { bool success = false; ubyte aPngHeader[PNG_IMAGE_HEADER_SIZE]; png_structp pPngStruct = NULL; png_infop pPngInfo = NULL; //float gamma = 0.0; uint rowSize; ubyte *pImageData = NULL; png_bytep *pImageRows = NULL; uint offset = 0; png_uint_32 width = 0; png_uint_32 height = 0; int bpp = 0; int colorType = 0; //check png signature if (sizeof(aPngHeader) != fread(aPngHeader, 1, sizeof(aPngHeader), pStream)) { //read failed goto Exit_Load; } if (!png_check_sig(aPngHeader, sizeof(aPngHeader))) { //file is not a png image goto Exit_Load; } //create png read struct pPngStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pPngStruct) { //png struct allocation failed goto Exit_Load; } //create png info struct pPngInfo = png_create_info_struct(pPngStruct); if (!pPngInfo) { //png info allocation failed goto Exit_Load; } //required for png library use if (setjmp(pPngStruct->jmpbuf)) { //handle png read error goto Exit_Load; } //initialize png io png_init_io(pPngStruct, pStream); //set offset into the file since png header has been already read png_set_sig_bytes(pPngStruct, sizeof(aPngHeader)); //read png image info header png_read_info(pPngStruct, pPngInfo); png_get_IHDR(pPngStruct, pPngInfo, &width, &height, &bpp, &colorType, NULL, NULL, NULL); DbgMessage("Image %ux%ux%ubpp", width, height, bpp); //filter out unsupported images if (bpp < PNG_IMAGE_MIN_BPP || bpp > PNG_IMAGE_MAX_BPP) { goto Exit_Load; } //convert palette images to rgb if (PNG_COLOR_TYPE_PALETTE == colorType) { png_set_expand(pPngStruct); } //convert low-bpp images to 8 bpp if (bpp < IMAGE_BPP_8) { png_set_expand(pPngStruct); } //strip alpha channel if ((colorType & PNG_COLOR_MASK_ALPHA) || png_get_valid(pPngStruct, pPngInfo, PNG_INFO_tRNS)) { png_set_strip_alpha(pPngStruct); } //strip 16 bpp images down to 8 bpp if (IMAGE_BPP_16 == bpp) { png_set_strip_16(pPngStruct); } //convert grayscale images to rgb if (PNG_COLOR_TYPE_GRAY == colorType || PNG_COLOR_TYPE_GRAY_ALPHA == colorType) { //png_set_expand(pPngStruct); png_set_gray_to_rgb(pPngStruct); } //perform gamma correction if gamma is preset /*if (png_get_gAMA(pPngStruct, pPngInfo, &gamma)) { //png_set_gamma(pPngStruct, ???, gamma); }*/ //update image info png_read_update_info(pPngStruct, pPngInfo); //allocate space for image row offsets rowSize = png_get_rowbytes(pPngStruct, pPngInfo); pImageData = new ubyte [height * rowSize]; if (!pImageData) { //allocation failed goto Exit_Load; } //allocate space for image row pointers pImageRows = new png_bytep [height]; if (!pImageRows) { //allocation failed goto Exit_Load; } //set individual row pointers to correct offsets for (uint index = 0; index < height; ++index) { pImageRows[index] = pImageData + offset; offset += rowSize; } //read image data png_read_image(pPngStruct, pImageRows); png_read_end(pPngStruct, NULL); //set image properties m_pImageData = pImageData; m_width = static_cast<uint>(width); m_height = static_cast<uint>(height); m_bpp = static_cast<uint>(bpp); //image successfully loaded success = true; Exit_Load: delete pImageRows; if (pPngStruct && pPngInfo) { //free png struct and png info png_destroy_read_struct(&pPngStruct, &pPngInfo, NULL); } else if (pPngStruct) { //free png struct only png_destroy_read_struct(&pPngStruct, NULL, NULL); } if (!success) { delete pImageData; } return success; } return false; }
// Runs calculations on friction component, applies friction force to effected component and returns reaction forces(forces that can effect track or a wheel) void UMMTFrictionComponent::ApplyFriction(const FVector& ContactPointLocation, const FVector& ContactPointNormal, const FVector& InducedVelocity, const FVector& PreNormalForceAtPoint, const EPhysicalSurface& PhysicalSurface, const float& NumberOfContactPoints, const float& DeltaTime, FVector& NormalizedReactionForce, FVector& RollingFrictionForce) { // Gather stats SCOPE_CYCLE_COUNTER(STAT_MMTFrictionApply); float NormalForceAtContactPoint = PreNormalForceAtPoint.ProjectOnTo(ContactPointNormal).Size(); // Check if Effected Component Mesh reference is valid and escape early otherwise if (!IsValid(EffectedComponentMesh)) { GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, FString::Printf(TEXT("%s->%s component's EffectedComponentMesh reference is invalid!"), *GetOwner()->GetName(), *GetName())); UE_LOG(LogTemp, Warning, TEXT("%s->%s component's EffectedComponentMesh reference is invalid!"), *GetOwner()->GetName(), *GetName()); NormalizedReactionForce = FVector::ZeroVector; RollingFrictionForce = FVector::ZeroVector; return; } //Find relative velocity of the friction surface and ground/another object at point FVector RelativeVelocityAtPoint = EffectedComponentMesh->GetPhysicsLinearVelocityAtPoint(ContactPointLocation) + InducedVelocity + FrictionSurfaceVelocity; RelativeVelocityAtPoint = RelativeVelocityAtPoint.VectorPlaneProject(RelativeVelocityAtPoint, ContactPointNormal); //filter out oscillations when vehicle is standing still but friction overshoots RelativeVelocityAtPoint = (PrevRelativeVelocityAtPoint + RelativeVelocityAtPoint) * 0.5; PrevRelativeVelocityAtPoint = RelativeVelocityAtPoint; // early exit if velocity is too low to consider as vehicle most likely standing still if (RelativeVelocityAtPoint.Size() < 1.0f) { NormalizedReactionForce = FVector::ZeroVector; RollingFrictionForce = FVector::ZeroVector; return; } //Calculate static and kinetic friction coefficients, taking into account velocity direction and friction ellipse float MuStatic; float MuKinetic; UMMTBPFunctionLibrary::GetMuFromFrictionElipse(RelativeVelocityAtPoint.GetSafeNormal(), ReferenceFrameTransform.TransformVector(FVector(1.0f, 1.0f, 1.0f)), MuXStatic, MuXKinetic, MuYStatic, MuYKinetic, MuStatic, MuKinetic); //Calculate "stopping force" which is amount of force necessary to completely remove velocity of the object FVector StoppingForce = ((RelativeVelocityAtPoint * (-1.0f) * EffectedComponentMesh->GetMass()) / DeltaTime) / NumberOfContactPoints; //Static friction threshold float MuStaticByLoad = NormalForceAtContactPoint * MuStatic; //Friction Force that will be applied to effected mesh component FVector ApplicationForce; if (StoppingForce.Size() >= MuStaticByLoad) { ApplicationForce = StoppingForce.GetClampedToSize(0.0f, NormalForceAtContactPoint * MuKinetic); if (IsDebugMode) { DrawDebugString(GetWorld(), ContactPointLocation, FString("Kinetic Friction"), nullptr, FColor::Magenta, 0.0f, false); } } else { ApplicationForce = StoppingForce.GetClampedToSize(0.0f, MuStaticByLoad); if (IsDebugMode) { DrawDebugString(GetWorld(), ContactPointLocation, FString("Static Friction"), nullptr, FColor::Red, 0.0f, false); } } //Apply friction force UMMTBPFunctionLibrary::MMTAddForceAtLocationComponent(EffectedComponentMesh, ApplicationForce, ContactPointLocation); //Calculate Reaction force NormalizedReactionForce = (ApplicationForce * (-1.0f)) / EffectedComponentMesh->GetMass(); //Calculate Rolling Friction float RollingFrictionCoefficient = FPhysicalSurfaceRollingFrictionCoefficient().RollingFrictionCoefficient; for (int32 i = 0; i < PhysicsSurfaceResponse.Num(); i++) { if (PhysicsSurfaceResponse[i].PhysicalSurface == PhysicalSurface) { RollingFrictionCoefficient = PhysicsSurfaceResponse[i].RollingFrictionCoefficient; break; } } RollingFrictionForce = RelativeVelocityAtPoint.GetSafeNormal() * NormalForceAtContactPoint * RollingFrictionCoefficient; if (IsDebugMode) { DrawDebugLine(GetWorld(), ContactPointLocation, ContactPointLocation + ApplicationForce * 0.005f, FColor::Yellow, false, 0.0f, 0, 3.0f); DrawDebugLine(GetWorld(), ContactPointLocation, ContactPointLocation + RollingFrictionForce * 0.005f, FColor::Green, false, 0.0f, 0, 3.0f); DrawDebugString(GetWorld(), ContactPointLocation+FVector(0.0f, 0.0f, 50.0f), (PhysicalSurfaceEnum ? PhysicalSurfaceEnum->GetEnumName(PhysicalSurface) : FString("<Invalid Enum>")), nullptr, FColor::Cyan, 0.0f, false); //DrawDebugString(GetWorld(), ContactPointLocation + FVector(0.0f, 0.0f, 25.0f), FString("Normal Force: ") + FString::SanitizeFloat(NormalForceAtContactPoint), nullptr, FColor::Turquoise, 0.0f, false); } }
void * wxChoice::DoGetItemClientData(unsigned int n) const { wxCHECK_MSG( IsValid(n), NULL, wxT("wxChoice::DoGetClientData: invalid index") ); return (void *)m_datas[n]; }
// ---------------------------------------------------------------------------- // client data // ---------------------------------------------------------------------------- void wxChoice::DoSetItemClientData(unsigned int n, void* clientData) { wxCHECK_RET( IsValid(n), wxT("wxChoice::DoSetItemClientData: invalid index") ); m_datas[n] = (char*)clientData ; }
CFile::FILESIZE CWinFile::GetSize() const { ASSERT(IsValid()); return _filelengthi64(m_hFile); }
bool wxRegExImpl::Compile(const wxString& expr, int flags) { Reinit(); #ifdef WX_NO_REGEX_ADVANCED # define FLAVORS wxRE_BASIC #else # define FLAVORS (wxRE_ADVANCED | wxRE_BASIC) wxASSERT_MSG( (flags & FLAVORS) != FLAVORS, wxT("incompatible flags in wxRegEx::Compile") ); #endif wxASSERT_MSG( !(flags & ~(FLAVORS | wxRE_ICASE | wxRE_NOSUB | wxRE_NEWLINE)), wxT("unrecognized flags in wxRegEx::Compile") ); // translate our flags to regcomp() ones int flagsRE = 0; if ( !(flags & wxRE_BASIC) ) { #ifndef WX_NO_REGEX_ADVANCED if (flags & wxRE_ADVANCED) flagsRE |= REG_ADVANCED; else #endif flagsRE |= REG_EXTENDED; } if ( flags & wxRE_ICASE ) flagsRE |= REG_ICASE; if ( flags & wxRE_NOSUB ) flagsRE |= REG_NOSUB; if ( flags & wxRE_NEWLINE ) flagsRE |= REG_NEWLINE; // compile it #ifdef WXREGEX_USING_BUILTIN bool conv = true; // FIXME-UTF8: use wc_str() after removing ANSI build int errorcode = wx_re_comp(&m_RegEx, expr.c_str(), expr.length(), flagsRE); #else // FIXME-UTF8: this is potentially broken, we shouldn't even try it // and should always use builtin regex library (or PCRE?) const wxWX2MBbuf conv = expr.mbc_str(); int errorcode = conv ? regcomp(&m_RegEx, conv, flagsRE) : REG_BADPAT; #endif if ( errorcode ) { wxLogError(_("Invalid regular expression '%s': %s"), expr.c_str(), GetErrorMsg(errorcode, !conv).c_str()); m_isCompiled = false; } else // ok { // don't allocate the matches array now, but do it later if necessary if ( flags & wxRE_NOSUB ) { // we don't need it at all m_nMatches = 0; } else { // we will alloc the array later (only if really needed) but count // the number of sub-expressions in the regex right now // there is always one for the whole expression m_nMatches = 1; // and some more for bracketed subexperessions for ( const wxChar *cptr = expr.c_str(); *cptr; cptr++ ) { if ( *cptr == wxT('\\') ) { // in basic RE syntax groups are inside \(...\) if ( *++cptr == wxT('(') && (flags & wxRE_BASIC) ) { m_nMatches++; } } else if ( *cptr == wxT('(') && !(flags & wxRE_BASIC) ) { // we know that the previous character is not an unquoted // backslash because it would have been eaten above, so we // have a bare '(' and this indicates a group start for the // extended syntax. '(?' is used for extensions by perl- // like REs (e.g. advanced), and is not valid for POSIX // extended, so ignore them always. if ( cptr[1] != wxT('?') ) m_nMatches++; } } } m_isCompiled = true; } return IsValid(); }
CFile::ERRCODE CWinFile::SetSize(FILESIZE iSize) { ASSERT(IsValid()); int iRes = _chsize(m_hFile, (long) iSize); return (iRes < 0) ? (ERRCODE) errno : 0; }
int wxRegExImpl::Replace(wxString *text, const wxString& replacement, size_t maxMatches) const { wxCHECK_MSG( text, wxNOT_FOUND, wxT("NULL text in wxRegEx::Replace") ); wxCHECK_MSG( IsValid(), wxNOT_FOUND, wxT("must successfully Compile() first") ); // the input string #ifndef WXREGEX_CONVERT_TO_MB const wxChar *textstr = text->c_str(); size_t textlen = text->length(); #else const wxWX2MBbuf textstr = WXREGEX_CHAR(*text); if (!textstr) { wxLogError(_("Failed to find match for regular expression: %s"), GetErrorMsg(0, true).c_str()); return 0; } size_t textlen = strlen(textstr); text->clear(); #endif // the replacement text wxString textNew; // the result, allow 25% extra wxString result; result.reserve(5 * textlen / 4); // attempt at optimization: don't iterate over the string if it doesn't // contain back references at all bool mayHaveBackrefs = replacement.find_first_of(wxT("\\&")) != wxString::npos; if ( !mayHaveBackrefs ) { textNew = replacement; } // the position where we start looking for the match size_t matchStart = 0; // number of replacement made: we won't make more than maxMatches of them // (unless maxMatches is 0 which doesn't limit the number of replacements) size_t countRepl = 0; // note that "^" shouldn't match after the first call to Matches() so we // use wxRE_NOTBOL to prevent it from happening while ( (!maxMatches || countRepl < maxMatches) && Matches( #ifndef WXREGEX_CONVERT_TO_MB textstr + matchStart, #else textstr.data() + matchStart, #endif countRepl ? wxRE_NOTBOL : 0 WXREGEX_IF_NEED_LEN(textlen - matchStart)) ) { // the string possibly contains back references: we need to calculate // the replacement text anew after each match if ( mayHaveBackrefs ) { mayHaveBackrefs = false; textNew.clear(); textNew.reserve(replacement.length()); for ( const wxChar *p = replacement.c_str(); *p; p++ ) { size_t index = (size_t)-1; if ( *p == wxT('\\') ) { if ( wxIsdigit(*++p) ) { // back reference wxChar *end; index = (size_t)wxStrtoul(p, &end, 10); p = end - 1; // -1 to compensate for p++ in the loop } //else: backslash used as escape character } else if ( *p == wxT('&') ) { // treat this as "\0" for compatbility with ed and such index = 0; } // do we have a back reference? if ( index != (size_t)-1 ) { // yes, get its text size_t start, len; if ( !GetMatch(&start, &len, index) ) { wxFAIL_MSG( wxT("invalid back reference") ); // just eat it... } else { textNew += wxString( #ifndef WXREGEX_CONVERT_TO_MB textstr #else textstr.data() #endif + matchStart + start, *wxConvCurrent, len); mayHaveBackrefs = true; } } else // ordinary character { textNew += *p; } } } size_t start, len; if ( !GetMatch(&start, &len) ) { // we did have match as Matches() returned true above! wxFAIL_MSG( wxT("internal logic error in wxRegEx::Replace") ); return wxNOT_FOUND; } // an insurance against implementations that don't grow exponentially // to ensure building the result takes linear time if (result.capacity() < result.length() + start + textNew.length()) result.reserve(2 * result.length()); #ifndef WXREGEX_CONVERT_TO_MB result.append(*text, matchStart, start); #else result.append(wxString(textstr.data() + matchStart, *wxConvCurrent, start)); #endif matchStart += start; result.append(textNew); countRepl++; matchStart += len; } #ifndef WXREGEX_CONVERT_TO_MB result.append(*text, matchStart, wxString::npos); #else result.append(wxString(textstr.data() + matchStart, *wxConvCurrent)); #endif *text = result; return countRepl; }
CFile::ERRCODE CWinFile::SetPos(FILESIZE iPos) { ASSERT(IsValid()); FILESIZE iRes = _lseeki64(m_hFile, iPos, SEEK_SET); return (iRes < 0) ? (ERRCODE) errno : 0; }
bool wxRegEx::GetMatch(size_t *start, size_t *len, size_t index) const { wxCHECK_MSG( IsValid(), false, wxT("must successfully Compile() first") ); return m_impl->GetMatch(start, len, index); }
//======================================================================= // function: PreparePaveBlocks // purpose: //======================================================================= void NMTTools_CheckerSI::PreparePaveBlocks(const Standard_Integer nE) { myIsDone=Standard_False; // // char buf[32]={"SR"}; Standard_Boolean bIsValid; Standard_Integer nV1, nV2, iErr; Standard_Real aT1, aT2; TopoDS_Edge aE; TopoDS_Vertex aV1, aV2; // BOPTools_ListOfPaveBlock& aLPB=mySplitShapesPool(myDS->RefEdge(nE)); // Edge aE=TopoDS::Edge(myDS->Shape(nE)); if (BRep_Tool::Degenerated(aE)) { myIsDone=Standard_True; return; } // BOPTools_PaveSet& aPS=myPavePool(myDS->RefEdge(nE)); BOPTools_PaveBlockIterator aPBIt(nE, aPS); for (; aPBIt.More(); aPBIt.Next()) { BOPTools_PaveBlock& aPB=aPBIt.Value(); const IntTools_Range& aRange=aPB.Range(); // const BOPTools_Pave& aPave1=aPB.Pave1(); nV1=aPave1.Index(); aV1=TopoDS::Vertex(myDS->Shape(nV1)); aT1=aPave1.Param(); // const BOPTools_Pave& aPave2=aPB.Pave2(); nV2=aPave2.Index(); aV2=TopoDS::Vertex(myDS->Shape(nV2)); aT2=aPave2.Param(); // bIsValid=Standard_True; if (nV1==nV2) { bIsValid=IsValid(aE, aV1, aT1, aT2); if (!bIsValid) { //printf(" pb SR: nV nE: %d nV1:( %d %15.10lf ) nV2:( %d %15.10lf )\n", nE, nV1, aT1, nV2, aT2); myStopStatus=1; } } // IntTools_ShrunkRange aSR (aE, aV1, aV2, aRange, myContext); iErr=aSR.ErrorStatus(); if (!aSR.IsDone()) { //printf(" pb SR: Done nE: %d nV1:( %d %15.10lf ) nV2:( %d %15.10lf )\n", nE, nV1, aT1, nV2, aT2); aSR.SetShrunkRange(aRange); //throw BOPTColStd_Failure(buf) ; } else if (iErr!=6) { CorrectShrunkRanges (0, aPave1, aSR); CorrectShrunkRanges (1, aPave2, aSR); } aPB.SetShrunkRange(aSR); aLPB.Append(aPB); } //for (; aPBIt.More(); aPBIt.Next()) myIsDone=Standard_True; }
size_t wxRegEx::GetMatchCount() const { wxCHECK_MSG( IsValid(), 0, wxT("must successfully Compile() first") ); return m_impl->GetMatchCount(); }
void DWARFDIE::Dump (lldb_private::Stream *s, const uint32_t recurse_depth) const { if (s && IsValid()) m_die->Dump (GetDWARF(), GetCU(), *s, recurse_depth); }
//----------------------------------------------------------------------------- // (For text buffers only) // Parse a token from the buffer: // Grab all text that lies between a starting delimiter + ending delimiter // (skipping whitespace that leads + trails both delimiters). // Note the delimiter checks are case-insensitive. // If successful, the get index is advanced and the function returns true, // otherwise the index is not advanced and the function returns false. //----------------------------------------------------------------------------- bool CUtlBuffer::ParseToken( const char *pStartingDelim, const char *pEndingDelim, char* pString, int nMaxLen ) { int nCharsToCopy = 0; int nCurrentGet = 0; size_t nEndingDelimLen; // Starting delimiter is optional char emptyBuf = '\0'; if ( !pStartingDelim ) { pStartingDelim = &emptyBuf; } // Ending delimiter is not Assert( pEndingDelim && pEndingDelim[0] ); nEndingDelimLen = Q_strlen( pEndingDelim ); int nStartGet = TellGet(); char nCurrChar; int nTokenStart = -1; EatWhiteSpace( ); while ( *pStartingDelim ) { nCurrChar = *pStartingDelim++; if ( !isspace((unsigned char)nCurrChar) ) { if ( tolower( GetChar() ) != tolower( nCurrChar ) ) goto parseFailed; } else { EatWhiteSpace(); } } EatWhiteSpace(); nTokenStart = TellGet(); if ( !GetToken( pEndingDelim ) ) goto parseFailed; nCurrentGet = TellGet(); nCharsToCopy = (nCurrentGet - nEndingDelimLen) - nTokenStart; if ( nCharsToCopy >= nMaxLen ) { nCharsToCopy = nMaxLen - 1; } if ( nCharsToCopy > 0 ) { SeekGet( CUtlBuffer::SEEK_HEAD, nTokenStart ); Get( pString, nCharsToCopy ); if ( !IsValid() ) goto parseFailed; // Eat trailing whitespace for ( ; nCharsToCopy > 0; --nCharsToCopy ) { if ( !isspace( (unsigned char)pString[ nCharsToCopy-1 ] ) ) break; } } pString[ nCharsToCopy ] = '\0'; // Advance the Get index SeekGet( CUtlBuffer::SEEK_HEAD, nCurrentGet ); return true; parseFailed: // Revert the get index SeekGet( SEEK_HEAD, nStartGet ); pString[0] = '\0'; return false; }
// Specialized method (overloaded from IpMatrix) void CompoundMatrix::SinvBlrmZMTdBrImpl(Number alpha, const Vector& S, const Vector& R, const Vector& Z, const Vector& D, Vector& X) const { // First check if the matrix is indeed such that we can use the // special methods from the component spaces (this only works if // we have exactly one submatrix per column) bool fast_SinvBlrmZMTdBr = false; if (!owner_space_->Diagonal()) { fast_SinvBlrmZMTdBr = true; for (Index jcol=0; jcol < NComps_Cols(); jcol++ ) { Index nblocks = 0; for (Index irow=0; irow < NComps_Rows(); irow++ ) { if (ConstComp(irow, jcol)) { nblocks++; if (nblocks>1) { break; } } } if (nblocks!=1) { fast_SinvBlrmZMTdBr = false; break; } } } if (!owner_space_->Diagonal() && !fast_SinvBlrmZMTdBr) { // Use the standard replacement implementation Matrix::SinvBlrmZMTdBrImpl(alpha, S, R, Z, D, X); DBG_ASSERT(false && "Found a matrix where we can't use the fast SinvBlrmZMTdBr implementation in CompoundMatrix"); } else { // The vectors are assumed to be compound Vectors as well (unless they // are assumed to consist of only one component const CompoundVector* comp_S = dynamic_cast<const CompoundVector*>(&S); const CompoundVector* comp_R = dynamic_cast<const CompoundVector*>(&R); const CompoundVector* comp_Z = dynamic_cast<const CompoundVector*>(&Z); const CompoundVector* comp_D = dynamic_cast<const CompoundVector*>(&D); CompoundVector* comp_X = dynamic_cast<CompoundVector*>(&X); #ifndef ALLOW_NESTED // A few sanity checks for sizes if (comp_S) { DBG_ASSERT(NComps_Cols()==comp_S->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } if (comp_Z) { DBG_ASSERT(NComps_Cols()==comp_Z->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } if (comp_R) { DBG_ASSERT(NComps_Cols()==comp_R->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } if (comp_D) { DBG_ASSERT(NComps_Rows()==comp_D->NComps()); } else { DBG_ASSERT(NComps_Rows() == 1); } if (comp_X) { DBG_ASSERT(NComps_Cols()==comp_X->NComps()); } else { DBG_ASSERT(NComps_Cols() == 1); } #endif if (comp_S) { if (NComps_Cols()!=comp_S->NComps()) { comp_S = NULL; } } if (comp_Z) { if (NComps_Cols()!=comp_Z->NComps()) { comp_Z = NULL; } } if (comp_R) { if (NComps_Cols()!=comp_R->NComps()) { comp_R = NULL; } } if (comp_D) { if (NComps_Rows()!=comp_D->NComps()) { comp_D = NULL; } } if (comp_X) { if (NComps_Cols()!=comp_X->NComps()) { comp_X = NULL; } } for (Index irow=0; irow<NComps_Cols(); irow++) { Index jcol = irow; if (!owner_space_->Diagonal()) { for (Index j=0; j<NComps_Rows(); j++) { if (ConstComp(j, irow)) { jcol = j; break; } } } SmartPtr<const Vector> S_i; if (comp_S) { S_i = comp_S->GetComp(irow); } else { S_i = &S; } DBG_ASSERT(IsValid(S_i)); SmartPtr<const Vector> Z_i; if (comp_Z) { Z_i = comp_Z->GetComp(irow); } else { Z_i = &Z; } DBG_ASSERT(IsValid(Z_i)); SmartPtr<const Vector> R_i; if (comp_R) { R_i = comp_R->GetComp(irow); } else { R_i = &R; } DBG_ASSERT(IsValid(R_i)); SmartPtr<const Vector> D_i; if (comp_D) { D_i = comp_D->GetComp(jcol); } else { D_i = &D; } DBG_ASSERT(IsValid(D_i)); SmartPtr<Vector> X_i; if (comp_X) { X_i = comp_X->GetCompNonConst(irow); } else { X_i = &X; } DBG_ASSERT(IsValid(X_i)); ConstComp(jcol, irow)->SinvBlrmZMTdBr(alpha, *S_i, *R_i, *Z_i, *D_i, *X_i); } } }
//----------------------------------------------------------------------------- // Parses the next token, given a set of character breaks to stop at //----------------------------------------------------------------------------- int CUtlBuffer::ParseToken( characterset_t *pBreaks, char *pTokenBuf, int nMaxLen, bool bParseComments ) { Assert( nMaxLen > 0 ); pTokenBuf[0] = 0; // skip whitespace + comments while ( true ) { if ( !IsValid() ) return -1; EatWhiteSpace(); if ( bParseComments ) { if ( !EatCPPComment() ) break; } else { break; } } char c = GetChar(); // End of buffer if ( c == 0 ) return -1; // handle quoted strings specially if ( c == '\"' ) { int nLen = 0; while( IsValid() ) { c = GetChar(); if ( c == '\"' || !c ) { pTokenBuf[nLen] = 0; return nLen; } pTokenBuf[nLen] = c; if ( ++nLen == nMaxLen ) { pTokenBuf[nLen-1] = 0; return nMaxLen; } } // In this case, we hit the end of the buffer before hitting the end qoute pTokenBuf[nLen] = 0; return nLen; } // parse single characters if ( IN_CHARACTERSET( *pBreaks, c ) ) { pTokenBuf[0] = c; pTokenBuf[1] = 0; return 1; } // parse a regular word int nLen = 0; while ( true ) { pTokenBuf[nLen] = c; if ( ++nLen == nMaxLen ) { pTokenBuf[nLen-1] = 0; return nMaxLen; } c = GetChar(); if ( !IsValid() ) break; if ( IN_CHARACTERSET( *pBreaks, c ) || c == '\"' || c <= ' ' ) { SeekGet( SEEK_CURRENT, -1 ); break; } } pTokenBuf[nLen] = 0; return nLen; }
void CUnit::RecieveMessage(CMessage &message){ NLOG("CUnit::RecieveMessage"); if(!IsValid()){ return; } if(message.GetType() == string("update")){ if(under_construction){ return; } if(EVERY_((GetAge()%32+20))){ if(currentTask.get() != 0){ if(!currentTask->IsValid()){ // taskManager->TaskFinished(); if(taskManager->HasTasks()){ currentTask = taskManager->GetNextTask(); if(currentTask.get() != 0){ currentTask->Init(); G->RegisterMessageHandler(currentTask); } }else{ currentTask = boost::shared_ptr<IModule>(); } } }else{ // if(taskManager->HasTasks()){ currentTask = taskManager->GetNextTask(); if(currentTask.get() != 0){ currentTask->Init(); G->RegisterMessageHandler(currentTask); } } } } }else if(message.GetType() == string("unitfinished")){ if(message.GetParameter(0) == this->uid){ under_construction = false; LoadBehaviours(); } }else if(message.GetType() == string("unitdestroyed")){ if(message.GetParameter(0) == uid){ if(!utd->IsMobile()){ G->BuildingPlacer->UnBlock(G->GetUnitPos(uid),utd); } G->RemoveHandler(currentTask); taskManager->RemoveAllTasks(); G->RemoveHandler(taskManager); if(!behaviours.empty()){ behaviours.erase(behaviours.begin(),behaviours.end()); behaviours.clear(); } this->End(); return; } } if(under_construction){ return; } }
bool ON_Line::Create( const ON_3dPoint& from_pt, const ON_3dPoint& to_pt ) { from = from_pt; to = to_pt; return IsValid(); }
bool CFantomSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); }
bool CAnoncoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); }