hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f9cc18b43b3fac64fd050497fcd4052b7a504534 | 13,764 | cpp | C++ | Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Util/ObjectRegister.cpp | cpc/carla | 2b4af4c08c751461e23558809a1d8dcb5dc740dc | [
"MIT"
] | 3 | 2021-01-08T13:04:11.000Z | 2021-01-25T16:56:52.000Z | Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Util/ObjectRegister.cpp | cpc/carla | 2b4af4c08c751461e23558809a1d8dcb5dc740dc | [
"MIT"
] | 2 | 2021-03-31T20:10:04.000Z | 2021-12-13T20:48:30.000Z | Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Util/ObjectRegister.cpp | cpc/carla | 2b4af4c08c751461e23558809a1d8dcb5dc740dc | [
"MIT"
] | 4 | 2021-04-15T03:45:53.000Z | 2021-12-24T13:13:39.000Z | // Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "Carla.h"
#include "Carla/Util/ObjectRegister.h"
#include "Carla/Game/Tagger.h"
#if WITH_EDITOR
#include "FileHelper.h"
#include "Paths.h"
#endif // WITH_EDITOR
namespace crp = carla::rpc;
TArray<FEnvironmentObject> UObjectRegister::GetEnvironmentObjects(uint8 InTagQueried) const
{
TArray<FEnvironmentObject> Result;
crp::CityObjectLabel TagQueried = (crp::CityObjectLabel)InTagQueried;
bool FilterByTagEnabled = (TagQueried != crp::CityObjectLabel::Any);
for(const FEnvironmentObject& It : EnvironmentObjects)
{
if(!FilterByTagEnabled || (It.ObjectLabel == TagQueried))
{
Result.Emplace(It);
}
}
return Result;
}
void UObjectRegister::RegisterObjects(TArray<AActor*> Actors)
{
// Empties the array but doesn't change memory allocations
EnvironmentObjects.Reset();
for(AActor* Actor : Actors)
{
FString ClassName = Actor->GetClass()->GetName();
// Discard Sky to not break the global ilumination
if(ClassName.Equals("BP_Sky_C")) continue;
ACarlaWheeledVehicle* Vehicle = Cast<ACarlaWheeledVehicle>(Actor);
if (Vehicle)
{
RegisterVehicle(Vehicle);
continue;
}
ACharacter* Character = Cast<ACharacter>(Actor);
if (Character)
{
RegisterCharacter(Character);
continue;
}
ATrafficLightBase* TrafficLight = Cast<ATrafficLightBase>(Actor);
if(TrafficLight)
{
RegisterTrafficLight(TrafficLight);
continue;
}
RegisterISMComponents(Actor);
RegisterSMComponents(Actor);
RegisterSKMComponents(Actor);
}
#if WITH_EDITOR
// To help debug
FString FileContent;
FileContent += FString::Printf(TEXT("Num actors %d\n"), Actors.Num());
FileContent += FString::Printf(TEXT("Num registered objects %d\n\n"), EnvironmentObjects.Num());
for(const FEnvironmentObject& Object : EnvironmentObjects)
{
FileContent += FString::Printf(TEXT("%llu\t"), Object.Id);
FileContent += FString::Printf(TEXT("%s\t"), *Object.Name);
FileContent += FString::Printf(TEXT("%s\t"), *Object.IdStr);
FileContent += FString::Printf(TEXT("%d\n"), static_cast<int32>(Object.Type));
}
FString FilePath = FPaths::ProjectSavedDir() + "RegisteredObjects.txt";
FFileHelper::SaveStringToFile(
FileContent,
*FilePath,
FFileHelper::EEncodingOptions::AutoDetect,
&IFileManager::Get(),
EFileWrite::FILEWRITE_Silent);
#endif // WITH_EDITOR
}
void UObjectRegister::EnableEnvironmentObjects(const TSet<uint64>& EnvObjectIds, bool Enable)
{
for(uint64 It : EnvObjectIds)
{
bool found = false;
for(FEnvironmentObject& EnvironmentObject : EnvironmentObjects)
{
if(It == EnvironmentObject.Id)
{
EnableEnvironmentObject(EnvironmentObject, Enable);
found = true;
break;
}
}
if(!found)
{
UE_LOG(LogCarla, Error, TEXT("EnableEnvironmentObjects id not found %llu"), It);
}
}
}
void UObjectRegister::RegisterEnvironmentObject(
AActor* Actor,
FBoundingBox& BoundingBox,
EnvironmentObjectType Type,
uint8 Tag)
{
const FString ActorName = Actor->GetName();
const char* ActorNameChar = TCHAR_TO_ANSI(*ActorName);
FEnvironmentObject EnvironmentObject;
EnvironmentObject.Transform = Actor->GetActorTransform();
EnvironmentObject.Id = CityHash64(ActorNameChar, ActorName.Len());
EnvironmentObject.Name = ActorName;
EnvironmentObject.Actor = Actor;
EnvironmentObject.CanTick = Actor->IsActorTickEnabled();
EnvironmentObject.BoundingBox = BoundingBox;
EnvironmentObject.ObjectLabel = static_cast<crp::CityObjectLabel>(Tag);
EnvironmentObject.Type = Type;
EnvironmentObjects.Emplace(std::move(EnvironmentObject));
}
void UObjectRegister::RegisterVehicle(ACarlaWheeledVehicle* Vehicle)
{
check(Vehicle);
FBoundingBox BB = UBoundingBoxCalculator::GetVehicleBoundingBox(Vehicle);
RegisterEnvironmentObject(Vehicle, BB, EnvironmentObjectType::Vehicle, static_cast<uint8>(crp::CityObjectLabel::Vehicles));
}
void UObjectRegister::RegisterCharacter(ACharacter* Character)
{
check(Character);
FBoundingBox BB = UBoundingBoxCalculator::GetCharacterBoundingBox(Character);
RegisterEnvironmentObject(Character, BB, EnvironmentObjectType::Character, static_cast<uint8>(crp::CityObjectLabel::Pedestrians));
}
void UObjectRegister::RegisterTrafficLight(ATrafficLightBase* TrafficLight)
{
check(TrafficLight);
TArray<FBoundingBox> BBs;
TArray<uint8> Tags;
UBoundingBoxCalculator::GetTrafficLightBoundingBox(TrafficLight, BBs, Tags);
check(BBs.Num() == Tags.Num());
const FTransform Transform = TrafficLight->GetTransform();
const FString ActorName = TrafficLight->GetName();
const bool IsActorTickEnabled = TrafficLight->IsActorTickEnabled();
for(int i = 0; i < BBs.Num(); i++)
{
const FBoundingBox& BB = BBs[i];
const uint8 Tag = Tags[i];
crp::CityObjectLabel ObjectLabel = static_cast<crp::CityObjectLabel>(Tag);
const FString TagString = ATagger::GetTagAsString(ObjectLabel);
const FString SMName = FString::Printf(TEXT("%s_%s_%d"), *ActorName, *TagString, i);
FEnvironmentObject EnvironmentObject;
EnvironmentObject.Transform = Transform;
EnvironmentObject.Id = CityHash64(TCHAR_TO_ANSI(*SMName), SMName.Len());
EnvironmentObject.Name = SMName;
EnvironmentObject.Actor = TrafficLight;
EnvironmentObject.CanTick = IsActorTickEnabled;
EnvironmentObject.BoundingBox = BB;
EnvironmentObject.Type = EnvironmentObjectType::TrafficLight;
EnvironmentObject.ObjectLabel = ObjectLabel;
EnvironmentObjects.Emplace(EnvironmentObject);
// Register components with its ID; it's not the best solution since we are recalculating the BBs
// But this is only calculated when the level is loaded
TArray<UStaticMeshComponent*> StaticMeshComps;
UBoundingBoxCalculator::GetMeshCompsFromActorBoundingBox(TrafficLight, BB, StaticMeshComps);
for(const UStaticMeshComponent* Comp : StaticMeshComps)
{
ObjectIdToComp.Emplace(EnvironmentObject.Id, Comp);
}
}
}
void UObjectRegister::RegisterISMComponents(AActor* Actor)
{
check(Actor);
TArray<UInstancedStaticMeshComponent*> ISMComps;
Actor->GetComponents<UInstancedStaticMeshComponent>(ISMComps);
const FString ActorName = Actor->GetName();
int InstanceCount = 0;
bool IsActorTickEnabled = Actor->IsActorTickEnabled();
// Foliage actor is a special case, it can appear more than once while traversing the actor list
if(Cast<AInstancedFoliageActor>(Actor))
{
InstanceCount = FoliageActorInstanceCount;
}
for(UInstancedStaticMeshComponent* Comp : ISMComps)
{
const TArray<FInstancedStaticMeshInstanceData>& PerInstanceSMData = Comp->PerInstanceSMData;
const FTransform CompTransform = Comp->GetComponentTransform();
TArray<FBoundingBox> BoundingBoxes;
UBoundingBoxCalculator::GetISMBoundingBox(Comp, BoundingBoxes);
FString CompName = Comp->GetName();
const crp::CityObjectLabel Tag = ATagger::GetTagOfTaggedComponent(*Comp);
for(int i = 0; i < PerInstanceSMData.Num(); i++)
{
const FInstancedStaticMeshInstanceData& It = PerInstanceSMData[i];
const FTransform InstanceTransform = FTransform(It.Transform);
const FVector InstanceLocation = InstanceTransform.GetLocation();
// Discard decimal part
const int32 X = static_cast<int32>(InstanceLocation.X);
const int32 Y = static_cast<int32>(InstanceLocation.Y);
const int32 Z = static_cast<int32>(InstanceLocation.Z);
const FString InstanceName = FString::Printf(TEXT("%s_Inst_%d_%d"), *ActorName, InstanceCount, i);
const FString InstanceIdStr = FString::Printf(TEXT("%s_%s_%d_%d_%d_%d"), *ActorName, *CompName, X, Y, Z, InstanceCount);
uint64 InstanceId = CityHash64(TCHAR_TO_ANSI(*InstanceIdStr), InstanceIdStr.Len());
FEnvironmentObject EnvironmentObject;
EnvironmentObject.Transform = InstanceTransform * CompTransform;
EnvironmentObject.Id = InstanceId;
EnvironmentObject.Name = InstanceName;
EnvironmentObject.IdStr = InstanceIdStr;
EnvironmentObject.Actor = Actor;
EnvironmentObject.CanTick = IsActorTickEnabled;
if( i < BoundingBoxes.Num())
{
EnvironmentObject.BoundingBox = BoundingBoxes[i];
}
EnvironmentObject.Type = EnvironmentObjectType::ISMComp;
EnvironmentObject.ObjectLabel = static_cast<crp::CityObjectLabel>(Tag);
EnvironmentObjects.Emplace(EnvironmentObject);
ObjectIdToComp.Emplace(InstanceId, Comp);
InstanceCount++;
}
}
if(Cast<AInstancedFoliageActor>(Actor))
{
FoliageActorInstanceCount = InstanceCount;
}
}
void UObjectRegister::RegisterSMComponents(AActor* Actor)
{
check(Actor);
TArray<UStaticMeshComponent*> StaticMeshComps;
Actor->GetComponents<UStaticMeshComponent>(StaticMeshComps);
TArray<FBoundingBox> BBs;
TArray<uint8> Tags;
UBoundingBoxCalculator::GetBBsOfStaticMeshComponents(StaticMeshComps, BBs, Tags);
check(BBs.Num() == Tags.Num());
const FTransform Transform = Actor->GetTransform();
const FString ActorName = Actor->GetName();
const bool IsActorTickEnabled = Actor->IsActorTickEnabled();
for(int i = 0; i < BBs.Num(); i++)
{
const FString SMName = FString::Printf(TEXT("%s_SM_%d"), *ActorName, i);
FEnvironmentObject EnvironmentObject;
EnvironmentObject.Transform = Transform;
EnvironmentObject.Id = CityHash64(TCHAR_TO_ANSI(*SMName), SMName.Len());
EnvironmentObject.Name = SMName;
EnvironmentObject.Actor = Actor;
EnvironmentObject.CanTick = IsActorTickEnabled;
EnvironmentObject.BoundingBox = BBs[i];
EnvironmentObject.Type = EnvironmentObjectType::SMComp;
EnvironmentObject.ObjectLabel = static_cast<crp::CityObjectLabel>(Tags[i]);
EnvironmentObjects.Emplace(EnvironmentObject);
}
}
void UObjectRegister::RegisterSKMComponents(AActor* Actor)
{
check(Actor);
TArray<USkeletalMeshComponent*> SkeletalMeshComps;
Actor->GetComponents<USkeletalMeshComponent>(SkeletalMeshComps);
TArray<FBoundingBox> BBs;
TArray<uint8> Tags;
UBoundingBoxCalculator::GetBBsOfSkeletalMeshComponents(SkeletalMeshComps, BBs, Tags);
check(BBs.Num() == Tags.Num());
const FTransform Transform = Actor->GetTransform();
const FString ActorName = Actor->GetName();
const bool IsActorTickEnabled = Actor->IsActorTickEnabled();
for(int i = 0; i < BBs.Num(); i++)
{
const FString SKMName = FString::Printf(TEXT("%s_SKM_%d"), *ActorName, i);
FEnvironmentObject EnvironmentObject;
EnvironmentObject.Transform = Transform;
EnvironmentObject.Id = CityHash64(TCHAR_TO_ANSI(*SKMName), SKMName.Len());
EnvironmentObject.Name = SKMName;
EnvironmentObject.Actor = Actor;
EnvironmentObject.CanTick = IsActorTickEnabled;
EnvironmentObject.BoundingBox = BBs[i];
EnvironmentObject.Type = EnvironmentObjectType::SKMComp;
EnvironmentObject.ObjectLabel = static_cast<crp::CityObjectLabel>(Tags[i]);
EnvironmentObjects.Emplace(EnvironmentObject);
}
}
void UObjectRegister::EnableEnvironmentObject(
FEnvironmentObject& EnvironmentObject,
bool Enable)
{
switch (EnvironmentObject.Type)
{
case EnvironmentObjectType::Vehicle:
case EnvironmentObjectType::Character:
case EnvironmentObjectType::SMComp:
case EnvironmentObjectType::SKMComp:
EnableActor(EnvironmentObject, Enable);
break;
case EnvironmentObjectType::TrafficLight:
EnableTrafficLight(EnvironmentObject, Enable);
break;
case EnvironmentObjectType::ISMComp:
EnableISMComp(EnvironmentObject, Enable);
break;
default:
check(false);
break;
}
}
void UObjectRegister::EnableActor(FEnvironmentObject& EnvironmentObject, bool Enable)
{
AActor* Actor = EnvironmentObject.Actor;
Actor->SetActorHiddenInGame(!Enable);
Actor->SetActorEnableCollision(Enable);
if(EnvironmentObject.CanTick)
{
Actor->SetActorTickEnabled(Enable);
}
}
void UObjectRegister::EnableTrafficLight(FEnvironmentObject& EnvironmentObject, bool Enable)
{
// We need to look for the component(s) that form the EnvironmentObject
// i.e.: The light box is composed by various SMComponents, one per light,
// we need to enable/disable all of them
TArray<const UStaticMeshComponent*> ObjectComps;
ObjectIdToComp.MultiFind(EnvironmentObject.Id, ObjectComps);
for(const UStaticMeshComponent* Comp : ObjectComps)
{
UStaticMeshComponent* SMComp = const_cast<UStaticMeshComponent*>(Comp);
SMComp->SetHiddenInGame(!Enable);
ECollisionEnabled::Type CollisionType = Enable ? ECollisionEnabled::Type::QueryAndPhysics : ECollisionEnabled::Type::NoCollision;
SMComp->SetCollisionEnabled(CollisionType);
}
}
void UObjectRegister::EnableISMComp(FEnvironmentObject& EnvironmentObject, bool Enable)
{
TArray<const UStaticMeshComponent*> ObjectComps;
TArray<FString> InstanceName;
FTransform InstanceTransform = EnvironmentObject.Transform;
ObjectIdToComp.MultiFind(EnvironmentObject.Id, ObjectComps);
EnvironmentObject.Name.ParseIntoArray(InstanceName, TEXT("_"), false);
int Index = FCString::Atoi(*InstanceName[InstanceName.Num() - 1]);
if(!Enable)
{
InstanceTransform.SetTranslation(FVector(1000000.0f));
InstanceTransform.SetScale3D(FVector(0.0f));
}
UStaticMeshComponent* SMComp = const_cast<UStaticMeshComponent*>(ObjectComps[0]);
UInstancedStaticMeshComponent* ISMComp = Cast<UInstancedStaticMeshComponent>(SMComp);
bool Result = ISMComp->UpdateInstanceTransform(Index, InstanceTransform, true, true);
}
| 32.539007 | 133 | 0.7415 | [
"object",
"transform"
] |
f9d10afae8741595ec5bdb04855859c61f80cdb9 | 679 | cpp | C++ | HackerRank/Plus Minus.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | HackerRank/Plus Minus.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | HackerRank/Plus Minus.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void plusMinus(vector<int> arr) {
int tam = arr.size();
double bigger = 0;
double zero = 0;
double smaller = 0;
double ans;
for (int i = 0; i < tam; i++){
if (arr[i] == 0) zero++;
else if (arr[i] < 0) smaller++;
else bigger++;
}
ans = bigger/tam;
printf ("%.6lf\n", ans);
ans = smaller/tam;
printf ("%.6lf\n", ans);
ans = zero/tam;
printf ("%.6lf\n", ans);
}
int main () {
vector <int> arr;
int n, aux;
cin >> n;
for (int i = 0; i < n; i++){
cin >> aux;
arr.push_back(aux);
}
plusMinus(arr);
return 0;
} | 16.560976 | 39 | 0.478645 | [
"vector"
] |
f9d40d89616ddcb81823a50c39b69df621b749ed | 1,059 | cpp | C++ | find_total_length.cpp | Kaban-5/square_free_words | 850302a12e56f05e07aee7b8f84dc9b97f45fa0c | [
"MIT"
] | null | null | null | find_total_length.cpp | Kaban-5/square_free_words | 850302a12e56f05e07aee7b8f84dc9b97f45fa0c | [
"MIT"
] | null | null | null | find_total_length.cpp | Kaban-5/square_free_words | 850302a12e56f05e07aee7b8f84dc9b97f45fa0c | [
"MIT"
] | null | null | null | void calc_number_of_states(int32_t l, int32_t r, int32_t depth, const vector<string> &dictionary, int &states_needed)
{
if (l == r)
return;
states_needed++;
if (int32_t(dictionary[l].size()) == depth)
l++;
if (l == r)
return;
array<int32_t, 4> where = {l, r, r, r};
int32_t ptr = 1;
for (int32_t i = l; i < r; i++)
{
while (dictionary[i][depth] > 'a' + (ptr - 1))
where[ptr++] = i;
}
for (int32_t i = 0; i < 3; i++)
calc_number_of_states(where[i], where[i + 1], depth + 1, dictionary, states_needed);
}
int32_t print_the_number_of_states()
{
ifstream in(dictionary_address);
vector<string> dictionary;
string word;
ignore_int(in);
while (in >> word)
{
if (int(word.size()) <= trie_word_length)
dictionary.push_back(word + word);
}
int32_t states_needed = 0;
sort(dictionary.begin(), dictionary.end());
calc_number_of_states(0, int(dictionary.size()), 0, dictionary, states_needed);
cerr << states_needed << " states in the trie." << endl;
return states_needed;
}
| 22.531915 | 118 | 0.626062 | [
"vector"
] |
f9d51ee831d8e93589263a81b3bee23e48895028 | 901 | cpp | C++ | problems/validate_binary_search_tree/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/validate_binary_search_tree/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/validate_binary_search_tree/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
vector<int> ans;
bool ok = true;
function<void(TreeNode*)> dfs = [&](TreeNode* root) {
if (root == NULL) return;
dfs(root->left);
ans.push_back(root->val);
dfs(root->right);
};
dfs(root);
unordered_set<int> se(ans.begin(), ans.end());
if (se.size() != ans.size()) ok = false;
if (is_sorted(ans.begin(), ans.end()) && ok) return true;
else return false;
}
}; | 31.068966 | 93 | 0.531632 | [
"vector"
] |
f9d6ceb9f656de5b7d3effc954dcbeb58829324e | 1,288 | hpp | C++ | src/Console/Console.hpp | RainingComputers/ShnooTalk | 714f6648363a99e011e329ed1a3f800e6fe65f39 | [
"MIT"
] | 6 | 2021-07-17T16:02:07.000Z | 2022-02-05T16:33:51.000Z | src/Console/Console.hpp | RainingComputers/ShnooTalk | 714f6648363a99e011e329ed1a3f800e6fe65f39 | [
"MIT"
] | 1 | 2021-07-16T07:14:31.000Z | 2021-07-16T07:22:10.000Z | src/Console/Console.hpp | RainingComputers/ShnooTalk | 714f6648363a99e011e329ed1a3f800e6fe65f39 | [
"MIT"
] | 2 | 2021-07-16T02:54:27.000Z | 2022-03-29T20:51:57.000Z | #ifndef CONSOLE_CONSOLE
#define CONSOLE_CONSOLE
#include <fstream>
#include <map>
#include <vector>
#include "../Builder/Unit.hpp"
#include "../PrettyPrint/Errors.hpp"
struct CompileError
{
};
struct InternalBugError
{
};
class Console
{
std::string fileName;
std::ifstream* file;
std::map<std::string, std::ifstream> streamsMap;
std::vector<std::string> fileNameStack;
std::vector<std::ifstream*> fileStack;
public:
[[noreturn]] void compileErrorOnToken(const std::string& message, const Token& tok);
[[noreturn]] void typeError(const Token& tok, const Unit& expected, const Unit& found);
[[noreturn]] void internalBugErrorOnToken(const Token& tok);
[[noreturn]] void internalBugError();
[[noreturn]] void internalBugErrorMessage(const std::string& message);
[[noreturn]] void parseError(token::TokenType& expected, Token& found);
[[noreturn]] void parserErrorMultiple(const token::TokenType* expected, int ntoks, const Token& found);
[[noreturn]] void lexerError(const std::string& errorMessage, const std::string& line, int lineno, int col);
void check(bool flag);
std::ifstream* getStream();
std::string getFileName();
void pushModule(const std::string& fileName);
void popModule();
};
#endif | 23 | 112 | 0.700311 | [
"vector"
] |
f9edebf2885a948212a11d45aabcb2217f958174 | 616 | cpp | C++ | src/analyzers/multi_analyzer.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 615 | 2015-01-31T17:14:03.000Z | 2022-03-27T03:03:02.000Z | src/analyzers/multi_analyzer.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 167 | 2015-01-20T17:48:16.000Z | 2021-12-20T00:15:29.000Z | src/analyzers/multi_analyzer.cpp | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 264 | 2015-01-30T00:08:01.000Z | 2022-03-02T17:19:11.000Z | /**
* @file multi_analyzer.cpp
*/
#include "meta/analyzers/multi_analyzer.h"
namespace meta
{
namespace analyzers
{
multi_analyzer::multi_analyzer(std::vector<std::unique_ptr<analyzer>>&& toks)
: analyzers_{std::move(toks)}
{
/* nothing */
}
multi_analyzer::multi_analyzer(const multi_analyzer& other)
{
analyzers_.reserve(other.analyzers_.size());
for (const auto& an : other.analyzers_)
analyzers_.emplace_back(an->clone());
}
void multi_analyzer::tokenize(const corpus::document& doc, featurizer& counts)
{
for (auto& tok : analyzers_)
tok->tokenize(doc, counts);
}
}
}
| 19.25 | 78 | 0.693182 | [
"vector"
] |
f9f45c58bcbdce9079c962a91eaae6f3c8aff288 | 1,167 | cpp | C++ | src/builder.cpp | cssartori/ovig | 3af99cc5d1d4d0e9043b0bb3fe1043fb5a53d25d | [
"MIT"
] | 3 | 2021-04-16T22:40:17.000Z | 2021-11-03T13:18:57.000Z | src/builder.cpp | cssartori/ovig | 3af99cc5d1d4d0e9043b0bb3fe1043fb5a53d25d | [
"MIT"
] | 4 | 2021-07-31T14:32:28.000Z | 2021-07-31T14:40:25.000Z | src/builder.cpp | cssartori/ovig | 3af99cc5d1d4d0e9043b0bb3fe1043fb5a53d25d | [
"MIT"
] | 4 | 2019-09-19T09:52:57.000Z | 2021-06-16T18:55:56.000Z | #include "../include/builder.hpp"
#include <algorithm>
using namespace std;
namespace Builder{
//Builds an instance of the problem specified in InstanceType (currently supported types are PDPTW and CVRP)
//This function considers that locations are given and all the information must be generated.
int build(const Configurations& con, const std::vector<GeoLocation>& locations, std::vector< std::vector< double > >& matrix, Instance& inst){
int res = EXIT_FAILURE;
if(con.type == InstanceType::PDPTW)
res = PDPTW::build(con, locations, matrix, inst);
else if(con.type == InstanceType::CVRP)
res = CVRP::build(con, locations, matrix, inst);
return res;
}
//Builds an instance of the problem specified in InstanceType (currently supported type is PDPTW)
//This function considers that complete Nodes are given and only some of the information must be generated (this is used to create PDPTW New York Taxi instances)
int build(const Configurations& con, std::vector<Node>& nodes, std::vector< std::vector< double > >& matrix, Instance& inst){
int res = EXIT_FAILURE;
res = PDPTW::build(con, nodes, matrix, inst);
return res;
}
};
| 37.645161 | 162 | 0.732648 | [
"vector"
] |
e602ffb5bff84a1a22c92294f608f1233cb159d4 | 5,676 | cpp | C++ | oeml-sdk/cpp-qt5-client/client/OAIValidationError.cpp | Martin-Molinero/coinapi-sdk | 8633f61e0809e7ee4032100fe08454e8c4ad5e0c | [
"MIT"
] | 1 | 2020-07-23T05:47:52.000Z | 2020-07-23T05:47:52.000Z | oeml-sdk/cpp-qt5-client/client/OAIValidationError.cpp | Martin-Molinero/coinapi-sdk | 8633f61e0809e7ee4032100fe08454e8c4ad5e0c | [
"MIT"
] | null | null | null | oeml-sdk/cpp-qt5-client/client/OAIValidationError.cpp | Martin-Molinero/coinapi-sdk | 8633f61e0809e7ee4032100fe08454e8c4ad5e0c | [
"MIT"
] | null | null | null | /**
* OEML - REST API
* This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
*
* The version of the OpenAPI document: v1
* Contact: support@coinapi.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIValidationError.h"
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QObject>
#include "OAIHelpers.h"
namespace OpenAPI {
OAIValidationError::OAIValidationError(QString json) {
this->initializeModel();
this->fromJson(json);
}
OAIValidationError::OAIValidationError() {
this->initializeModel();
}
OAIValidationError::~OAIValidationError() {}
void OAIValidationError::initializeModel() {
m_type_isSet = false;
m_type_isValid = false;
m_title_isSet = false;
m_title_isValid = false;
m_status_isSet = false;
m_status_isValid = false;
m_trace_id_isSet = false;
m_trace_id_isValid = false;
m_errors_isSet = false;
m_errors_isValid = false;
}
void OAIValidationError::fromJson(QString jsonString) {
QByteArray array(jsonString.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
}
void OAIValidationError::fromJsonObject(QJsonObject json) {
m_type_isValid = ::OpenAPI::fromJsonValue(type, json[QString("type")]);
m_type_isSet = !json[QString("type")].isNull() && m_type_isValid;
m_title_isValid = ::OpenAPI::fromJsonValue(title, json[QString("title")]);
m_title_isSet = !json[QString("title")].isNull() && m_title_isValid;
m_status_isValid = ::OpenAPI::fromJsonValue(status, json[QString("status")]);
m_status_isSet = !json[QString("status")].isNull() && m_status_isValid;
m_trace_id_isValid = ::OpenAPI::fromJsonValue(trace_id, json[QString("traceId")]);
m_trace_id_isSet = !json[QString("traceId")].isNull() && m_trace_id_isValid;
m_errors_isValid = ::OpenAPI::fromJsonValue(errors, json[QString("errors")]);
m_errors_isSet = !json[QString("errors")].isNull() && m_errors_isValid;
}
QString OAIValidationError::asJson() const {
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject OAIValidationError::asJsonObject() const {
QJsonObject obj;
if (m_type_isSet) {
obj.insert(QString("type"), ::OpenAPI::toJsonValue(type));
}
if (m_title_isSet) {
obj.insert(QString("title"), ::OpenAPI::toJsonValue(title));
}
if (m_status_isSet) {
obj.insert(QString("status"), ::OpenAPI::toJsonValue(status));
}
if (m_trace_id_isSet) {
obj.insert(QString("traceId"), ::OpenAPI::toJsonValue(trace_id));
}
if (m_errors_isSet) {
obj.insert(QString("errors"), ::OpenAPI::toJsonValue(errors));
}
return obj;
}
QString OAIValidationError::getType() const {
return type;
}
void OAIValidationError::setType(const QString &type) {
this->type = type;
this->m_type_isSet = true;
}
bool OAIValidationError::is_type_Set() const{
return m_type_isSet;
}
bool OAIValidationError::is_type_Valid() const{
return m_type_isValid;
}
QString OAIValidationError::getTitle() const {
return title;
}
void OAIValidationError::setTitle(const QString &title) {
this->title = title;
this->m_title_isSet = true;
}
bool OAIValidationError::is_title_Set() const{
return m_title_isSet;
}
bool OAIValidationError::is_title_Valid() const{
return m_title_isValid;
}
double OAIValidationError::getStatus() const {
return status;
}
void OAIValidationError::setStatus(const double &status) {
this->status = status;
this->m_status_isSet = true;
}
bool OAIValidationError::is_status_Set() const{
return m_status_isSet;
}
bool OAIValidationError::is_status_Valid() const{
return m_status_isValid;
}
QString OAIValidationError::getTraceId() const {
return trace_id;
}
void OAIValidationError::setTraceId(const QString &trace_id) {
this->trace_id = trace_id;
this->m_trace_id_isSet = true;
}
bool OAIValidationError::is_trace_id_Set() const{
return m_trace_id_isSet;
}
bool OAIValidationError::is_trace_id_Valid() const{
return m_trace_id_isValid;
}
QString OAIValidationError::getErrors() const {
return errors;
}
void OAIValidationError::setErrors(const QString &errors) {
this->errors = errors;
this->m_errors_isSet = true;
}
bool OAIValidationError::is_errors_Set() const{
return m_errors_isSet;
}
bool OAIValidationError::is_errors_Valid() const{
return m_errors_isValid;
}
bool OAIValidationError::isSet() const {
bool isObjectUpdated = false;
do {
if (m_type_isSet) {
isObjectUpdated = true;
break;
}
if (m_title_isSet) {
isObjectUpdated = true;
break;
}
if (m_status_isSet) {
isObjectUpdated = true;
break;
}
if (m_trace_id_isSet) {
isObjectUpdated = true;
break;
}
if (m_errors_isSet) {
isObjectUpdated = true;
break;
}
} while (false);
return isObjectUpdated;
}
bool OAIValidationError::isValid() const {
// only required properties are required for the object to be considered valid
return true;
}
} // namespace OpenAPI
| 25.567568 | 246 | 0.687104 | [
"object"
] |
e60380a0fa14874fd03173b1d61dc4e59fd99c33 | 29,376 | cpp | C++ | readdy/test/TestPotentials.cpp | ilyasku/readdy | 3e09e5c8eb2dd861758d3b91cc3a4a00301c13af | [
"BSD-3-Clause"
] | 51 | 2015-02-24T18:19:34.000Z | 2022-03-30T06:57:47.000Z | readdy/test/TestPotentials.cpp | readdy/readdy | ef400db60a29107672a7f2bc42f6c3db4de34eb0 | [
"BSD-3-Clause"
] | 81 | 2016-05-25T22:29:39.000Z | 2022-03-28T14:22:18.000Z | readdy/test/TestPotentials.cpp | ilyasku/readdy | 3e09e5c8eb2dd861758d3b91cc3a4a00301c13af | [
"BSD-3-Clause"
] | 15 | 2015-03-10T03:16:49.000Z | 2021-10-11T11:26:39.000Z | /********************************************************************
* Copyright © 2018 Computational Molecular Biology Group, *
* Freie Universität Berlin (GER) *
* *
* Redistribution and use in source and binary forms, with or *
* without modification, are permitted provided that the *
* following conditions are met: *
* 1. Redistributions of source code must retain the above *
* copyright notice, this list of conditions and the *
* following disclaimer. *
* 2. Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials *
* provided with the distribution. *
* 3. Neither the name of the copyright holder nor the names of *
* its contributors may be used to endorse or promote products *
* derived from this software without specific *
* prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND *
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, *
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, *
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF *
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
********************************************************************/
/**
* Test potentials of first and second order via small particle systems. First order potentials
* often assure that particles stay in a certain volume of the simulation box, which is checked for.
*
* @file TestPotentials.cpp
* @brief Check correct behavior of particles subject to potentials.
* @author clonker
* @author chrisfroe
* @date 27.06.16
*/
#include <catch2/catch.hpp>
#include <readdy/plugin/KernelProvider.h>
#include <readdy/testing/KernelTest.h>
#include <readdy/testing/Utils.h>
using namespace Catch::Floating;
using namespace readdytesting::kernel;
void run(readdy::model::Kernel &kernel, readdy::scalar timeStep) {
unsigned int nSteps = 200;
auto &&integrator = kernel.actions().eulerBDIntegrator(timeStep);
auto &&initNeighborList = kernel.actions().createNeighborList(kernel.context().calculateMaxCutoff());
auto &&nl = kernel.actions().updateNeighborList();
auto &&forces = kernel.actions().calculateForces();
bool requiresNeighborList = initNeighborList->cutoffDistance() > 0;
if (requiresNeighborList) {
initNeighborList->perform();
nl->perform();
}
for (readdy::TimeStep &&t = 0; t < nSteps; ++t) {
forces->perform();
integrator->perform();
if (requiresNeighborList) nl->perform();
}
}
TEMPLATE_TEST_CASE("Test potentials", "[potentials]", SingleCPU, CPU) {
auto kernel = create<TestType>();
auto &context = kernel->context();
auto &stateModel = kernel->stateModel();
SECTION("External potentials") {
SECTION("Box") {
context.particleTypes().add("A", static_cast<readdy::scalar>(1.));
context.particleTypes().add("B", static_cast<readdy::scalar>(0.1));
context.periodicBoundaryConditions() = {{false, false, false}};
const unsigned int nParticlesA = 10;
const unsigned int nParticlesB = 10;
// add particles close to origin but not all exactly on 0,0,0
for (auto i = 0; i < nParticlesA; ++i) {
kernel->addParticle("A", readdy::model::rnd::normal3<readdy::scalar>());
}
for (auto i = 0; i < nParticlesB; ++i) {
kernel->addParticle("B", readdy::model::rnd::normal3<readdy::scalar>());
}
const readdy::scalar timeStep = .005;
kernel->context().potentials().addHarmonicRepulsion("A", "B", .01, .1 + .01);
std::array<std::string, 2> types{{"A", "B"}};
//std::array<readdy::scalar, 2> radii {{.1, .01}};
for (const auto &t : types) {
// create cube potential that is spanned from (-1,-1,-1) to (1, 1, 1)
readdy::Vec3 origin {-1, -1, -1};
readdy::Vec3 extent {2, 2, 2};
kernel->context().potentials().addBox(t, 10, origin, extent);
}
auto ppObs = kernel->observe().positions(1);
readdy::Vec3 lowerBound{static_cast<readdy::scalar>(-2.5), static_cast<readdy::scalar>(-2.5),
static_cast<readdy::scalar>(-2.5)},
upperBound{2.5, 2.5, 2.5};
ppObs->setCallback([lowerBound, upperBound](readdy::model::observables::Positions::result_type currentResult) {
readdy::Vec3 avg{0, 0, 0};
bool allWithinBounds = true;
for (auto &&v : currentResult) {
allWithinBounds &= v >= lowerBound && v <= upperBound;
avg += v;
}
avg /= currentResult.size();
if (!allWithinBounds) readdy::log::debug("Average position: {}", avg);
REQUIRE(allWithinBounds);
});
auto connection = kernel->connectObservable(ppObs.get());
run(*kernel, timeStep);
}
SECTION("Spherical inclusion") {
context.boxSize() = {{10, 10, 10}};
context.particleTypes().add("A", static_cast<readdy::scalar>(1.));
context.particleTypes().add("B", static_cast<readdy::scalar>(0.1));
context.periodicBoundaryConditions() = {{false, false, false}};
const unsigned int nParticlesA = 10;
const unsigned int nParticlesB = 10;
// add particles close to origin but not all exactly on 0,0,0
for (auto i = 0; i < nParticlesA; ++i) {
kernel->addParticle("A", readdy::model::rnd::normal3<readdy::scalar>());
}
for (auto i = 0; i < nParticlesB; ++i) {
kernel->addParticle("B", readdy::model::rnd::normal3<readdy::scalar>());
}
const readdy::scalar timeStep = .005;
std::array<std::string, 2> types{{"A", "B"}};
for (const auto &t : types) {
readdy::Vec3 origin (0, 0, 0);
kernel->context().potentials().addSphere(t, 20, origin, 3, true);
}
auto ppObs = kernel->observe().positions(1);
const readdy::scalar maxDistFromOrigin = 4.0; // at kbt=1 and force_const=20 the RMSD in a well potential would be ~0.2
const readdy::scalar maxDistFromOriginSquared = maxDistFromOrigin * maxDistFromOrigin;
ppObs->setCallback([maxDistFromOriginSquared](readdy::model::observables::Positions::result_type currentResult) {
readdy::Vec3 avg{0, 0, 0};
bool allWithinBounds = true;
for (auto &&v : currentResult) {
const readdy::scalar distanceFromOriginSquared = v * v;
allWithinBounds &= distanceFromOriginSquared < maxDistFromOriginSquared;
avg += v;
}
avg /= currentResult.size();
if (!allWithinBounds) readdy::log::debug("Average position: {}", avg);
REQUIRE(allWithinBounds);
});
auto connection = kernel->connectObservable(ppObs.get());
run(*kernel, timeStep);
}
SECTION("Spherical membrane") {
// Combine SphereIn and SphereOut to build a 2D spherical manifold
context.particleTypes().add("A", 1.0);
context.boxSize() = {{10, 10, 10}};
// add two particles, one outside, one inside the sphere
auto id0 = kernel->addParticle("A", {2., 1., 1.});
auto id1 = kernel->addParticle("A", {4., 3., -3.});
auto forceConstant = static_cast<readdy::scalar>(1.);
auto radius = static_cast<readdy::scalar>(3.);
readdy::Vec3 origin = {static_cast<readdy::scalar>(1.), static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
context.potentials().addSphere("A", forceConstant, origin, radius, false);
context.potentials().addSphere("A", forceConstant, origin, radius, true);
// record ids to get data-structure-indexes of the two particles later on
auto pObs = kernel->observe().particles(1);
std::vector<readdy::ParticleId> ids;
pObs->setCallback([&ids](const readdy::model::observables::Particles::result_type &result) {
const auto &recordedIds = std::get<1>(result);
ids.insert(ids.end(), recordedIds.begin(), recordedIds.end());
});
auto connParticles = kernel->connectObservable(pObs.get());
// also record forces
auto fObs = kernel->observe().forces(1);
std::vector<readdy::Vec3> collectedForces;
fObs->setCallback([&collectedForces](const readdy::model::observables::Forces::result_type &result) {
collectedForces.insert(collectedForces.end(), result.begin(), result.end());
});
auto conn = kernel->connectObservable(fObs.get());
// calc forces
auto calculateForces = kernel->actions().calculateForces();
calculateForces->perform();
// give me results
kernel->evaluateObservables(1);
// the reference values were calculated numerically
REQUIRE(stateModel.energy() == Approx(0.803847577293 + 2.41154273188));
ptrdiff_t id0Idx = std::find(ids.begin(), ids.end(), id0) - ids.begin();
ptrdiff_t id1Idx = std::find(ids.begin(), ids.end(), id1) - ids.begin();
readdy::Vec3 forceOnParticle0{static_cast<readdy::scalar>(0.73205081),
static_cast<readdy::scalar>(0.73205081),
static_cast<readdy::scalar>(0.73205081)};
readdy::Vec3 forceOnParticle1{static_cast<readdy::scalar>(-1.26794919),
static_cast<readdy::scalar>(-1.26794919),
static_cast<readdy::scalar>(1.26794919)};
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, 1e-6);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, 1e-6);
}
SECTION("Spherical barrier") {
auto calculateForces = kernel->actions().calculateForces();
context.particleTypes().add("A", 1.0);
context.boxSize() = {{10, 10, 10}};
// add two particles, one on the outer edge getting pushed outside, one inside the sphere unaffected
auto id0 = kernel->addParticle("A", {2.1, 1., 1.});
auto id1 = kernel->addParticle("A", {1.1, 1., 1.});
readdy::Vec3 origin = {1.0, 0.9, 1.0};
double radius = 1.;
double height = 2.;
double width = 0.3;
context.potentials().addSphericalBarrier("A", height, width, origin, radius);
// record ids to get data-structure-indexes of the two particles later on
auto pObs = kernel->observe().particles(1);
std::vector<readdy::ParticleId> ids;
pObs->setCallback([&ids](const readdy::model::observables::Particles::result_type &result) {
const auto &recordedIds = std::get<1>(result);
ids.insert(ids.end(), recordedIds.begin(), recordedIds.end());
});
auto connParticles = kernel->connectObservable(pObs.get());
// also record forces
auto fObs = kernel->observe().forces(1);
std::vector<readdy::Vec3> collectedForces;
fObs->setCallback([&collectedForces](const readdy::model::observables::Forces::result_type &result) {
collectedForces.insert(collectedForces.end(), result.begin(), result.end());
});
auto connForces = kernel->connectObservable(fObs.get());
kernel->initialize();
calculateForces->perform();
kernel->evaluateObservables(1);
// the reference values were calculated numerically
REQUIRE(stateModel.energy() == Approx(1.51432015278));
auto id0Idx = std::find(ids.begin(), ids.end(), id0) - ids.begin();
auto id1Idx = std::find(ids.begin(), ids.end(), id1) - ids.begin();
readdy::Vec3 forceOnParticle0{static_cast<readdy::scalar>(9.2539372), static_cast<readdy::scalar>(0.84126702),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle1{static_cast<readdy::scalar>(0.), static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, kernel->doublePrecision() ? 1e-8 : 1e-5);
}
SECTION("Cylindrical inclusion") {
auto calculateForces = kernel->actions().calculateForces();
context.particleTypes().add("A", 1.0);
context.boxSize() = {{20, 20, 20}};
// particle 0 and 3 are outside, 1 and 2 inside of the cylinder
auto id0 = kernel->addParticle("A", {-1, -4, 1.});
auto id1 = kernel->addParticle("A", {0., -3., 3.});
auto id2 = kernel->addParticle("A", {1.5, -1., 5.});
auto id3 = kernel->addParticle("A", {4., -2., 8.});
readdy::Vec3 origin = {1., -2., 3.};
readdy::Vec3 normal = {0., 0., 1.};
double radius = 2.;
double forceConstant = 4.;
context.potentials().addCylinder("A", forceConstant, origin, normal, radius, true);
// record ids to get data-structure-indexes of the two particles later on
auto pObs = kernel->observe().particles(1);
std::vector<readdy::ParticleId> ids;
pObs->setCallback([&ids](const readdy::model::observables::Particles::result_type &result) {
const auto &recordedIds = std::get<1>(result);
ids.insert(ids.end(), recordedIds.begin(), recordedIds.end());
});
auto connParticles = kernel->connectObservable(pObs.get());
// also record forces
auto fObs = kernel->observe().forces(1);
std::vector<readdy::Vec3> collectedForces;
fObs->setCallback([&collectedForces](const readdy::model::observables::Forces::result_type &result) {
collectedForces.insert(collectedForces.end(), result.begin(), result.end());
});
auto connForces = kernel->connectObservable(fObs.get());
kernel->initialize();
calculateForces->perform();
kernel->evaluateObservables(1);
// the reference values were calculated by hand and evaluated numerically
REQUIRE(stateModel.energy() == Approx(3.37258300203048));
auto id0Idx = std::find(ids.begin(), ids.end(), id0) - ids.begin();
auto id1Idx = std::find(ids.begin(), ids.end(), id1) - ids.begin();
auto id2Idx = std::find(ids.begin(), ids.end(), id2) - ids.begin();
auto id3Idx = std::find(ids.begin(), ids.end(), id3) - ids.begin();
readdy::Vec3 forceOnParticle0{static_cast<readdy::scalar>(2.3431457505076203),
static_cast<readdy::scalar>(2.3431457505076203),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle1{static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle2{static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle3{static_cast<readdy::scalar>(-4.),
static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id2Idx], forceOnParticle2, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id3Idx], forceOnParticle3, kernel->doublePrecision() ? 1e-8 : 1e-5);
}
SECTION("Cylindrical exclusion") {
auto calculateForces = kernel->actions().calculateForces();
context.particleTypes().add("A", 1.0);
context.boxSize() = {{20, 20, 20}};
// particle 0 and 3 are outside, 1 and 2 inside of the cylinder
auto id0 = kernel->addParticle("A", {-1, -4, 1.});
auto id1 = kernel->addParticle("A", {0., -3., 3.});
auto id2 = kernel->addParticle("A", {1.5, -1., 5.});
auto id3 = kernel->addParticle("A", {4., -2., 8.});
readdy::Vec3 origin = {1., -2., 3.};
readdy::Vec3 normal = {0., 0., 1.};
double radius = 2.;
double forceConstant = 4.;
context.potentials().addCylinder("A", forceConstant, origin, normal, radius, false);
// record ids to get data-structure-indexes of the two particles later on
auto pObs = kernel->observe().particles(1);
std::vector<readdy::ParticleId> ids;
pObs->setCallback([&ids](const readdy::model::observables::Particles::result_type &result) {
const auto &recordedIds = std::get<1>(result);
ids.insert(ids.end(), recordedIds.begin(), recordedIds.end());
});
auto connParticles = kernel->connectObservable(pObs.get());
// also record forces
auto fObs = kernel->observe().forces(1);
std::vector<readdy::Vec3> collectedForces;
fObs->setCallback([&collectedForces](const readdy::model::observables::Forces::result_type &result) {
collectedForces.insert(collectedForces.end(), result.begin(), result.end());
});
auto connForces = kernel->connectObservable(fObs.get());
kernel->initialize();
calculateForces->perform();
kernel->evaluateObservables(1);
// the reference values were calculated by hand and evaluated numerically
REQUIRE(stateModel.energy() == Approx(2.2420195910160805));
auto id0Idx = std::find(ids.begin(), ids.end(), id0) - ids.begin();
auto id1Idx = std::find(ids.begin(), ids.end(), id1) - ids.begin();
auto id2Idx = std::find(ids.begin(), ids.end(), id2) - ids.begin();
auto id3Idx = std::find(ids.begin(), ids.end(), id3) - ids.begin();
readdy::Vec3 forceOnParticle0{static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle1{static_cast<readdy::scalar>(-1.6568542494923801),
static_cast<readdy::scalar>(-1.6568542494923801),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle2{static_cast<readdy::scalar>(0.5 * 3.155417527999327),
static_cast<readdy::scalar>(3.155417527999327),
static_cast<readdy::scalar>(0.)};
readdy::Vec3 forceOnParticle3{static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.),
static_cast<readdy::scalar>(0.)};
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id2Idx], forceOnParticle2, kernel->doublePrecision() ? 1e-8 : 1e-5);
readdy::testing::vec3eq(collectedForces[id3Idx], forceOnParticle3, kernel->doublePrecision() ? 1e-8 : 1e-5);
}
}
SECTION("Pair potentials") {
SECTION("Lennard-Jones") {
// test system where the particles are closer together than they should be, i.e.,
// the force should be repellent
auto calculateForces = kernel->actions().calculateForces();
// one particle type A
context.particleTypes().add("A", 1.0);
// large enough box
context.boxSize() = {{10, 10, 10}};
// particles are aligned in the x-y plane and have a distance of .09
auto id0 = kernel->addParticle("A", {0, 0, 0});
auto id1 = kernel->addParticle("A", {0, 0, .09});
auto id2 = kernel->addParticle("A", {2, 0, 0});
auto id3 = kernel->addParticle("A", {2, 0, .09});
// the potential has exponents 3 and 2, a cutoff distance of 1.0, does not shift the energy, a well depth
// of 1.0 and a zero-interaction distance of 0.1 (particle distance < sigma ==> repellent)
context.potentials().addLennardJones("A", "A", 3, 2, 1.0, false, 1.0, .1);
// record ids
auto pObs = kernel->observe().particles(1);
std::vector<readdy::ParticleId> ids;
pObs->setCallback([&ids](const readdy::model::observables::Particles::result_type& result) {
const auto& recordedIds = std::get<1>(result);
ids.insert(ids.end(), recordedIds.begin(), recordedIds.end());
});
auto connParticles = kernel->connectObservable(pObs.get());
// also record forces
auto fObs = kernel->observe().forces(1);
std::vector<readdy::Vec3> collectedForces;
fObs->setCallback([&collectedForces](const readdy::model::observables::Forces::result_type& result) {
collectedForces.insert(collectedForces.end(), result.begin(), result.end());
});
auto conn = kernel->connectObservable(fObs.get());
// we need to update the neighbor list as this is a pair potential
auto initNeighborList = kernel->actions().createNeighborList(context.calculateMaxCutoff());
initNeighborList->perform();
auto updateNeighborList = kernel->actions().updateNeighborList();
updateNeighborList->perform();
// calc forces
calculateForces->perform();
// give me results
kernel->evaluateObservables(1);
// the reference values were calculated numerically
REQUIRE(stateModel.energy() == Approx(2.0 * 0.925925925926).epsilon(1e-6));
auto id0Idx = std::find(ids.begin(), ids.end(), id0) - ids.begin();
auto id1Idx = std::find(ids.begin(), ids.end(), id1) - ids.begin();
auto id2Idx = std::find(ids.begin(), ids.end(), id2) - ids.begin();
auto id3Idx = std::find(ids.begin(), ids.end(), id3) - ids.begin();
readdy::Vec3 forceOnParticle0 {0, 0, static_cast<readdy::scalar>(-123.45679012)};
readdy::Vec3 forceOnParticle1 {0, 0, static_cast<readdy::scalar>(123.45679012)};
readdy::Vec3 forceOnParticle2 {0, 0, static_cast<readdy::scalar>(-123.45679012)};
readdy::Vec3 forceOnParticle3 {0, 0, static_cast<readdy::scalar>(123.45679012)};
if(kernel->singlePrecision()) {
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, 1e-4);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, 1e-4);
readdy::testing::vec3eq(collectedForces[id2Idx], forceOnParticle2, 1e-4);
readdy::testing::vec3eq(collectedForces[id3Idx], forceOnParticle3, 1e-4);
} else {
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, 1e-6);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, 1e-6);
readdy::testing::vec3eq(collectedForces[id2Idx], forceOnParticle2, 1e-6);
readdy::testing::vec3eq(collectedForces[id3Idx], forceOnParticle3, 1e-6);
}
}
SECTION("Screened electrostatics") {
auto calculateForces = kernel->actions().calculateForces();
context.periodicBoundaryConditions() = {{false, false, false}};
context.particleTypes().add("A", 1.0);
context.boxSize() = {{10, 10, 10}};
context.potentials().addBox("A", .001, {-4.9, -4.9, -4.9}, {9.8, 9.8, 9.8});
// distance of particles is 2.56515106768
auto id0 = kernel->addParticle("A", {0, 0, 0});
auto id1 = kernel->addParticle("A", {1.2, 1.5, -1.7});
auto electrostaticStrength = static_cast<readdy::scalar>(-1.);
auto screeningDepth = static_cast<readdy::scalar>(1.);
auto repulsionStrength = static_cast<readdy::scalar>(1.);
auto sigma = static_cast<readdy::scalar>(1.);
auto cutoff = static_cast<readdy::scalar>(8.);
unsigned int exponent = 6;
context.potentials().addScreenedElectrostatics("A", "A", electrostaticStrength, 1. / screeningDepth,
repulsionStrength, sigma, exponent, cutoff);
// record ids to get data-structure-indexes of the two particles later on
auto pObs = kernel->observe().particles(1);
std::vector<readdy::ParticleId> ids;
pObs->setCallback([&ids](const readdy::model::observables::Particles::result_type &result) {
const auto &recordedIds = std::get<1>(result);
ids.insert(ids.end(), recordedIds.begin(), recordedIds.end());
});
auto connParticles = kernel->connectObservable(pObs.get());
// also record forces
auto fObs = kernel->observe().forces(1);
std::vector<readdy::Vec3> collectedForces;
fObs->setCallback([&collectedForces](const readdy::model::observables::Forces::result_type &result) {
collectedForces.insert(collectedForces.end(), result.begin(), result.end());
});
auto conn = kernel->connectObservable(fObs.get());
// we need to update the neighbor list as this is a pair potential
auto initNeighborList = kernel->actions().createNeighborList(context.calculateMaxCutoff());
initNeighborList->perform();
auto updateNeighborList = kernel->actions().updateNeighborList();
updateNeighborList->perform();
// calc forces
calculateForces->perform();
// give me results
kernel->evaluateObservables(1);
// the reference values were calculated numerically
if(kernel->singlePrecision()) {
REQUIRE(stateModel.energy() == Approx(-0.0264715664281));
} else {
REQUIRE(stateModel.energy() == Approx(-0.0264715664281));
}
ptrdiff_t id0Idx = std::find(ids.begin(), ids.end(), id0) - ids.begin();
ptrdiff_t id1Idx = std::find(ids.begin(), ids.end(), id1) - ids.begin();
readdy::Vec3 forceOnParticle0{0.01565262, 0.01956577, static_cast<readdy::scalar>(-0.02217454)};
readdy::Vec3 forceOnParticle1{static_cast<readdy::scalar>(-0.01565262),
static_cast<readdy::scalar>(-0.01956577), 0.02217454};
readdy::testing::vec3eq(collectedForces[id0Idx], forceOnParticle0, 1e-8);
readdy::testing::vec3eq(collectedForces[id1Idx], forceOnParticle1, 1e-8);
}
}
}
| 57.826772 | 131 | 0.56713 | [
"vector",
"model"
] |
e604a32bdb4d08117946a25e9bd99b84abb454fc | 1,002 | cpp | C++ | cpp-leetcode/leetcode17-letter-combinations-of-a-phone-number_iterate.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode17-letter-combinations-of-a-phone-number_iterate.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode17-letter-combinations-of-a-phone-number_iterate.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if(digits == "") return {};
vector<string> res{""};
for(int i=0; i<digits.size(); i++)
{
vector<string> temp; // temp是本轮字符选择完成的结果
char ch = digits[i];
string curStr = dict[ch-'0'];
for(int j = 0; j < curStr.size(); j++)
for(int k = 0; k < res.size(); k++)
{
temp.push_back(res[k]+curStr[j]); // res[k] 是上一轮字符选择的结果
}
res = temp;
}
return res;
}
};
// Test
int main()
{
Solution sol;
string n = "25";
vector<string> res = sol.letterCombinations(n);
for(string s : res)
{
cout << s << endl;
}
return 0;
} | 22.772727 | 97 | 0.478044 | [
"vector"
] |
e6061a19cc8655b6fabf1b85810e14248db9ed05 | 2,720 | cpp | C++ | srcs/elements/Flag.cpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | 6 | 2020-03-13T16:45:13.000Z | 2022-03-30T18:20:48.000Z | srcs/elements/Flag.cpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | 191 | 2020-03-02T14:47:19.000Z | 2020-06-03T08:13:00.000Z | srcs/elements/Flag.cpp | tnicolas42/bomberman | 493d7243fabb1e5b6d5adfdcb5eb5973869b83a2 | [
"MIT"
] | null | null | null | #include "Flag.hpp"
#include "SceneGame.hpp"
#include "AudioManager.hpp"
// -- Constructors -------------------------------------------------------------
/**
* @brief Construct a new Flag:: Flag object
*
* @param game A reference to the SceneGame master object
*/
Flag::Flag(SceneGame &game) : AObject(game) {
type = Type::FLAG;
name = FLAG_STR;
destructible = true;
blockPropagation = true;
AudioManager::loadSound(FLAG_DESTROYED_SOUND);
_soundOfDeath = FLAG_DESTROYED_SOUND;
}
/**
* @brief Destroy the Flag:: Flag object
*/
Flag::~Flag() {
if (game.clearFromBoard(this, {position.x, position.z})) {
game.flags--;
}
}
/**
* @brief Construct a new Flag:: Flag object
*
* @param src The object to do the copy
*/
Flag::Flag(Flag const &src) : AObject(src) {
*this = src;
}
// -- Operators ----------------------------------------------------------------
/**
* @brief Copy this object
*
* @param rhs The object to copy
* @return Flag& A reference to the copied object
*/
Flag &Flag::operator=(Flag const &rhs) {
if ( this != &rhs ) {
AObject::operator=(rhs);
}
return *this;
}
// -- Methods ------------------------------------------------------------------
/**
* @brief Init Flag
*
* @return true on success
* @return false on failure
*/
bool Flag::init() {
AObject::init();
try {
// if exist, delete last model
if (_model)
delete _model;
_model = new Model(ModelsManager::getModel("server"), game.getDtTime(),
ETransform((position + glm::vec3(.5, 0, .5))));
}
catch(ModelsManager::ModelsManagerException const &e) {
logErr(e.what());
return false;
}
catch(OpenGLModel::ModelException const &e) {
logErr(e.what());
return false;
}
return true;
}
/**
* @brief update is called each frame.
*
* @return true if success
* @return false if failure
*/
bool Flag::update() {
return true;
}
/**
* @brief postUpdate is called each frame. After update.
*
* @return true if success
* @return false if failure
*/
bool Flag::postUpdate() {
if (active == false || alive == false)
delete this;
return true;
}
/**
* @brief draw is called each frame.
*
* @return true if success
* @return false if failure
*/
bool Flag::draw(Gui &gui) {
(void)gui;
// gui.drawCube(Block::FLAG, getPos());
// draw model
try {
_model->draw();
}
catch(OpenGLModel::ModelException const & e) {
logErr(e.what());
return false;
}
return true;
}
// -- Exceptions errors --------------------------------------------------------
Flag::FlagException::FlagException()
: std::runtime_error("Flag Exception") {}
Flag::FlagException::FlagException(const char* whatArg)
: std::runtime_error(std::string(std::string("FlagError: ") + whatArg).c_str()) {}
| 19.854015 | 82 | 0.591544 | [
"object",
"model"
] |
e607b91449fa8177f539a8528762c8b9a243056f | 788 | hpp | C++ | include/altacore/ast/try-catch-block.hpp | alta-lang/alta-core | 290ebcd94b4b2956fd34f5cd0e516e756d4fc219 | [
"MIT"
] | null | null | null | include/altacore/ast/try-catch-block.hpp | alta-lang/alta-core | 290ebcd94b4b2956fd34f5cd0e516e756d4fc219 | [
"MIT"
] | 6 | 2019-03-04T01:37:27.000Z | 2019-09-07T20:12:36.000Z | include/altacore/ast/try-catch-block.hpp | alta-lang/alta-core | 290ebcd94b4b2956fd34f5cd0e516e756d4fc219 | [
"MIT"
] | null | null | null | #ifndef ALTACORE_AST_TRY_CATCH_BLOCK_HPP
#define ALTACORE_AST_TRY_CATCH_BLOCK_HPP
#include "statement-node.hpp"
#include "block-node.hpp"
#include "type.hpp"
#include "../det/scope.hpp"
#include <vector>
namespace AltaCore {
namespace AST {
class TryCatchBlock: public StatementNode {
public:
virtual const NodeType nodeType();
std::shared_ptr<StatementNode> tryBlock = nullptr;
std::vector<std::string> catchIDs;
std::vector<std::pair<std::shared_ptr<Type>, std::shared_ptr<StatementNode>>> catchBlocks;
std::shared_ptr<StatementNode> catchAllBlock = nullptr;
TryCatchBlock() {};
ALTACORE_AST_DETAIL(TryCatchBlock);
ALTACORE_AST_VALIDATE;
};
};
};
#endif // ALTACORE_AST_TRY_CATCH_BLOCK_HPP
| 26.266667 | 98 | 0.696701 | [
"vector"
] |
e60c8a2cd13b4edf5d7caf668bf07ba60da007ae | 2,943 | cpp | C++ | test/test_lexer.cpp | madedit/aclang | 698ea6a56812f3702d63b6b4235a5eee8eaa0773 | [
"MIT"
] | 10 | 2015-01-27T09:16:29.000Z | 2021-05-07T16:39:05.000Z | test/test_lexer.cpp | madedit/aclang | 698ea6a56812f3702d63b6b4235a5eee8eaa0773 | [
"MIT"
] | null | null | null | test/test_lexer.cpp | madedit/aclang | 698ea6a56812f3702d63b6b4235a5eee8eaa0773 | [
"MIT"
] | 4 | 2015-01-27T09:45:05.000Z | 2021-05-07T16:39:06.000Z |
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <ac_lexer.h>
void test_lexer()
{
size_t length;
char *buffer;
#if 1
buffer=
" /* block /* *comment */ /+ \n"
" /+ // line comment +/\n"
"/= +/ /= / \n"
"x\"e0 af 80 00\"d \n"
" `abcdefghi`c \n"
" x\"f ff f\"w \n"
" \" \\t \xe4\xb8\x80 \\U0000FFff \" \n"
" \\n\\xff\\U00000001\n"
" 0e0 1.f .0 078.e10f 0x1.0p102 999f 0.e1f 1_e_1_ \n"
" 0b1_1_1_0 1 2 0x344L \n"
"/ /= . .. ... & &= && | |= || - -= -- + += ++ \n"
"< <= << <<= <> <>= > >= >>= >>>= >> >>> \n"
"! != !<> !<>= !< !<= !> !>= ( ) [ ] { } \n"
"? , ; : $ = == * *= % %= ^ ^= ~ ~= \n"
" a _slkdfjsldf_jk for(int a=10;a<=15;a++) a++;\n"
"void x=-10;\n"
;
length = strlen(buffer);
#else
std::vector<char> buf;
std::ifstream is;
is.open ("test.ac", std::ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
buf.resize(length);
buffer = &buf[0];
// read data as a block:
is.read (buffer,length);
is.close();
#endif
unsigned char *bufferEnd = (unsigned char*)(buffer+length);
acMsgHandler msghandler;
acLexer lexer(&msghandler);
acToken tk;
int ret;
tk.m_begin = (unsigned char*)buffer;
tk.m_beginLine = tk.m_endLine = 1;
while( (ret=lexer.next(tk, bufferEnd))==0 && tk.m_type != TOK_EOF)
{
acString str(tk.m_begin, tk.m_end);
if(tk.m_type!=TOK_EOL && tk.m_type!=TOK_SPACE)
printf("%d: line %d:\n%s\n", tk.m_type, tk.m_beginLine, str.c_str());
tk.m_begin = tk.m_end;
switch(tk.m_type)
{
case TOK_EOL:
{
}
break;
case TOK_FLOAT64:
{
printf(" --> tk.doubleValue = %f\n", tk.m_doubleValue);
}
break;
case TOK_FLOAT32:
{
printf(" --> tk.floatValue = %f\n", tk.m_doubleValue);
}
break;
case TOK_UNS32:
{
printf(" --> tk.uns32Value = %d\n", tk.m_integerValue);
}
break;
case TOK_UNS64:
{
printf(" --> tk.uns64Value = %d\n", tk.m_integerValue);
}
break;
case TOK_IDENTIFIER:
{
printf(" --> tt_identifier\n");
}
break;
}
tk.m_beginLine = tk.m_endLine;
}
if(ret<0)
{
acString str(tk.m_begin, tk.m_end);
printf("error occurred!: %d: line %d: [[%s]]\n", tk.m_type, tk.m_beginLine, str.c_str());
getchar();
}
}
| 25.153846 | 98 | 0.431532 | [
"vector"
] |
e63165349ef0c283e60363bd78485d6b24d7ee25 | 1,906 | cpp | C++ | sources/Renderer/Direct3D11/D3D11ObjectUtils.cpp | beldenfox/LLGL | 3a54125ebfa79bb06fccf8c413d308ff22186b52 | [
"BSD-3-Clause"
] | 1,403 | 2016-09-28T21:48:07.000Z | 2022-03-31T23:58:57.000Z | sources/Renderer/Direct3D11/D3D11ObjectUtils.cpp | beldenfox/LLGL | 3a54125ebfa79bb06fccf8c413d308ff22186b52 | [
"BSD-3-Clause"
] | 70 | 2016-10-13T20:15:58.000Z | 2022-01-12T23:51:12.000Z | sources/Renderer/Direct3D11/D3D11ObjectUtils.cpp | beldenfox/LLGL | 3a54125ebfa79bb06fccf8c413d308ff22186b52 | [
"BSD-3-Clause"
] | 122 | 2016-10-23T15:33:44.000Z | 2022-03-07T07:41:23.000Z | /*
* D3D11ObjectUtils.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "D3D11ObjectUtils.h"
#include <string>
#include <cstring>
namespace LLGL
{
// Declare custom object of "WKPDID_D3DDebugObjectName" as defined in <d3dcommon.h> to avoid linking with "dxguid.lib"
static const GUID g_WKPDID_D3DDebugObjectName = { 0x429b8c22, 0x9188, 0x4b0c, { 0x87,0x42,0xac,0xb0,0xbf,0x85,0xc2,0x00 } };
void D3D11SetObjectName(ID3D11DeviceChild* obj, const char* name)
{
if (obj != nullptr)
{
if (name != nullptr)
{
const std::size_t length = std::strlen(name);
obj->SetPrivateData(g_WKPDID_D3DDebugObjectName, static_cast<UINT>(length), name);
}
else
obj->SetPrivateData(g_WKPDID_D3DDebugObjectName, 0, nullptr);
}
}
void D3D11SetObjectNameSubscript(ID3D11DeviceChild* obj, const char* name, const char* subscript)
{
if (obj != nullptr)
{
if (name != nullptr)
{
std::string nameWithSubscript = name;
nameWithSubscript += subscript;
const std::size_t length = nameWithSubscript.size();
obj->SetPrivateData(g_WKPDID_D3DDebugObjectName, static_cast<UINT>(length), nameWithSubscript.c_str());
}
else
obj->SetPrivateData(g_WKPDID_D3DDebugObjectName, 0, nullptr);
}
}
void D3D11SetObjectNameIndexed(ID3D11DeviceChild* obj, const char* name, std::uint32_t index)
{
if (name != nullptr)
{
/* Append subscript to label */
std::string subscript = std::to_string(index);
D3D11SetObjectNameSubscript(obj, name, subscript.c_str());
}
else
D3D11SetObjectName(obj, nullptr);
}
} // /namespace LLGL
// ================================================================================
| 28.029412 | 124 | 0.627492 | [
"object"
] |
e633fb3eb79071f98c5801f8f92f6c355c0a9334 | 1,914 | hpp | C++ | src/map_storage.hpp | thealexhoar/Apollo | 60e92729375b6b18944274c62e0e3612b453e33f | [
"MIT"
] | 3 | 2017-09-16T03:57:18.000Z | 2018-05-29T22:38:23.000Z | src/map_storage.hpp | thealexhoar/Apollo | 60e92729375b6b18944274c62e0e3612b453e33f | [
"MIT"
] | null | null | null | src/map_storage.hpp | thealexhoar/Apollo | 60e92729375b6b18944274c62e0e3612b453e33f | [
"MIT"
] | null | null | null | //
// Created by alex on 18/02/18.
//
#pragma once
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <assert.h>
#include "entity.hpp"
#include "storage.hpp"
namespace apollo {
template<class C>
class MapStorage : public Storage<C> {
private:
std::vector<C> data_;
std::unordered_map<EIndex, size_t> data_mappings_;
std::unordered_set<Entity, EntityHash> entities_;
public:
MapStorage() : data_(), data_mappings_(), entities_() {}
bool add_for(const Entity& entity, C&& component) override {
if (entities_.count(entity) > 0) {
return false;
}
if (data_mappings_.count(entity.index) > 0) {
data_[data_mappings_[entity.index]] = component;
}
else {
data_mappings_[entity.index] = data_.size();
data_.push_back(component);
}
return true;
}
C& get_for(const Entity& entity) override {
assert(data_mappings_.count(entity.index) > 0);
auto index = data_mappings_.at(entity.index);
assert(data_.size() > index);
return data_[index];
}
bool has_for(const Entity& entity) override {
return entities_.count(entity) > 0;
}
const C& read_for(const Entity& entity) const override {
assert(data_mappings_.count(entity.index) > 0);
auto index = data_mappings_.at(entity.index);
assert(data_.size() > index);
return data_[index];
}
bool remove_for(const Entity& entity) override {
if (entities_.count(entity) == 0) {
return false;
}
entities_.erase(entity);
return true;
}
void update() override {}
};
}
| 25.184211 | 68 | 0.552769 | [
"vector"
] |
e639a91e8556ac40a8412828a8015dbe85f5d4ef | 4,671 | cpp | C++ | Project1/mainwindow.cpp | MarcLF/CuteTProject1 | fc2e2e596e5bce495dc059d29b3f36141ad33be5 | [
"Apache-2.0"
] | null | null | null | Project1/mainwindow.cpp | MarcLF/CuteTProject1 | fc2e2e596e5bce495dc059d29b3f36141ad33be5 | [
"Apache-2.0"
] | null | null | null | Project1/mainwindow.cpp | MarcLF/CuteTProject1 | fc2e2e596e5bce495dc059d29b3f36141ad33be5 | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_rendering.h"
#include "inspector.h"
#include "hierarchy.h"
#include "myopenglwidget.h"
#include "lightdirection.h"
#include "dofoptions.h"
#include "mesh.h"
#include "resource.h"
#include "entity.h"
#include "componentrender.h"
#include <QFile>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <iostream>
MainWindow *MainWindow::window;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
window = this;
resources = new Resource();
hierarchy = new Hierarchy(this);
ui->Hierarchywidget->setWidget(hierarchy);
inspector = new Inspector(this);
ui->Inspectorwidget->setWidget(inspector);
openGLWidget = new MyOpenGLWidget(this);
ui->Scene->setWidget(openGLWidget);
lightDirection = new LightDirection(openGLWidget);
lightColorPicker = new QColorDialog();
connect(ui->actionLightColor, SIGNAL(triggered()), this, SLOT(onLightColor()));
connect(lightColorPicker, SIGNAL(accepted()), this, SLOT(changeLightColor()));
dofOptions = new DoFOptions(openGLWidget);
connect(ui->actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(ui->actionAlbedo, SIGNAL(triggered()), this, SLOT(ChangeToAlbedo()));
connect(ui->actionLighting, SIGNAL(triggered()), this, SLOT(ChangeToLighting()));
connect(ui->actionNormals, SIGNAL(triggered()), this, SLOT(ChangeToNormals()));
connect(ui->actionDepth_test, SIGNAL(triggered()), this, SLOT(ChangeToDepthTest()));
connect(ui->actionBlur, SIGNAL(triggered()), this, SLOT(SwitchBlur()));
connect(ui->actionDepth_of_Field, SIGNAL(triggered()), this, SLOT(SwitchDoF()));
connect(ui->actionLight_Settings, SIGNAL(triggered()), this, SLOT(OpenLightSettings()));
connect(ui->actionOptions, SIGNAL(triggered()), this, SLOT(OpenDoFSettings()));
setAcceptDrops(true);
}
MainWindow::~MainWindow()
{
delete resources;
delete ui;
}
void MainWindow::ChangeToAlbedo()
{
openGLWidget->SetRendererDisplay(0);
}
void MainWindow::ChangeToLighting()
{
openGLWidget->SetRendererDisplay(1);
}
void MainWindow::ChangeToNormals()
{
openGLWidget->SetRendererDisplay(2);
}
void MainWindow::ChangeToDepthTest()
{
openGLWidget->SetRendererDisplay(3);
}
void MainWindow::OpenLightSettings()
{
lightDirection->show();
}
void MainWindow::OpenDoFSettings()
{
dofOptions->show();
}
void MainWindow::onLightColor()
{
lightColorPicker->show();
}
void MainWindow::changeLightColor()
{
openGLWidget->SetLightColor(QVector3D(lightColorPicker->currentColor().red()/255.0f, lightColorPicker->currentColor().green()/255.0f, lightColorPicker->currentColor().blue()/255.0f));
}
void MainWindow::SwitchBlur()
{
openGLWidget->SwitchBlur();
}
void MainWindow::SwitchDoF()
{
openGLWidget->SwitchDoF();
}
Inspector *MainWindow::GetInspector()
{
return inspector;
}
Hierarchy *MainWindow::GetHierarchy()
{
return hierarchy;
}
Resource *MainWindow::GetResources()
{
return resources;
}
MainWindow * MainWindow::GetWindow()
{
return window;
}
void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
if (e->mimeData()->hasUrls()) {
e->acceptProposedAction();
}
}
void MainWindow::dropEvent(QDropEvent *e)
{
foreach (const QUrl &url, e->mimeData()->urls())
{
QString fileName = url.toLocalFile();
QString extension = fileName.section('.', -1);
QString modelName = fileName.section('/', -1);
if(extension == "obj")
{
Entity* temp = nullptr;
Mesh* isLoaded = resources->GetModel(modelName);
if(isLoaded != nullptr)
{
temp = hierarchy->AddEntityWithMesh(isLoaded);
}
else
{
hierarchy->UpdateComboBoxes(modelName);
temp = hierarchy->AddEntityWithObj(fileName);
}
if(temp != nullptr)
{
ComponentRender* renderComp = (ComponentRender*)temp->GetComponent(Component_Render);
if(renderComp != nullptr)
{
for(auto it : resources->GetModelMap().keys())
{
if(modelName == it)
{
renderComp->AddModelToComboBox(it, true);
}
else
{
renderComp->AddModelToComboBox(it);
}
}
}
}
}
}
}
| 24.455497 | 187 | 0.626204 | [
"mesh"
] |
e63d005e4d5db73682ebf5b59860cacd494c2d3e | 4,498 | cc | C++ | DPGAnalysis/SiStripTools/src/RunHistogramManager.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DPGAnalysis/SiStripTools/src/RunHistogramManager.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | DPGAnalysis/SiStripTools/src/RunHistogramManager.cc | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #include "DPGAnalysis/SiStripTools/interface/RunHistogramManager.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TProfile.h"
#include "TProfile2D.h"
BaseHistoParams::BaseHistoParams() { }
BaseHistoParams::~BaseHistoParams() { }
/*
void BaseHistoParams::beginRun(const edm::Run& iRun, TFileDirectory& subrun) {
beginRun(iRun.run(),subrun);
}
*/
RunHistogramManager::RunHistogramManager(edm::ConsumesCollector& iC, const bool fillHistograms):
_fillHistograms(fillHistograms),
_histograms(),
_conditionsInRunToken(iC.consumes<edm::ConditionsInRunBlock,edm::InRun>(edm::InputTag("conditionsInEdm"))) {}
RunHistogramManager::RunHistogramManager(edm::ConsumesCollector&& iC, const bool fillHistograms):
_fillHistograms(fillHistograms),
_histograms(),
_conditionsInRunToken(iC.consumes<edm::ConditionsInRunBlock,edm::InRun>(edm::InputTag("conditionsInEdm"))) {}
TH1F** RunHistogramManager::makeTH1F(const char* name, const char* title, const unsigned int nbinx, const double xmin, const double xmax) {
TH1F** pointer =new TH1F*(0);
BaseHistoParams* hp = new HistoParams<TH1F>(pointer,"TH1F",name,title,nbinx,xmin,xmax);
_histograms.push_back(hp);
LogDebug("TH1Fmade") << "Histogram " << name << " " << title << " pre-booked:" << _histograms.size();
return pointer;
}
RunHistogramManager::~RunHistogramManager() {
for(std::vector<BaseHistoParams*>::const_iterator hp=_histograms.begin();hp!=_histograms.end();++hp) {
delete *hp;
}
LogDebug("Destructor") << "All BaseHistoParams destroyed ";
}
TProfile** RunHistogramManager::makeTProfile(const char* name, const char* title, const unsigned int nbinx, const double xmin, const double xmax) {
TProfile** pointer =new TProfile*(0);
BaseHistoParams* hp = new HistoParams<TProfile>(pointer,"TProfile",name,title,nbinx,xmin,xmax);
_histograms.push_back(hp);
LogDebug("TProfilemade") << "Histogram " << name << " " << title << " pre-booked:" << _histograms.size();
return pointer;
}
TH2F** RunHistogramManager::makeTH2F(const char* name, const char* title, const unsigned int nbinx, const double xmin, const double xmax, const unsigned int nbiny, const double ymin, const double ymax ) {
TH2F** pointer = new TH2F*(0);
BaseHistoParams* hp = new HistoParams<TH2F>(pointer,"TH2F",name,title,nbinx,xmin,xmax,nbiny,ymin,ymax);
_histograms.push_back(hp);
LogDebug("TH2Fmade") << "Histogram " << name << " " << title << " pre-booked :" << _histograms.size();
return pointer;
}
TProfile2D** RunHistogramManager::makeTProfile2D(const char* name, const char* title, const unsigned int nbinx, const double xmin, const double xmax, const unsigned int nbiny, const double ymin, const double ymax ) {
TProfile2D** pointer = new TProfile2D*(0);
BaseHistoParams* hp = new HistoParams<TProfile2D>(pointer,"TProfile2D",name,title,nbinx,xmin,xmax,nbiny,ymin,ymax);
_histograms.push_back(hp);
LogDebug("TProfile2Dmade") << "Histogram " << name << " " << title << " pre-booked :" << _histograms.size();
return pointer;
}
void RunHistogramManager::beginRun(const edm::Run& iRun) {
edm::Service<TFileService> tfserv;
beginRun(iRun, tfserv->tFileDirectory());
}
void RunHistogramManager::beginRun(const edm::Run& iRun, TFileDirectory& subdir) {
if(!_fillHistograms) {
beginRun(iRun.run(),subdir);
}
else {
unsigned int fillnum = 0;
edm::Handle<edm::ConditionsInRunBlock> cirb;
iRun.getByToken(_conditionsInRunToken,cirb);
if(!cirb.failedToGet() && cirb.isValid()) fillnum=cirb->lhcFillNumber;
beginRun(fillnum,subdir);
}
}
void RunHistogramManager::beginRun(const unsigned int irun) {
edm::Service<TFileService> tfserv;
beginRun(irun, tfserv->tFileDirectory());
}
void RunHistogramManager::beginRun(const unsigned int irun, TFileDirectory& subdir) {
// create/go to the run subdirectory
char fillrun[30];
if(!_fillHistograms) {
sprintf(fillrun,"%s","run");
}
else {
sprintf(fillrun,"%s","fill");
}
char dirname[300];
sprintf(dirname,"%s_%d",fillrun,irun);
TFileDirectory subrun = subdir.mkdir(dirname);
// loop on the histograms and update the pointer references
for(unsigned int ih=0;ih<_histograms.size();++ih) {
_histograms[ih]->beginRun(irun,subrun,fillrun);
}
}
| 29.398693 | 216 | 0.721654 | [
"vector"
] |
e656c56ed89d686db091cfad5c9cba634b35b8d8 | 28,846 | cpp | C++ | bin/evoef/EvoEF/src/ProgramFunction.cpp | tommyhuangthu/SSIPe | 47a3043b7f07dbc55906e0ea653d32d7de8502c2 | [
"MIT"
] | 7 | 2020-01-12T01:41:27.000Z | 2021-08-12T05:13:37.000Z | bin/evoef/EvoEF/src/ProgramFunction.cpp | tommyhuangthu/SSIPe | 47a3043b7f07dbc55906e0ea653d32d7de8502c2 | [
"MIT"
] | null | null | null | bin/evoef/EvoEF/src/ProgramFunction.cpp | tommyhuangthu/SSIPe | 47a3043b7f07dbc55906e0ea653d32d7de8502c2 | [
"MIT"
] | 2 | 2020-03-27T11:13:26.000Z | 2021-01-14T22:26:31.000Z | /*******************************************************************************************************************************
This file is a part of the EvoDesign physical Energy Function (EvoEF)
Copyright (c) 2019 Xiaoqiang Huang (tommyhuangthu@foxmail.com, xiaoqiah@umich.edu)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************************************************/
#include "ProgramFunction.h"
#include <string.h>
#include <ctype.h>
int EvoEF_help(){
printf(
"EvoEF program options:\n\n"
"Basic OPTIONS:\n"
"Usage: EvoEF [OPTIONS] [pdbfile]\n"
" [pdbfile] input a valid pdb format file\n"
" -v print verion info of EvoEF\n"
" -h print help message of EvoEF\n"
" -c arg choose your computation type:\n"
" AnalyseComplex\n"
" Stability\n"
" BuildModel\n"
" -d arg debug, produce more output\n"
" -f arg config file location\n"
" -o arg output file location\n"
);
return Success;
}
int EvoEF_version(){
printf("EvoDesign Force Field version 1.0\n");
return Success;
}
int EvoEF_interface(){
printf("******************************************************\n");
printf("* EvoDesign Energy Function *\n");
printf("* *\n");
printf("* Copyright (c) Xiaoqiang Huang *\n");
printf("* tommyhuangthu@foxmail.com, xiaoqiah@umich.edu *\n");
printf("* The Yang Zhang Lab *\n");
printf("* Dept. of Computational Medicine & Bioinformatics *\n");
printf("* Medical School *\n");
printf("* University of Michigan *\n");
printf("******************************************************\n");
return Success;
}
BOOL CheckCommandName(char* queryname){
int MAX_CMD_NUM = 100;
char *supportedcmd[] = {
"RepairStructure",
"ComputeStability",
"ComputeBinding",
"BuildMutant",
"ComputeResiEnergy",
"OptimizeHydrogen",
"ShowResiComposition",
NULL
};
BOOL exist = FALSE;
for(int i = 0; i < MAX_CMD_NUM; i++){
if(supportedcmd[i] == NULL) break;
else{
if(strcmp(queryname, supportedcmd[i]) == 0){
exist = TRUE;
break;
}
}
}
return exist;
}
int EvoEF_Stability(Structure *pStructure, double *energyTerms){
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++) energyTerms[i] = 0.0;
int aas[20]={0}; //ACDEFGHIKLMNPQRSTVWY, only for regular amino acid
StructureGetAminoAcidComposition(pStructure, aas);
// if the structure is composed of several chains, the residue position could be different in the whole structure from that in the separate chain
StructureComputeResiduePosition(pStructure);
for(int i = 0; i < StructureGetChainCount(pStructure); i++){
Chain *pChainI = StructureGetChain(pStructure,i);
for(int ir = 0; ir < ChainGetResidueCount(pChainI); ir++){
Residue *pResIR = ChainGetResidue(pChainI,ir);
double ratio1 = CalcResidueBuriedRatio(pResIR);
double refer=0.0;
ResidueReferenceEnergy(pResIR, energyTerms);
EVOEF_EnergyResidueSelfEnergy(pResIR,ratio1,energyTerms);
for(int is = ir+1; is < ChainGetResidueCount(pChainI); is++){
Residue *pResIS = ChainGetResidue(pChainI,is);
double ratio2 = CalcResidueBuriedRatio(pResIS);
double ratio12 = CalcAverageBuriedRatio(ratio1, ratio2);
if(is==ir+1) EVOEF_EnergyResidueAndNextResidue(pResIR,pResIS,ratio12,energyTerms);
else EVOEF_EnergyResidueAndOtherResidueSameChain(pResIR,pResIS,ratio12,energyTerms);
}
for(int k = i+1; k < StructureGetChainCount(pStructure); k++){
Chain *pChainK = StructureGetChain(pStructure,k);
for(int ks = 0; ks < ChainGetResidueCount(pChainK); ks++){
Residue *pResKS = ChainGetResidue(pChainK,ks);
double ratio2 = CalcResidueBuriedRatio(pResKS);
double ratio12 = CalcAverageBuriedRatio(ratio1, ratio2);
EVOEF_EnergyResidueAndOtherResidueDifferentChain(pResIR,pResKS,ratio12,energyTerms);
}
}
}
}
//total energy: weighted
EnergyTermWeighting(energyTerms);
for(int i = 1; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTerms[0] += energyTerms[i];
}
//energy term details: not weighted
printf("\nStructure energy details:\n");
printf("reference_ALA = %8.2f\n", energyTerms[21]);
printf("reference_CYS = %8.2f\n", energyTerms[22]);
printf("reference_ASP = %8.2f\n", energyTerms[23]);
printf("reference_GLU = %8.2f\n", energyTerms[24]);
printf("reference_PHE = %8.2f\n", energyTerms[25]);
printf("reference_GLY = %8.2f\n", energyTerms[26]);
printf("reference_HIS = %8.2f\n", energyTerms[27]);
printf("reference_ILE = %8.2f\n", energyTerms[28]);
printf("reference_LYS = %8.2f\n", energyTerms[29]);
printf("reference_LEU = %8.2f\n", energyTerms[30]);
printf("reference_MET = %8.2f\n", energyTerms[31]);
printf("reference_ASN = %8.2f\n", energyTerms[32]);
printf("reference_PRO = %8.2f\n", energyTerms[33]);
printf("reference_GLN = %8.2f\n", energyTerms[34]);
printf("reference_ARG = %8.2f\n", energyTerms[35]);
printf("reference_SER = %8.2f\n", energyTerms[36]);
printf("reference_THR = %8.2f\n", energyTerms[37]);
printf("reference_VAL = %8.2f\n", energyTerms[38]);
printf("reference_TRP = %8.2f\n", energyTerms[39]);
printf("reference_TYR = %8.2f\n", energyTerms[40]);
printf("intraR_vdwatt = %8.2f\n", energyTerms[6]);
printf("intraR_vdwrep = %8.2f\n", energyTerms[7]);
printf("intraR_electr = %8.2f\n", energyTerms[8]);
printf("intraR_deslvP = %8.2f\n", energyTerms[9]);
printf("intraR_deslvH = %8.2f\n", energyTerms[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTerms[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTerms[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTerms[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTerms[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTerms[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTerms[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTerms[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTerms[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTerms[49]);
printf("interS_vdwatt = %8.2f\n", energyTerms[1]);
printf("interS_vdwrep = %8.2f\n", energyTerms[2]);
printf("interS_electr = %8.2f\n", energyTerms[3]);
printf("interS_deslvP = %8.2f\n", energyTerms[4]);
printf("interS_deslvH = %8.2f\n", energyTerms[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTerms[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTerms[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTerms[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTerms[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTerms[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTerms[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTerms[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTerms[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTerms[19]);
printf("interD_vdwatt = %8.2f\n", energyTerms[51]);
printf("interD_vdwrep = %8.2f\n", energyTerms[52]);
printf("interD_electr = %8.2f\n", energyTerms[53]);
printf("interD_deslvP = %8.2f\n", energyTerms[54]);
printf("interD_deslvH = %8.2f\n", energyTerms[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTerms[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTerms[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTerms[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTerms[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTerms[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTerms[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTerms[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTerms[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTerms[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n\n", energyTerms[0]);
return Success;
}
int EvoEF_AnalyseComplex(Structure *pStructure, double *energyTerms){
double energyTermsStructure[MAX_EVOEF_ENERGY_TERM_NUM];
double energyTermsChain[MAX_EVOEF_ENERGY_TERM_NUM];
double energyTermsChainSum[MAX_EVOEF_ENERGY_TERM_NUM];
for(int i = 0; i < MAX_EVOEF_ENERGY_TERM_NUM; i++){
energyTermsChain[i] = 0.0;
energyTermsStructure[i] = 0.0;
energyTermsChainSum[i] = 0.0;
}
EvoEF_Stability(pStructure, energyTermsStructure);
for(int i = 0; i < StructureGetChainCount(pStructure); i++){
EvoEF_ComputeChainStability(pStructure, i, energyTermsChain);
for(int j = 0; j < MAX_EVOEF_ENERGY_TERM_NUM; j++){
energyTermsChainSum[j] += energyTermsChain[j];
}
}
// energy terms are weighted during the calculation, don't weight them for the difference
printf("Binding energy details:\n");
printf("reference_ALA = %8.2f\n", energyTermsStructure[21] - energyTermsChainSum[21]);
printf("reference_CYS = %8.2f\n", energyTermsStructure[22] - energyTermsChainSum[22]);
printf("reference_ASP = %8.2f\n", energyTermsStructure[23] - energyTermsChainSum[23]);
printf("reference_GLU = %8.2f\n", energyTermsStructure[24] - energyTermsChainSum[24]);
printf("reference_PHE = %8.2f\n", energyTermsStructure[25] - energyTermsChainSum[25]);
printf("reference_GLY = %8.2f\n", energyTermsStructure[26] - energyTermsChainSum[26]);
printf("reference_HIS = %8.2f\n", energyTermsStructure[27] - energyTermsChainSum[27]);
printf("reference_ILE = %8.2f\n", energyTermsStructure[28] - energyTermsChainSum[28]);
printf("reference_LYS = %8.2f\n", energyTermsStructure[29] - energyTermsChainSum[29]);
printf("reference_LEU = %8.2f\n", energyTermsStructure[30] - energyTermsChainSum[30]);
printf("reference_MET = %8.2f\n", energyTermsStructure[31] - energyTermsChainSum[31]);
printf("reference_ASN = %8.2f\n", energyTermsStructure[32] - energyTermsChainSum[32]);
printf("reference_PRO = %8.2f\n", energyTermsStructure[33] - energyTermsChainSum[33]);
printf("reference_GLN = %8.2f\n", energyTermsStructure[34] - energyTermsChainSum[34]);
printf("reference_ARG = %8.2f\n", energyTermsStructure[35] - energyTermsChainSum[35]);
printf("reference_SER = %8.2f\n", energyTermsStructure[36] - energyTermsChainSum[36]);
printf("reference_THR = %8.2f\n", energyTermsStructure[37] - energyTermsChainSum[37]);
printf("reference_VAL = %8.2f\n", energyTermsStructure[38] - energyTermsChainSum[38]);
printf("reference_TRP = %8.2f\n", energyTermsStructure[39] - energyTermsChainSum[39]);
printf("reference_TYR = %8.2f\n", energyTermsStructure[40] - energyTermsChainSum[40]);
printf("intraR_vdwatt = %8.2f\n", energyTermsStructure[6] - energyTermsChainSum[6]);
printf("intraR_vdwrep = %8.2f\n", energyTermsStructure[7] - energyTermsChainSum[7]);
printf("intraR_electr = %8.2f\n", energyTermsStructure[8] - energyTermsChainSum[8]);
printf("intraR_deslvP = %8.2f\n", energyTermsStructure[9] - energyTermsChainSum[9]);
printf("intraR_deslvH = %8.2f\n", energyTermsStructure[10] - energyTermsChainSum[10]);
printf("intraR_hbbbbb_dis = %8.2f\n", energyTermsStructure[41] - energyTermsChainSum[41]);
printf("intraR_hbbbbb_the = %8.2f\n", energyTermsStructure[42] - energyTermsChainSum[42]);
printf("intraR_hbbbbb_phi = %8.2f\n", energyTermsStructure[43] - energyTermsChainSum[43]);
printf("intraR_hbscbb_dis = %8.2f\n", energyTermsStructure[44] - energyTermsChainSum[44]);
printf("intraR_hbscbb_the = %8.2f\n", energyTermsStructure[45] - energyTermsChainSum[45]);
printf("intraR_hbscbb_phi = %8.2f\n", energyTermsStructure[46] - energyTermsChainSum[46]);
printf("intraR_hbscsc_dis = %8.2f\n", energyTermsStructure[47] - energyTermsChainSum[47]);
printf("intraR_hbscsc_the = %8.2f\n", energyTermsStructure[48] - energyTermsChainSum[48]);
printf("intraR_hbscsc_phi = %8.2f\n", energyTermsStructure[49] - energyTermsChainSum[49]);
printf("interS_vdwatt = %8.2f\n", energyTermsStructure[1] - energyTermsChainSum[1]);
printf("interS_vdwrep = %8.2f\n", energyTermsStructure[2] - energyTermsChainSum[2]);
printf("interS_electr = %8.2f\n", energyTermsStructure[3] - energyTermsChainSum[3]);
printf("interS_deslvP = %8.2f\n", energyTermsStructure[4] - energyTermsChainSum[4]);
printf("interS_deslvH = %8.2f\n", energyTermsStructure[5] - energyTermsChainSum[5]);
printf("interS_hbbbbb_dis = %8.2f\n", energyTermsStructure[11] - energyTermsChainSum[11]);
printf("interS_hbbbbb_the = %8.2f\n", energyTermsStructure[12] - energyTermsChainSum[12]);
printf("interS_hbbbbb_phi = %8.2f\n", energyTermsStructure[13] - energyTermsChainSum[13]);
printf("interS_hbscbb_dis = %8.2f\n", energyTermsStructure[14] - energyTermsChainSum[14]);
printf("interS_hbscbb_the = %8.2f\n", energyTermsStructure[15] - energyTermsChainSum[15]);
printf("interS_hbscbb_phi = %8.2f\n", energyTermsStructure[16] - energyTermsChainSum[16]);
printf("interS_hbscsc_dis = %8.2f\n", energyTermsStructure[17] - energyTermsChainSum[17]);
printf("interS_hbscsc_the = %8.2f\n", energyTermsStructure[18] - energyTermsChainSum[18]);
printf("interS_hbscsc_phi = %8.2f\n", energyTermsStructure[19] - energyTermsChainSum[19]);
printf("interD_vdwatt = %8.2f\n", energyTermsStructure[51] - energyTermsChainSum[51]);
printf("interD_vdwrep = %8.2f\n", energyTermsStructure[52] - energyTermsChainSum[52]);
printf("interD_electr = %8.2f\n", energyTermsStructure[53] - energyTermsChainSum[53]);
printf("interD_deslvP = %8.2f\n", energyTermsStructure[54] - energyTermsChainSum[54]);
printf("interD_deslvH = %8.2f\n", energyTermsStructure[55] - energyTermsChainSum[55]);
printf("interD_hbbbbb_dis = %8.2f\n", energyTermsStructure[61] - energyTermsChainSum[61]);
printf("interD_hbbbbb_the = %8.2f\n", energyTermsStructure[62] - energyTermsChainSum[62]);
printf("interD_hbbbbb_phi = %8.2f\n", energyTermsStructure[63] - energyTermsChainSum[63]);
printf("interD_hbscbb_dis = %8.2f\n", energyTermsStructure[64] - energyTermsChainSum[64]);
printf("interD_hbscbb_the = %8.2f\n", energyTermsStructure[65] - energyTermsChainSum[65]);
printf("interD_hbscbb_phi = %8.2f\n", energyTermsStructure[66] - energyTermsChainSum[66]);
printf("interD_hbscsc_dis = %8.2f\n", energyTermsStructure[67] - energyTermsChainSum[67]);
printf("interD_hbscsc_the = %8.2f\n", energyTermsStructure[68] - energyTermsChainSum[68]);
printf("interD_hbscsc_phi = %8.2f\n", energyTermsStructure[69] - energyTermsChainSum[69]);
printf("----------------------------------------------------\n");
printf("Total = %8.2f\n", energyTermsStructure[0] - energyTermsChainSum[0]);
return Success;
}
//this function is used to build the structure model of mutations
int EvoEF_BuildModel(Structure* pStructure, char* mutantfile, RotamerLib* rotlib, AtomParamsSet* atomParams,ResiTopoSet* resiTopos, char* pdbid){
FileReader fr;
FileReaderCreate(&fr, mutantfile);
int mutantcount = FileReaderGetLineCount(&fr);
if(mutantcount<=0){
printf("There is no mutant found in the mutant file\n");
return DataNotExistError;
}
StringArray* mutants = (StringArray*)malloc(sizeof(StringArray)*mutantcount);
char line[MAX_LENGTH_ONE_LINE_IN_FILE+1];
int mutantIndex=0;
while(!FAILED(FileReaderGetNextLine(&fr, line))){
StringArrayCreate(&mutants[mutantIndex]);
StringArraySplitString(&mutants[mutantIndex], line, ',');
char lastMutant[MAX_LENGTH_ONE_LINE_IN_FILE+1];
int lastmutindex = StringArrayGetCount(&mutants[mutantIndex])-1;
strcpy(lastMutant, StringArrayGet(&mutants[mutantIndex], lastmutindex));
//deal with the last char of the last single mutant
if((!isdigit(lastMutant[strlen(lastMutant)-1])) && !isalpha(lastMutant[strlen(lastMutant)-1])){
lastMutant[strlen(lastMutant)-1] = '\0';
}
StringArraySet(&mutants[mutantIndex], lastmutindex, lastMutant);
mutantIndex++;
}
FileReaderDestroy(&fr);
for(int mutantIndex = 0; mutantIndex < mutantcount; mutantIndex++){
//initialize designsites first
StructureInitializeDesignSites(pStructure);
//for each mutant, build the rotamer-tree
IntArray mutantArray,rotamersArray;
IntArrayCreate(&mutantArray,0);
IntArrayCreate(&rotamersArray,0);
for(int cycle=0; cycle<StringArrayGetCount(&mutants[mutantIndex]); cycle++){
char mutstr[10];
char aa1, chn, aa2;
int posInChain;
strcpy(mutstr, StringArrayGet(&mutants[mutantIndex], cycle));
sscanf(mutstr, "%c%c%d%c", &aa1, &chn, &posInChain, &aa2);
int chainIndex = -1, residueIndex = -1;
char chainname[MAX_LENGTH_CHAIN_NAME]; chainname[0] = chn; chainname[1] = '\0';
StructureFindChain(pStructure, chainname, &chainIndex);
if(chainIndex==-1){
printf("in file %s function %s() line %d, cannot find mutation %s\n", __FILE__, __FUNCTION__, __LINE__, mutstr);
exit(ValueError);
}
ChainFindResidueByPosInChain(StructureGetChain(pStructure, chainIndex), posInChain, &residueIndex);
if(residueIndex==-1){
printf("in file %s function %s() line %d, cannot find mutation %s\n", __FILE__, __FUNCTION__, __LINE__, mutstr);
exit(ValueError);
}
char mutaatype[MAX_LENGTH_RESIDUE_NAME];
OneLetterAAToThreeLetterAA(aa2, mutaatype);
StringArray designType, patchType;
StringArrayCreate(&designType);
StringArrayCreate(&patchType);
// for histidine, the default mutaatype is HSD, we need to add HSE
StringArrayAppend(&designType, mutaatype); StringArrayAppend(&patchType, "");
if(aa2=='H'){StringArrayAppend(&designType, "HSE"); StringArrayAppend(&patchType, "");}
ProteinSiteBuildMutatedRotamers(pStructure, chainIndex, residueIndex, rotlib, atomParams, resiTopos, &designType, &patchType);
IntArrayAppend(&mutantArray, chainIndex);
IntArrayAppend(&mutantArray, residueIndex);
IntArrayAppend(&rotamersArray,chainIndex);
IntArrayAppend(&rotamersArray,residueIndex);
StringArrayDestroy(&designType);
StringArrayDestroy(&patchType);
}
// for each mutant, find the surrounding residues and build the wild-type rotamer-tree
for(int ii=0; ii<IntArrayGetLength(&mutantArray); ii+=2){
int chainIndex = IntArrayGet(&mutantArray,ii);
int resiIndex = IntArrayGet(&mutantArray,ii+1);
Residue *pResi1 = ChainGetResidue(StructureGetChain(pStructure, chainIndex), resiIndex);
for(int j = 0; j < StructureGetChainCount(pStructure); ++j){
Chain* pChain = StructureGetChain(pStructure,j);
for(int k=0; k<ChainGetResidueCount(pChain); k++){
Residue* pResi2 = ChainGetResidue(pChain,k);
if(AtomArrayCalcMinDistance(&pResi1->atoms,&pResi2->atoms)<VDW_DISTANCE_CUTOFF){
if(pResi2->designSiteType==Type_ResidueDesignType_Fixed){
ProteinSiteBuildWildtypeRotamers(pStructure,j,k,rotlib,atomParams,resiTopos);
ProteinSiteAddCrystalRotamer(pStructure,j,k,resiTopos);
IntArrayAppend(&rotamersArray,j);
IntArrayAppend(&rotamersArray,k);
}
}
}
}
}
// optimization rotamers sequentially
printf("EvoEF Building Mutation Model %d, the following sites will be optimized:\n",mutantIndex+1);
IntArrayShow(&rotamersArray);
printf("\n");
for(int cycle=0; cycle<3; cycle++){
printf("optimization cycle %d ...\n",cycle+1);
for(int ii=0; ii<IntArrayGetLength(&rotamersArray); ii+=2){
int chainIndex = IntArrayGet(&rotamersArray, ii);
int resiIndex = IntArrayGet(&rotamersArray, ii+1);
//ProteinSiteOptimizeRotamer(pStructure, chainIndex, resiIndex);
ProteinSiteOptimizeRotamerLocally(pStructure,chainIndex,resiIndex,1.0);
}
}
IntArrayDestroy(&mutantArray);
IntArrayDestroy(&rotamersArray);
//remember to delete rotamers for previous mutant
StructureDeleteRotamers(pStructure);
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL)
sprintf(modelfile,"%s_Model_%d.pdb",pdbid,mutantIndex+1);
else
sprintf(modelfile,"EvoEF_Model_%d.pdb",mutantIndex+1);
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <BuildMutant>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
}
return Success;
}
int EvoEF_RepairPDB(Structure* pStructure, RotamerLib* rotlib, AtomParamsSet* atomParams,ResiTopoSet* resiTopos, char* pdbid){
StructureInitializeDesignSites(pStructure);
for(int cycle=0; cycle<1; cycle++){
printf("EvoEF Repairing PDB: optimization cycle %d ...\n",cycle+1);
for(int i=0; i<StructureGetChainCount(pStructure); ++i){
Chain* pChain = StructureGetChain(pStructure, i);
for(int j=0; j<ChainGetResidueCount(pChain); j++){
Residue* pResi = ChainGetResidue(pChain, j);
//skip CYS which may form disulfide bonds
if(strcmp(ResidueGetName(pResi),"CYS")==0) continue;
if(strcmp(ResidueGetName(pResi),"ASN")==0||strcmp(ResidueGetName(pResi),"GLN")==0||strcmp(ResidueGetName(pResi),"HSD")==0||strcmp(ResidueGetName(pResi),"HSE")==0){
printf("We will flip residue %s%d%c to optimize hbond\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteBuildFlippedCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteOptimizeRotamerHBondEnergy(pStructure,i,j);
}
else if(strcmp(ResidueGetName(pResi),"SER")==0 || strcmp(ResidueGetName(pResi),"THR")==0 || strcmp(ResidueGetName(pResi),"TYR")==0){
printf("We will rotate hydroxyl group of residue %s%d%c to optimize hbond\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteExpandHydroxylRotamers(pStructure,i,j,resiTopos);
ProteinSiteOptimizeRotamerHBondEnergy(pStructure,i,j);
}
if(TRUE){
printf("We optimize side chain of residue %s%d%c\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteBuildWildtypeRotamers(pStructure,i,j,rotlib,atomParams,resiTopos);
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteExpandHydroxylRotamers(pStructure,i,j,resiTopos);
//ProteinSiteOptimizeRotamer(pStructure,i,j);
ProteinSiteOptimizeRotamerLocally(pStructure,i,j, 1.0);
}
ProteinSiteDeleteRotamers(pStructure,i,j);
}
}
}
//output the repaired structure
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL){sprintf(modelfile,"%s_Repair.pdb",pdbid);}
else{strcpy(modelfile,"EvoEF_Repair.pdb");}
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <RepairStructure>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
return Success;
}
int EvoEF_WriteStructureToFile(Structure* pStructure, char* pdbfile){
FILE* pf=fopen(pdbfile,"w");
if(pf!=NULL){
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
}
else{
printf("failed to open file for writing structure coordinates\n");
return IOError;
}
return Success;
}
int EvoEF_AddHydrogens(Structure* pStructure, char* pdbid){
//polar hydrogens are automatically added, so we just output the repaired structure
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL){sprintf(modelfile,"%s_PolH.pdb",pdbid);}
else{strcpy(modelfile,"EvoEF_PolH.pdb");}
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <AddHydrogens>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
return Success;
}
int EvoEF_OptimizeHydrogen(Structure* pStructure, AtomParamsSet* atomParams,ResiTopoSet* resiTopos, char* pdbid){
StructureInitializeDesignSites(pStructure);
for(int cycle=0; cycle<1; cycle++){
printf("EvoEF Repairing PDB: optimization cycle %d ...\n",cycle+1);
for(int i=0; i<StructureGetChainCount(pStructure); ++i){
Chain* pChain = StructureGetChain(pStructure, i);
for(int j=0; j<ChainGetResidueCount(pChain); j++){
Residue* pResi = ChainGetResidue(pChain, j);
if(strcmp(ResidueGetName(pResi),"SER")==0 || strcmp(ResidueGetName(pResi),"THR")==0 || strcmp(ResidueGetName(pResi),"TYR")==0){
printf("We will rotate hydroxyl group of residue %s%d%c to optimize hbond\n", ResidueGetChainName(pResi),ResidueGetPosInChain(pResi),ThreeLetterAAToOneLetterAA(ResidueGetName(pResi)));
ProteinSiteAddCrystalRotamer(pStructure,i,j,resiTopos);
ProteinSiteExpandHydroxylRotamers(pStructure,i,j,resiTopos);
ProteinSiteOptimizeRotamerHBondEnergy(pStructure,i,j);
ProteinSiteDeleteRotamers(pStructure,i,j);
}
}
}
}
//output the repaired structure
char modelfile[MAX_LENGTH_ONE_LINE_IN_FILE+1];
if(pdbid!=NULL){sprintf(modelfile,"%s_OptH.pdb",pdbid);}
else{strcpy(modelfile,"EvoEF_OptH.pdb");}
FILE* pf=fopen(modelfile,"w");
fprintf(pf,"REMARK EvoEF generated pdb file\n");
fprintf(pf,"REMARK Output generated by EvoEF <OptimizeHydrogen>\n");
StructureShowInPDBFormat(pStructure,TRUE,pf);
fclose(pf);
return Success;
}
| 55.687259 | 194 | 0.637697 | [
"model"
] |
e65c9901464cb3248ed64d1b73b5fffc79875490 | 5,133 | cc | C++ | src/executor.cc | alan-baker/amber | 13dd6edfc6a0779093fa6182d1f57800d1e21504 | [
"Apache-2.0"
] | null | null | null | src/executor.cc | alan-baker/amber | 13dd6edfc6a0779093fa6182d1f57800d1e21504 | [
"Apache-2.0"
] | null | null | null | src/executor.cc | alan-baker/amber | 13dd6edfc6a0779093fa6182d1f57800d1e21504 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Amber Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/executor.h"
#include <cassert>
#include <vector>
#include "src/engine.h"
#include "src/script.h"
#include "src/shader_compiler.h"
namespace amber {
Executor::Executor() = default;
Executor::~Executor() = default;
Result Executor::Execute(Engine* engine,
const amber::Script* script,
const ShaderMap& shader_map) {
engine->SetEngineData(script->GetEngineData());
// Process Shader nodes
PipelineType pipeline_type = PipelineType::kGraphics;
for (const auto& shader : script->GetShaders()) {
ShaderCompiler sc;
Result r;
std::vector<uint32_t> data;
std::tie(r, data) = sc.Compile(shader.get(), shader_map);
if (!r.IsSuccess())
return r;
r = engine->SetShader(shader->GetType(), data);
if (!r.IsSuccess())
return r;
if (shader->GetType() == kShaderTypeCompute)
pipeline_type = PipelineType::kCompute;
}
// Handle Image and Depth buffers early so they are available when we call
// the CreatePipeline method.
for (const auto& buf : script->GetBuffers()) {
// Image and depth are handled earlier. They will be moved to the pipeline
// object when it exists.
if (buf->GetBufferType() != BufferType::kColor &&
buf->GetBufferType() != BufferType::kDepth) {
continue;
}
Result r = engine->SetBuffer(
buf->GetBufferType(), buf->GetLocation(),
buf->IsFormatBuffer() ? buf->AsFormatBuffer()->GetFormat() : Format(),
buf->GetData());
if (!r.IsSuccess())
return r;
}
// TODO(jaebaek): Support multiple pipelines.
Result r = engine->CreatePipeline(pipeline_type);
if (!r.IsSuccess())
return r;
// Process Buffers
for (const auto& buf : script->GetBuffers()) {
// Image and depth are handled earlier. They will be moved to the pipeline
// object when it exists.
if (buf->GetBufferType() == BufferType::kColor ||
buf->GetBufferType() == BufferType::kDepth) {
continue;
}
r = engine->SetBuffer(
buf->GetBufferType(), buf->GetLocation(),
buf->IsFormatBuffer() ? buf->AsFormatBuffer()->GetFormat() : Format(),
buf->GetData());
if (!r.IsSuccess())
return r;
}
// Process Commands
for (const auto& cmd : script->GetCommands()) {
if (cmd->IsProbe()) {
ResourceInfo info;
r = engine->DoProcessCommands();
if (!r.IsSuccess())
return r;
// This must come after processing commands because we require
// the frambuffer buffer to be mapped into host memory and have
// a valid host-side pointer.
r = engine->GetFrameBufferInfo(&info);
if (!r.IsSuccess())
return r;
assert(info.cpu_memory != nullptr);
r = verifier_.Probe(cmd->AsProbe(), info.image_info.texel_format,
info.image_info.texel_stride,
info.image_info.row_stride, info.image_info.width,
info.image_info.height, info.cpu_memory);
} else if (cmd->IsProbeSSBO()) {
auto probe_ssbo = cmd->AsProbeSSBO();
ResourceInfo info;
r = engine->GetDescriptorInfo(probe_ssbo->GetDescriptorSet(),
probe_ssbo->GetBinding(), &info);
if (!r.IsSuccess())
return r;
r = engine->DoProcessCommands();
if (!r.IsSuccess())
return r;
r = verifier_.ProbeSSBO(probe_ssbo, info.size_in_bytes, info.cpu_memory);
} else if (cmd->IsClear()) {
r = engine->DoClear(cmd->AsClear());
} else if (cmd->IsClearColor()) {
r = engine->DoClearColor(cmd->AsClearColor());
} else if (cmd->IsClearDepth()) {
r = engine->DoClearDepth(cmd->AsClearDepth());
} else if (cmd->IsClearStencil()) {
r = engine->DoClearStencil(cmd->AsClearStencil());
} else if (cmd->IsDrawRect()) {
r = engine->DoDrawRect(cmd->AsDrawRect());
} else if (cmd->IsDrawArrays()) {
r = engine->DoDrawArrays(cmd->AsDrawArrays());
} else if (cmd->IsCompute()) {
r = engine->DoCompute(cmd->AsCompute());
} else if (cmd->IsEntryPoint()) {
r = engine->DoEntryPoint(cmd->AsEntryPoint());
} else if (cmd->IsPatchParameterVertices()) {
r = engine->DoPatchParameterVertices(cmd->AsPatchParameterVertices());
} else if (cmd->IsBuffer()) {
r = engine->DoBuffer(cmd->AsBuffer());
} else {
return Result("Unknown command type");
}
if (!r.IsSuccess())
return r;
}
return {};
}
} // namespace amber
| 32.283019 | 79 | 0.624002 | [
"object",
"vector"
] |
e65d15011c05a643b0046bf0a519924231f2920d | 5,641 | cpp | C++ | core_view/core_view.cpp | liember/lieEngine | d58ea0874a764d60b464e8db9163009ba99a7a24 | [
"MIT"
] | 1 | 2020-02-29T00:35:46.000Z | 2020-02-29T00:35:46.000Z | core_view/core_view.cpp | liember/lieEngine | d58ea0874a764d60b464e8db9163009ba99a7a24 | [
"MIT"
] | null | null | null | core_view/core_view.cpp | liember/lieEngine | d58ea0874a764d60b464e8db9163009ba99a7a24 | [
"MIT"
] | null | null | null | #include "core_view.hpp"
using namespace lieEngine::View;
/*
void Component::Label::correctTexture()
{
int texW = 0;
int texH = 0;
SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);
dstrect = {0, 0, texW, texH};
}
void Component::Label::getTextureText(const char *t)
{
if (texture == nullptr)
{
texture = SDL_CreateTextureFromSurface(renderer, TTF_RenderText_Solid(f, t, color));
}
else
{
SDL_DestroyTexture(texture);
texture = SDL_CreateTextureFromSurface(renderer, TTF_RenderText_Solid(f, t, color));
}
}
void Component::Label::ChangeColor(int r, int g, int b)
{
color.r = r;
color.g = g;
color.b = b;
getTextureText(value.c_str());
}
void Component::Label::ChangeSize(int w, int h)
{
dstrect.w = w;
dstrect.h = h;
}
void Component::Label::Move(double x, double y)
{
x_mv = x;
y_mv = y;
}
void Component::Label::Draw()
{
SDL_Rect buf;
buf.x = pos_x + x_mv;
buf.y = pos_y + y_mv;
buf.w = dstrect.w;
buf.h = dstrect.h;
if (texture)
{
SDL_RenderCopy(renderer, texture, nullptr, &buf);
}
}
Component::Label::Label(std::string font_file, SDL_Renderer *ren, std::string val, double &x, double &y) : pos_x(x), pos_y(y)
{
value.swap(val);
renderer = ren;
f = TTF_OpenFont(font_file.c_str(), 25);
texture = nullptr;
getTextureText(value.c_str());
correctTexture();
}
Component::Label::~Label()
{
TTF_CloseFont(f);
}
// CLICK AREA
Component::ClickArea::ClickArea(const Eventor::Coursor &cours,
const double &x,
const double &y,
const int &w,
const int &h) : x_pos(x),
y_pos(y),
width(w),
height(h),
mouse(cours)
{
}
Component::ClickArea::~ClickArea()
{
}
bool Component::ClickArea::Update()
{
int x = mouse.GetX();
int y = mouse.GetY();
if (x > x_pos && x < x_pos + width && y > y_pos && y < y_pos + height)
{
clicked = mouse.isClecked();
holded = mouse.isHold();
hovered = true;
return true;
}
else
{
return false;
}
}
bool Component::ClickArea::isClecked() const
{
return clicked;
}
bool Component::ClickArea::isHovered() const
{
return hovered;
}
bool Component::ClickArea::isHold() const
{
return holded;
}
// TEXTURE
Component::Texture::Texture(std::string file_name, SDL_Renderer *rend)
{
renderer = rend;
CheckFile(file_name.c_str());
SDL_Surface *tempSurf = IMG_Load(file_name.c_str());
_texture = SDL_CreateTextureFromSurface(renderer, tempSurf);
SDL_FreeSurface(tempSurf);
};
Component::Texture::Texture(SDL_Texture *textur, SDL_Renderer *rend)
{
renderer = rend;
_texture = textur;
}
Component::Texture::~Texture()
{
SDL_DestroyTexture(_texture);
}
void Component::Texture::CheckFile(const char *file_name)
{
std::ifstream file;
file.open(file_name);
if (!file)
throw new std::exception();
}
void Component::Texture::Draw(int x, int y, int width, int height)
{
SDL_Rect dest;
dest.x = x;
dest.y = y;
dest.w = width;
dest.h = height;
SDL_RenderCopy(renderer, _texture, nullptr, &dest);
}
// COURSOR
Eventor::Coursor::Coursor(SDL_Event *events, SDL_Window *window)
{
ev = events;
win = window;
hold = false;
move = false;
clicked = false;
SetPos(0, 0);
}
Eventor::Coursor::~Coursor() {}
bool Eventor::Coursor::Update()
{
bool news = false;
clicked = false;
move = false;
if (ev->type == SDL_MOUSEMOTION)
{
news = true;
move = true;
SDL_GetMouseState(&xmp, &ymp);
}
if (ev->type == SDL_MOUSEBUTTONDOWN)
{
news = true;
hold = true;
}
if (ev->type == SDL_MOUSEBUTTONUP)
{
news = true;
hold = false;
clicked = true;
}
return news;
}
void Eventor::Coursor::SetPos(int x, int y)
{
SDL_WarpMouseInWindow(win, x, y);
}
int Eventor::Coursor::GetX() const { return xmp; }
int Eventor::Coursor::GetY() const { return ymp; }
bool Eventor::Coursor::isClecked() const { return clicked; }
bool Eventor::Coursor::isMoved() const { return move; }
bool Eventor::Coursor::isHold() const { return hold; }
*/
// WINDOW
Window::Window(const char *title, int width, int height)
{
if (!glfwInit())
throw Exception("GLFW init error");
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(width, height, title, NULL, NULL);
if (!window)
{
throw Exception("GLFW window init error");
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Make the window's context current */
glfwMakeContextCurrent(window);
if (!gladLoadGL())
{
throw Exception("GLAD init error");
}
glViewport(0, 0, width, height);
glClearColor(0, 1, 0, 1);
isrunning = true;
}
Window::~Window()
{
glfwTerminate();
}
void Window::EventUpdate()
{
isrunning = !glfwWindowShouldClose(window);
glfwPollEvents();
}
// void Window::Render()
// {
// /* Render here */
// //glClear(GL_COLOR_BUFFER_BIT);
// /* Swap front and back buffers */
// //glfwSwapBuffers(window);
// /* Poll for and process events */
// }
| 20.892593 | 125 | 0.586775 | [
"render"
] |
e65f768db1db23802f1f0db8300192b7fe930af1 | 10,129 | cpp | C++ | src/presolve/to_sat.cpp | Coloquinte/umo | 1f39c316d6584bbed22913aabaa4bfb5ee02d72b | [
"MIT"
] | 1 | 2021-04-24T20:56:25.000Z | 2021-04-24T20:56:25.000Z | src/presolve/to_sat.cpp | Coloquinte/umo | 1f39c316d6584bbed22913aabaa4bfb5ee02d72b | [
"MIT"
] | null | null | null | src/presolve/to_sat.cpp | Coloquinte/umo | 1f39c316d6584bbed22913aabaa4bfb5ee02d72b | [
"MIT"
] | null | null | null |
#include "presolve/to_sat.hpp"
#include "model/operator.hpp"
#include "utils/utils.hpp"
#include <cassert>
using namespace std;
namespace umoi {
namespace presolve {
class ToSat::Transformer {
public:
Transformer(PresolvedModel &);
void run();
void createExpressions();
void satify(uint32_t i);
void constrainPos(uint32_t i);
void constrainNeg(uint32_t i);
void satifyAnd(uint32_t i);
void satifyOr(uint32_t i);
void satifyXor(uint32_t i);
void satifyConstrainedAnd(uint32_t i);
void satifyConstrainedOr(uint32_t i);
void satifyConstrainedXor(uint32_t i);
void satifyConstrainedNAnd(uint32_t i);
void satifyConstrainedNOr(uint32_t i);
void satifyConstrainedNXor(uint32_t i);
// Helper function: direct expression of a generalized and
void satifyConstrainedGeneralized(uint32_t i, bool inInv, bool outInv);
void satifyGeneralized(uint32_t i, bool inInv, bool outInv);
// Helper function: direct expression of a clause
void makeClause(const vector<ExpressionId> &operands, bool useOriginalId=true);
void makeXorClause(const vector<ExpressionId> &operands, bool inv);
ExpressionId getMapping(ExpressionId id, bool useOriginalId=true);
private:
PresolvedModel &model;
PresolvedModel satModel;
ExpressionId constantZero;
ExpressionId constantOne;
};
ToSat::Transformer::Transformer(PresolvedModel &model) : model(model) {
constantZero = satModel.createConstant(0.0);
constantOne = satModel.createConstant(1.0);
}
void ToSat::Transformer::createExpressions() {
// Copy expressions
for (uint32_t i = 0; i < model.nbExpressions(); ++i) {
const auto &expr = model.expression(i);
if (expr.op == UMO_OP_INVALID)
continue;
if (expr.op == UMO_OP_CONSTANT)
continue;
if (model.isDecision(i)) {
if (expr.op != UMO_OP_DEC_BOOL) {
throw runtime_error("Only boolean expressions are supported");
}
ExpressionId newId = satModel.createExpression(UMO_OP_DEC_BOOL, {});
satModel.mapping().emplace(i, newId);
} else {
if (expr.type != UMO_TYPE_BOOL) {
throw runtime_error("Only boolean expressions are supported");
}
if (model.isConstraint(i)) {
// All constraints are converted without additional variables
continue;
}
ExpressionId newId = satModel.createExpression(UMO_OP_DEC_BOOL, {});
satModel.mapping().emplace(i, newId);
}
}
}
void ToSat::Transformer::satify(uint32_t i) {
if (model.isConstant(i)) {
if (model.isConstraint(i)) {
throw runtime_error("Constraints on constants are not supported");
}
return;
}
umo_operator op = model.expression(i).op;
if (model.isConstraint(i)) {
if (model.isConstraintPos(i)) {
switch (op) {
case UMO_OP_DEC_BOOL:
constrainPos(i);
break;
case UMO_OP_AND:
satifyConstrainedAnd(i);
break;
case UMO_OP_OR:
satifyConstrainedOr(i);
break;
case UMO_OP_XOR:
satifyConstrainedXor(i);
break;
default:
THROW_ERROR("Operand type " << op << " not handled by SAT");
}
}
if (model.isConstraintNeg(i)) {
switch (op) {
case UMO_OP_DEC_BOOL:
constrainNeg(i);
break;
case UMO_OP_AND:
satifyConstrainedNAnd(i);
break;
case UMO_OP_OR:
satifyConstrainedNOr(i);
break;
case UMO_OP_XOR:
satifyConstrainedNXor(i);
break;
default:
THROW_ERROR("Operand type " << op << " not handled by SAT");
}
}
} else {
switch (op) {
case UMO_OP_DEC_BOOL:
break;
case UMO_OP_AND:
satifyAnd(i);
break;
case UMO_OP_OR:
satifyOr(i);
break;
case UMO_OP_XOR:
satifyXor(i);
break;
default:
THROW_ERROR("Operand type " << op << " not handled by SAT");
}
}
}
void ToSat::Transformer::constrainPos(uint32_t i) {
makeClause({ExpressionId::fromVar(i)});
}
void ToSat::Transformer::constrainNeg(uint32_t i) {
makeClause({ExpressionId::fromVar(i).getNot()});
}
void ToSat::Transformer::satifyAnd(uint32_t i) {
satifyGeneralized(i, false, false);
}
void ToSat::Transformer::satifyOr(uint32_t i) {
satifyGeneralized(i, true, true);
}
void ToSat::Transformer::satifyXor(uint32_t i) {
vector<ExpressionId> operands = model.expression(i).operands;
operands.push_back(ExpressionId::fromVar(i));
makeXorClause(operands, true);
}
void ToSat::Transformer::satifyConstrainedAnd(uint32_t i) {
satifyConstrainedGeneralized(i, false, false);
}
void ToSat::Transformer::satifyConstrainedOr(uint32_t i) {
satifyConstrainedGeneralized(i, true, true);
}
void ToSat::Transformer::satifyConstrainedXor(uint32_t i) {
const Model::ExpressionData &expr = model.expression(i);
makeXorClause(expr.operands, false);
}
void ToSat::Transformer::satifyConstrainedNAnd(uint32_t i) {
satifyConstrainedGeneralized(i, false, true);
}
void ToSat::Transformer::satifyConstrainedNOr(uint32_t i) {
satifyConstrainedGeneralized(i, true, false);
}
void ToSat::Transformer::satifyConstrainedNXor(uint32_t i) {
const Model::ExpressionData &expr = model.expression(i);
makeXorClause(expr.operands, true);
}
void ToSat::Transformer::satifyConstrainedGeneralized(uint32_t i, bool inInv,
bool outInv) {
const Model::ExpressionData &expr = model.expression(i);
if (outInv) {
// Case of a or (single clause)
vector<ExpressionId> operands;
operands.reserve(expr.operands.size());
for (ExpressionId id : expr.operands) {
ExpressionId op = inInv ? id : id.getNot();
operands.push_back(op);
}
makeClause(operands);
} else {
// Case of a and (all constrained)
for (ExpressionId id : expr.operands) {
ExpressionId op = inInv ? id.getNot() : id;
makeClause({op});
}
}
}
void ToSat::Transformer::satifyGeneralized(uint32_t i, bool inInv,
bool outInv) {
const Model::ExpressionData &expr = model.expression(i);
ExpressionId idOut = ExpressionId::fromVar(i);
// Output --> Input implication
vector<ExpressionId> operands;
operands.reserve(expr.operands.size() + 1);
for (ExpressionId id : expr.operands) {
ExpressionId op = inInv ? id : id.getNot();
operands.push_back(op);
}
operands.push_back(outInv ? idOut.getNot() : idOut);
makeClause(operands);
// Input --> Output implications
for (ExpressionId id : expr.operands) {
ExpressionId op = inInv ? id.getNot() : id;
ExpressionId opOut = outInv ? idOut : idOut.getNot();
makeClause({op, opOut});
}
}
void ToSat::Transformer::makeClause(const vector<ExpressionId> &operands, bool useOriginalId) {
bool forceOne = false;
vector<ExpressionId> nonConstantOperands;
nonConstantOperands.reserve(operands.size());
for (ExpressionId id : operands) {
ExpressionId pid = getMapping(id, useOriginalId);
if (satModel.isConstant(pid.var())) {
forceOne |= (satModel.getExpressionIdValue(pid) != 0.0);
} else {
nonConstantOperands.push_back(pid);
}
}
if (!forceOne && !nonConstantOperands.empty()) {
ExpressionId expr = satModel.createExpression(UMO_OP_OR, nonConstantOperands);
satModel.createConstraint(expr);
}
}
void ToSat::Transformer::makeXorClause(const vector<ExpressionId> &operands, bool inv) {
if (operands.empty()) {
if (!inv) {
THROW_ERROR("Empty XOR clause is trivially infeasible");
}
return;
}
ExpressionId expr = getMapping(operands.front());
if (inv) expr = expr.getNot();
for (size_t i = 1; i < operands.size(); ++i) {
ExpressionId satOp = getMapping(operands[i]);
ExpressionId xorExpr = satModel.createExpression(UMO_OP_DEC_BOOL, {});
makeClause({satOp, expr, xorExpr.getNot()}, false);
makeClause({satOp.getNot(), expr, xorExpr}, false);
makeClause({satOp, expr.getNot(), xorExpr}, false);
makeClause({satOp.getNot(), expr.getNot(), xorExpr.getNot()}, false);
expr = xorExpr;
}
makeClause({expr}, false);
}
ExpressionId ToSat::Transformer::getMapping(ExpressionId id, bool useOriginalId) {
ExpressionId pid;
if (useOriginalId) {
if (model.isConstant(id.var())) {
return satModel.createConstant(model.getExpressionIdValue(id));
}
else {
pid = satModel.mapping().at(id.var());
}
return id.isNot() ? pid.getNot() : pid;
}
else {
return id;
}
}
void ToSat::Transformer::run() {
createExpressions();
for (uint32_t i = 0; i < model.nbExpressions(); ++i) {
satify(i);
}
model.apply(satModel);
}
bool ToSat::valid(const PresolvedModel &model) const {
if (model.nbObjectives() != 0)
return false;
for (uint32_t i = 0; i < model.nbExpressions(); ++i) {
const auto &expr = model.expression(i);
switch (expr.op) {
case UMO_OP_INVALID:
case UMO_OP_CONSTANT:
case UMO_OP_DEC_BOOL:
case UMO_OP_AND:
case UMO_OP_OR:
case UMO_OP_XOR:
continue;
default:
return false;
}
}
return true;
}
void ToSat::run(PresolvedModel &model) const {
Transformer tf(model);
tf.run();
}
} // namespace presolve
} // namespace umoi
| 31.070552 | 95 | 0.607661 | [
"vector",
"model"
] |
e66608a6d30e28a504c533854ad05cd972299e25 | 3,203 | hh | C++ | include/items/misc.hh | king1600/Valk | b376a0dcce522ae03ced7d882835e4dea98df86e | [
"MIT"
] | null | null | null | include/items/misc.hh | king1600/Valk | b376a0dcce522ae03ced7d882835e4dea98df86e | [
"MIT"
] | null | null | null | include/items/misc.hh | king1600/Valk | b376a0dcce522ae03ced7d882835e4dea98df86e | [
"MIT"
] | null | null | null | #pragma once
#include "collection.hh"
namespace valk {
class User;
class Guild;
class Channel;
class Color {
private:
uint32_t value;
public:
uint8_t r, g, b, a;
Color(const uint8_t _r = 0, const uint8_t _g = 0,
const uint8_t _b = 0, const uint8_t _a = 0) :
r(_r), g(_g), b(_b), a(_a) {}
Color(const uint32_t val) {
r = static_cast<uint8_t>((val >> (8 * 0)) & 0xff);
g = static_cast<uint8_t>((val >> (8 * 0)) & 0xff);
b = static_cast<uint8_t>((val >> (8 * 0)) & 0xff);
a = static_cast<uint8_t>((val >> (8 * 0)) & 0xff);
}
const uint32_t val() {
value = 0;
uint8_t num[4];
num[0] = r;
num[1] = g;
num[2] = b;
num[3] = a;
value = *((uint32_t*)(num));
return value;
}
};
struct ChannelType {
static const uint8_t GuildText = 0;
static const uint8_t UserDM = 1;
static const uint8_t GuildVoice = 2;
static const uint8_t GroupDM = 3;
static const uint8_t GuidlCategory = 4;
};
struct MessageType {
static const uint8_t Default = 0;
static const uint8_t RecipientAdd = 1;
static const uint8_t RecipientRemove = 2;
static const uint8_t Call = 3;
static const uint8_t ChannelNameChange = 4;
static const uint8_t ChannelIconChange = 5;
static const uint8_t ChannelPinnedMessage = 6;
static const uint8_t GuildMemberJoin = 7;
};
typedef struct Invite {
Guild *guild;
Channel *channel;
std::string code;
} Invite;
typedef struct Overwrite {
int deny;
int allow;
snowflake id;
std::string type;
} Overwrite;
typedef struct Attachment {
int width;
int height;
snowflake id;
std::string url;
std::size_t size;
std::string filename;
std::string proxy_url;
} Attachment;
typedef struct VoiceRegion {
bool vip;
bool custom;
bool optimal;
std::string id;
bool deprecated;
int sample_port;
std::string name;
std::string sample_hostname;
} VoiceRegion;
typedef struct VoiceState {
bool deaf;
bool mute;
User *user;
Guild *guild;
bool suppress;
bool self_deaf;
bool self_mute;
Channel *channel;
std::string session_id;
} VoiceState;
class Role : public Item {
public:
bool hoist;
Color color;
bool managed;
Guild *guild;
std::string name;
bool mentionable;
uint32_t position;
uint32_t permissions;
inline ~Role() = default;
inline Role() : Item() {}
void from(const io::json& data);
std::string toString() {
return "<@&" + std::to_string(id) + ">";
}
};
class Emoji : public Item {
public:
Guild *guild;
bool managed;
std::string name;
bool require_colons;
std::vector<Role> roles;
inline ~Emoji() = default;
inline Emoji() : Item() {}
void from(const io::json& data);
std::string toString() {
return "<:" + name + ":" + std::to_string(id) + ">";
}
};
typedef struct Reaction {
bool me;
Emoji& emoji;
uint8_t count;
inline Reaction(Emoji &e) : emoji(e) {}
} Reaction;
} | 22.398601 | 58 | 0.583203 | [
"vector"
] |
e674a0dfde6a8e71de2e29228b03bb2a1fd85c32 | 3,771 | cpp | C++ | libs/pcl/pcl_examples/draw_correspondences/main_draw_correspondences.cpp | quanhua92/learning-notes | a9c50d3955c51bb58f4b012757c550b76c5309ef | [
"Apache-2.0"
] | null | null | null | libs/pcl/pcl_examples/draw_correspondences/main_draw_correspondences.cpp | quanhua92/learning-notes | a9c50d3955c51bb58f4b012757c550b76c5309ef | [
"Apache-2.0"
] | null | null | null | libs/pcl/pcl_examples/draw_correspondences/main_draw_correspondences.cpp | quanhua92/learning-notes | a9c50d3955c51bb58f4b012757c550b76c5309ef | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/io/obj_io.h>
#include <pcl/point_cloud.h>
#include <pcl/console/parse.h>
#include <pcl/common/transforms.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/filters/passthrough.h>
using namespace std;
using namespace pcl;
void showHelp(char * program_name) {
cout << endl;
cout << "Usage: " << program_name << " source.pcd target.pcd correspondences.txt threshold" << endl;
cout << "-h: Show this help." << endl;
}
int main(int argc, char** argv) {
if (pcl::console::find_switch(argc, argv, "-h") || pcl::console::find_switch(argc, argv, "--help")) {
showHelp(argv[0]);
}
if (argc != 5) {
showHelp(argv[0]);
system("pause");
return -1;
}
string source_path = string(argv[1]);
string target_path = string(argv[2]);
string corres_path = string(argv[3]);
float threshold = atof(argv[4]);
cout << "threshold: " << threshold << endl;
vector<Correspondence> correspondences;
ifstream file(corres_path);
string line;
while (getline(file, line)) {
int source, target;
float distance;
stringstream ss;
ss << line;
ss >> source >> target >> distance;
if (distance < threshold) {
cout << "source: " << source << " target: " << target << " dist: " << distance << endl;
correspondences.push_back(Correspondence(source, target, distance));
}
}
PointCloud<PointXYZ>::Ptr source_cloud(new PointCloud<PointXYZ>());
if (io::loadPCDFile(source_path, *source_cloud) < 0) {
cout << "Error loading " << source_path << endl;
showHelp(argv[0]);
system("pause");
return -1;
}
PointCloud<PointXYZ>::Ptr target_cloud(new PointCloud<PointXYZ>());
if (io::loadPCDFile(target_path, *target_cloud) < 0) {
if (io::loadOBJFile(target_path, *target_cloud) < 0) {
cout << "Error loading " << target_path << endl;
showHelp(argv[0]);
system("pause");
return -1;
}
Eigen::Affine3f transform = Eigen::Affine3f::Identity();
transform.rotate(Eigen::AngleAxisf(M_PI / 2, Eigen::Vector3f::UnitY()));
pcl::transformPointCloud(*target_cloud, *target_cloud, transform);
transform.setIdentity();
transform.rotate(Eigen::AngleAxisf(M_PI / 2, Eigen::Vector3f::UnitX()));
pcl::transformPointCloud(*target_cloud, *target_cloud, transform);
}
// Translation
Eigen::Affine3f transform = Eigen::Affine3f::Identity();
transform.translation() << 0, 1.0, 0;
pcl::transformPointCloud(*target_cloud, *target_cloud, transform);
// Visualization
pcl::visualization::PCLVisualizer viewer("Extract plane example");
float bckgr_gray_level = 0.0; // Black
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source_cloud_color_handler(source_cloud, 255, 0, 0);
viewer.addPointCloud(source_cloud, source_cloud_color_handler, "original_cloud");
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "original_cloud");
pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> target_cloud_color_handler(target_cloud, 0, 255, 0);
viewer.addPointCloud(target_cloud, target_cloud_color_handler, "target_cloud");
viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "target_cloud");
for (int i = 0; i < correspondences.size(); i++) {
int source = correspondences[i].index_query;
int target = correspondences[i].index_match;
viewer.addLine(source_cloud->points[source], target_cloud->points[target], 255, 0, 0, "arrow" + to_string(i));
}
viewer.addCoordinateSystem(1.0, "cloud", 0);
viewer.setBackgroundColor(bckgr_gray_level, bckgr_gray_level, bckgr_gray_level);
viewer.setSize(1280, 1024); // Visualiser window size
while (!viewer.wasStopped()) { // Display the visualiser until 'q' key is pressed
viewer.spinOnce();
}
system("pause");
} | 33.078947 | 117 | 0.714134 | [
"vector",
"transform"
] |
e67e06e3fb1e99f797bc1c1b22c35024a8043a0e | 21,885 | cpp | C++ | retrace/d3d9state_images.cpp | Gurten/apitrace | e4ab1fee3eeb1f9f95a3b6f68339a0e5a87f5528 | [
"MIT"
] | 1,723 | 2015-01-08T19:10:21.000Z | 2022-03-31T16:41:40.000Z | retrace/d3d9state_images.cpp | Gurten/apitrace | e4ab1fee3eeb1f9f95a3b6f68339a0e5a87f5528 | [
"MIT"
] | 471 | 2015-01-02T15:02:34.000Z | 2022-03-26T17:54:10.000Z | retrace/d3d9state_images.cpp | Gurten/apitrace | e4ab1fee3eeb1f9f95a3b6f68339a0e5a87f5528 | [
"MIT"
] | 380 | 2015-01-22T19:06:32.000Z | 2022-03-25T02:20:39.000Z | /**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**************************************************************************/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "image.hpp"
#include "state_writer.hpp"
#include "com_ptr.hpp"
#include "d3d9state.hpp"
#include "d3dstate.hpp"
#include "d3d9size.hpp"
#include <vector>
namespace d3dstate {
static image::Image *
getSurfaceImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pSurface,
struct StateWriter::ImageDesc &imageDesc) {
image::Image *image = NULL;
HRESULT hr;
if (!pSurface) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Format == D3DFMT_NULL) {
// dummy rendertarget
return NULL;
}
D3DLOCKED_RECT LockedRect;
hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY);
if (FAILED(hr)) {
return NULL;
}
image = ConvertImage(Desc.Format, LockedRect.pBits, LockedRect.Pitch, Desc.Width, Desc.Height);
pSurface->UnlockRect();
imageDesc.format = formatToString(Desc.Format);
return image;
}
static image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pRenderTarget,
struct StateWriter::ImageDesc &imageDesc) {
HRESULT hr;
if (!pRenderTarget) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pRenderTarget->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Desc.Format == D3DFMT_NULL) {
// dummy rendertarget
return NULL;
}
com_ptr<IDirect3DSurface9> pResolveSurface;
if (Desc.MultiSampleType == D3DMULTISAMPLE_NONE) {
pResolveSurface = pRenderTarget;
} else {
hr = pDevice->CreateRenderTarget(Desc.Width, Desc.Height, Desc.Format, D3DMULTISAMPLE_NONE, 0, FALSE, &pResolveSurface, nullptr);
if (FAILED(hr)) {
std::cerr << "warning: failed to create resolve rendertarget\n";
return nullptr;
}
hr = pDevice->StretchRect(pRenderTarget, nullptr, pResolveSurface, nullptr, D3DTEXF_NONE);
if (FAILED(hr)) {
std::cerr << "warning: failed to resolve render target\n";
return nullptr;
}
}
com_ptr<IDirect3DSurface9> pStagingSurface;
hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL);
if (FAILED(hr)) {
return NULL;
}
hr = pDevice->GetRenderTargetData(pResolveSurface, pStagingSurface);
if (FAILED(hr)) {
std::cerr << "warning: GetRenderTargetData failed\n";
return NULL;
}
return getSurfaceImage(pDevice, pStagingSurface, imageDesc);
}
image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice) {
HRESULT hr;
struct StateWriter::ImageDesc imageDesc;
com_ptr<IDirect3DSurface9> pRenderTarget;
hr = pDevice->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)) {
return NULL;
}
assert(pRenderTarget);
return getRenderTargetImage(pDevice, pRenderTarget, imageDesc);
}
image::Image *
getRenderTargetImage(IDirect3DSwapChain9 *pSwapChain) {
HRESULT hr;
struct StateWriter::ImageDesc imageDesc;
com_ptr<IDirect3DDevice9> pDevice;
hr = pSwapChain->GetDevice(&pDevice);
if (FAILED(hr)) {
return NULL;
}
// TODO: Use GetFrontBufferData instead??
com_ptr<IDirect3DSurface9> pBackBuffer;
hr = pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);
if (FAILED(hr)) {
return NULL;
}
assert(pBackBuffer);
return getRenderTargetImage(pDevice, pBackBuffer, imageDesc);
}
static HRESULT
getLockableRenderTargetForDepth(IDirect3DDevice9 *pDevice,
int w,
int h,
com_ptr<IDirect3DSurface9> &pRenderTarget)
{
HRESULT hr;
std::vector<D3DFORMAT> fmts ({D3DFMT_R32F, D3DFMT_G32R32F, D3DFMT_R16F, D3DFMT_X8R8G8B8});
pRenderTarget = NULL;
for (UINT i = 0; i < fmts.size(); i++) {
hr = pDevice->CreateRenderTarget(w, h, fmts[i], D3DMULTISAMPLE_NONE,
0, TRUE, &pRenderTarget, NULL);
if (SUCCEEDED(hr))
break;
}
return hr;
}
static HRESULT
blitTexturetoRendertarget(IDirect3DDevice9 *pDevice,
IDirect3DBaseTexture9 *pSourceTex,
IDirect3DSurface9 *pRenderTarget)
{
com_ptr<IDirect3DPixelShader9> pPS;
HRESULT hr;
/* state */
com_ptr<IDirect3DSurface9> pOldRenderTarget;
com_ptr<IDirect3DSurface9> pOldDepthStencil;
D3DVIEWPORT9 oldViewport;
D3DMATRIX oldProj, oldView, oldWorld;
com_ptr<IDirect3DPixelShader9> pOldPixelShader;
com_ptr<IDirect3DVertexShader9> pOldVertexShader;
DWORD oldFVF;
com_ptr<IDirect3DBaseTexture9> pOldTexture;
com_ptr<IDirect3DStateBlock9> pState;
static const DWORD ps_code[] =
{
0xffff0200, /* ps_2_0 */
0x0200001f, 0x90000000, 0xa00f0800, /* dcl_2d s0 */
0x0200001f, 0x80000000, 0xb00f0000, /* dcl t0 */
0x05000051, 0xa00f0000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, /* def c0, 0.0, 0.0, 0.0, 0.0 */
0x02000001, 0x800f0000, 0xa0e40000, /* mov r0, c0 */
0x03000042, 0x800f0000, 0xb0e40000, 0xa0e40800, /* texld r0, t0, s0 */
0x02000001, 0x800f0800, 0x80e40000, /* mov oC0, r0 */
0x0000ffff, /* end */
};
static const struct
{
float x, y, z;
float s, t, p, q;
}
quad[] =
{
{ -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f},
{ 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.5f},
{ -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f},
{ 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f},
};
hr = pDevice->CreatePixelShader(ps_code, &pPS);
if (!SUCCEEDED(hr))
return hr;
/* Store state */
pDevice->GetTransform(D3DTS_PROJECTION, &oldProj);
pDevice->GetTransform(D3DTS_VIEW, &oldView);
pDevice->GetTransform(D3DTS_WORLD, &oldWorld);
pDevice->GetPixelShader(&pOldPixelShader);
pDevice->GetVertexShader(&pOldVertexShader);
pDevice->GetFVF(&oldFVF);
pDevice->GetViewport(&oldViewport);
pDevice->GetTexture(0, &pOldTexture);
pDevice->GetRenderTarget(0, &pOldRenderTarget);
pDevice->GetDepthStencilSurface(&pOldDepthStencil);
/* Store samplerstates and texture and sampler states */
pDevice->CreateStateBlock(D3DSBT_ALL, &pState);
/* Set source */
pDevice->SetTexture(0, pSourceTex);
/* Set destination */
pDevice->SetRenderTarget(0, pRenderTarget);
pDevice->SetDepthStencilSurface(NULL);
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
pDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO);
pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_ALWAYS);
pDevice->SetRenderState(D3DRS_ALPHAREF, 0);
pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
pDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
pDevice->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
pDevice->SetRenderState(D3DRS_FOGTABLEMODE, D3DFOG_NONE);
pDevice->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
pDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
pDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
pDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
pDevice->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_ZERO);
pDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP);
pDevice->SetRenderState(D3DRS_STENCILREF, 0);
D3DSURFACE_DESC desc;
pRenderTarget->GetDesc(&desc);
D3DVIEWPORT9 vp;
vp.X = 0;
vp.Y = 0;
vp.Height = desc.Height;
vp.Width = desc.Width;
vp.MaxZ = 1.0f;
vp.MinZ = 0.0f;
pDevice->SetViewport(&vp);
static const D3DMATRIX identity =
{{{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
}}};
pDevice->SetTransform(D3DTS_PROJECTION, &identity);
pDevice->SetTransform(D3DTS_VIEW, &identity);
pDevice->SetTransform(D3DTS_WORLD, &identity);
pDevice->SetPixelShader(pPS);
pDevice->SetVertexShader(NULL);
pDevice->SetFVF(D3DFVF_XYZ | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE4(0));
pDevice->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, 0);
pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
pDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
pDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
pDevice->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, 0);
pDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
pDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT);
/* Blit texture to rendertarget */
pDevice->BeginScene();
pDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(*quad));
pDevice->EndScene();
/* Restore state */
pDevice->SetTransform(D3DTS_PROJECTION, &oldProj);
pDevice->SetTransform(D3DTS_VIEW, &oldView);
pDevice->SetTransform(D3DTS_WORLD, &oldWorld);
pDevice->SetPixelShader(pOldPixelShader);
pDevice->SetVertexShader(pOldVertexShader);
pDevice->SetFVF(oldFVF);
pDevice->SetViewport(&oldViewport);
pDevice->SetTexture(0, pOldTexture);
pDevice->SetRenderTarget(0, pOldRenderTarget);
pDevice->SetDepthStencilSurface(pOldDepthStencil);
pState->Apply();
return D3D_OK;
}
static bool
isDepthSamplerFormat(D3DFORMAT fmt)
{
return (fmt == D3DFMT_DF24 ||
fmt == D3DFMT_DF16 ||
fmt == D3DFMT_INTZ);
}
static image::Image *
getTextureImage(IDirect3DDevice9 *pDevice,
IDirect3DBaseTexture9 *pTexture,
D3DCUBEMAP_FACES FaceType,
UINT Level,
struct StateWriter::ImageDesc &imageDesc)
{
HRESULT hr;
if (!pTexture) {
return NULL;
}
com_ptr<IDirect3DSurface9> pSurface;
D3DRESOURCETYPE Type = pTexture->GetType();
switch (Type) {
case D3DRTYPE_TEXTURE:
assert(FaceType == D3DCUBEMAP_FACE_POSITIVE_X);
hr = reinterpret_cast<IDirect3DTexture9 *>(pTexture)->GetSurfaceLevel(Level, &pSurface);
break;
case D3DRTYPE_CUBETEXTURE:
hr = reinterpret_cast<IDirect3DCubeTexture9 *>(pTexture)->GetCubeMapSurface(FaceType, Level, &pSurface);
break;
default:
/* TODO: support volume textures */
return NULL;
}
if (FAILED(hr) || !pSurface) {
return NULL;
}
D3DSURFACE_DESC Desc;
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
if (Type == D3DRTYPE_TEXTURE && isDepthSamplerFormat(Desc.Format)) {
/* Special case for depth sampling formats.
* Blit to temporary rendertarget and dump it.
* Finally replace the format string to avoid confusion.
*/
com_ptr<IDirect3DSurface9> pTempSurf;
hr = getLockableRenderTargetForDepth(pDevice, Desc.Width, Desc.Height, pTempSurf);
if (FAILED(hr) || !pTempSurf) {
return NULL;
}
hr = blitTexturetoRendertarget(pDevice, pTexture, pTempSurf);
if (FAILED(hr)) {
return NULL;
}
image::Image *image;
image = getRenderTargetImage(pDevice, pTempSurf, imageDesc);
/* Replace rendertarget format with depth format */
imageDesc.format = formatToString(Desc.Format);
return image;
} else if (Desc.Pool != D3DPOOL_DEFAULT ||
Desc.Usage & D3DUSAGE_DYNAMIC) {
// Lockable texture
return getSurfaceImage(pDevice, pSurface, imageDesc);
} else if (Desc.Usage & D3DUSAGE_RENDERTARGET) {
// Rendertarget texture
return getRenderTargetImage(pDevice, pSurface, imageDesc);
} else {
// D3D constraints are such there is not much else that can be done.
return NULL;
}
}
void
dumpTextures(StateWriter &writer, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
writer.beginMember("textures");
writer.beginObject();
for (DWORD Stage = 0; Stage < 16; ++Stage) {
com_ptr<IDirect3DBaseTexture9> pTexture;
hr = pDevice->GetTexture(Stage, &pTexture);
if (FAILED(hr)) {
continue;
}
if (!pTexture) {
continue;
}
D3DRESOURCETYPE Type = pTexture->GetType();
DWORD NumFaces = Type == D3DRTYPE_CUBETEXTURE ? 6 : 1;
DWORD NumLevels = pTexture->GetLevelCount();
for (DWORD Face = 0; Face < NumFaces; ++Face) {
for (DWORD Level = 0; Level < NumLevels; ++Level) {
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getTextureImage(pDevice, pTexture, static_cast<D3DCUBEMAP_FACES>(Face), Level, imageDesc);
if (image) {
char label[128];
if (Type == D3DRTYPE_CUBETEXTURE) {
_snprintf(label, sizeof label, "PS_RESOURCE_%lu_FACE_%lu_LEVEL_%lu", Stage, Face, Level);
} else {
_snprintf(label, sizeof label, "PS_RESOURCE_%lu_LEVEL_%lu", Stage, Level);
}
writer.beginMember(label);
writer.writeImage(image, imageDesc);
writer.endMember(); // PS_RESOURCE_*
delete image;
}
}
}
}
writer.endObject();
writer.endMember(); // textures
}
static void
dumpRenderTargets(StateWriter &writer,
IDirect3DDevice9 *pDevice)
{
HRESULT hr;
D3DCAPS9 Caps;
pDevice->GetDeviceCaps(&Caps);
for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) {
com_ptr<IDirect3DSurface9> pRenderTarget;
hr = pDevice->GetRenderTarget(i, &pRenderTarget);
if (FAILED(hr)) {
continue;
}
if (!pRenderTarget) {
continue;
}
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
image = getRenderTargetImage(pDevice, pRenderTarget, imageDesc);
if (image) {
char label[64];
_snprintf(label, sizeof label, "RENDER_TARGET_%u", i);
writer.beginMember(label);
writer.writeImage(image, imageDesc);
writer.endMember(); // RENDER_TARGET_*
delete image;
}
}
}
static void
dumpDepthStencil(StateWriter &writer,
IDirect3DDevice9 *pDevice,
com_ptr<IDirect3DSurface9> &pDepthStencil,
D3DFORMAT format)
{
image::Image *image;
struct StateWriter::ImageDesc imageDesc;
if (!pDepthStencil)
return;
D3DSURFACE_DESC Desc;
pDepthStencil->GetDesc(&Desc);
if (Desc.Usage & D3DUSAGE_RENDERTARGET) {
/* RESZ hack: depth has been uploaded to rendertarget */
image = getRenderTargetImage(pDevice, pDepthStencil, imageDesc);
imageDesc.format = formatToString(format);
} else {
image = getSurfaceImage(pDevice, pDepthStencil, imageDesc);
}
if (image) {
writer.beginMember("DEPTH_STENCIL");
writer.writeImage(image, imageDesc);
writer.endMember(); // DEPTH_STENCIL
delete image;
}
}
static bool
isLockableFormat(D3DFORMAT fmt)
{
return (fmt == D3DFMT_D16_LOCKABLE ||
fmt == D3DFMT_D32F_LOCKABLE ||
fmt == D3DFMT_S8_LOCKABLE ||
fmt == D3DFMT_D32_LOCKABLE);
}
static bool
isRESZSupported(IDirect3DDevice9 *pDevice)
{
com_ptr<IDirect3D9> pD3D9;
HRESULT hr;
pDevice->GetDirect3D(&pD3D9);
hr = pD3D9->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8,
D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_RESZ);
return SUCCEEDED(hr);
}
static HRESULT
blitDepthRESZ(IDirect3DDevice9 *pDevice, com_ptr<IDirect3DTexture9> &pDestTex)
{
D3DVECTOR vDummyPoint = {0.0f, 0.0f, 0.0f};
HRESULT hr;
DWORD oldZEnable, oldZWriteEnable, oldColorWriteEnable;
com_ptr<IDirect3DBaseTexture9> pOldTex;
/* Store current state */
pDevice->GetTexture(0, &pOldTex);
pDevice->GetRenderState(D3DRS_ZENABLE, &oldZEnable);
pDevice->GetRenderState(D3DRS_ZWRITEENABLE, &oldZWriteEnable);
pDevice->GetRenderState(D3DRS_COLORWRITEENABLE, &oldColorWriteEnable);
pDevice->SetTexture(0, pDestTex);
pDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
pDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
/* Dummy draw call */
hr = pDevice->DrawPrimitiveUP(D3DPT_POINTLIST, 1, &vDummyPoint, sizeof(vDummyPoint));
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, oldZEnable);
pDevice->SetRenderState(D3DRS_ZENABLE, oldZWriteEnable);
pDevice->SetRenderState(D3DRS_COLORWRITEENABLE, oldColorWriteEnable);
/* Trigger RESZ hack, upload depth to texture bound at sampler 0 */
pDevice->SetRenderState(D3DRS_POINTSIZE, RESZ_CODE);
pDevice->SetRenderState(D3DRS_POINTSIZE, 0);
/* Restore state */
pDevice->SetTexture(0, pOldTex);
return hr;
}
static HRESULT
getTextureforDepthAsTexture(IDirect3DDevice9 *pDevice, int w, int h, com_ptr<IDirect3DTexture9> &pDestTex)
{
HRESULT hr;
std::vector<D3DFORMAT> fmts ({D3DFMT_INTZ, D3DFMT_DF24, D3DFMT_DF16});
for (int i = 0; i < fmts.size(); i++) {
hr = pDevice->CreateTexture(w, h, 1, D3DUSAGE_DEPTHSTENCIL,
fmts[i], D3DPOOL_DEFAULT, &pDestTex, NULL);
if (SUCCEEDED(hr))
break;
}
return hr;
}
void
dumpFramebuffer(StateWriter &writer, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
writer.beginMember("framebuffer");
writer.beginObject();
dumpRenderTargets(writer, pDevice);
com_ptr<IDirect3DSurface9> pDepthStencil;
hr = pDevice->GetDepthStencilSurface(&pDepthStencil);
if (SUCCEEDED(hr)) {
D3DSURFACE_DESC Desc;
pDepthStencil->GetDesc(&Desc);
if (isLockableFormat(Desc.Format)) {
dumpDepthStencil(writer, pDevice, pDepthStencil, Desc.Format);
} else if(isRESZSupported(pDevice)) {
/* Use RESZ hack to copy depth to a readable format.
* This is working on AMD, Intel and WINE.
* 1. Copy to depth sampling format using RESZ hack.
* 2. Blit to temporary rendertarget and dump it.
*/
com_ptr<IDirect3DTexture9> pTextureDepthSampler;
hr = getTextureforDepthAsTexture(pDevice, Desc.Width, Desc.Height, pTextureDepthSampler);
if (SUCCEEDED(hr)) {
hr = blitDepthRESZ(pDevice, pTextureDepthSampler);
if (SUCCEEDED(hr)) {
com_ptr<IDirect3DSurface9> pTempSurf;
hr = getLockableRenderTargetForDepth(pDevice, Desc.Width, Desc.Height, pTempSurf);
if (SUCCEEDED(hr)) {
hr = blitTexturetoRendertarget(pDevice, pTextureDepthSampler, pTempSurf);
if (SUCCEEDED(hr)) {
dumpDepthStencil(writer, pDevice, pTempSurf, Desc.Format);
}
}
}
}
} else {
// Can't to anything about it
}
}
writer.endObject();
writer.endMember(); // framebuffer
}
} /* namespace d3dstate */
| 31.948905 | 137 | 0.633585 | [
"render",
"vector"
] |
e68357f970cce03c81f4c72dbe899d5011201221 | 3,802 | cc | C++ | chrome/browser/enterprise/connectors/device_trust/key_management/core/signing_key_pair_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | chrome/browser/enterprise/connectors/device_trust/key_management/core/signing_key_pair_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | chrome/browser/enterprise/connectors/device_trust/key_management/core/signing_key_pair_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/enterprise/connectors/device_trust/key_management/core/signing_key_pair.h"
#include <memory>
#include <vector>
#include "chrome/browser/enterprise/connectors/device_trust/key_management/core/ec_signing_key.h"
#include "chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/key_persistence_delegate.h"
#include "chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/mock_key_persistence_delegate.h"
#include "chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/scoped_key_persistence_delegate_factory.h"
#include "crypto/unexportable_key.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using BPKUP = enterprise_management::BrowserPublicKeyUploadResponse;
using BPKUR = enterprise_management::BrowserPublicKeyUploadRequest;
using testing::Return;
namespace enterprise_connectors {
namespace {
void ValidateSigningKey(const absl::optional<SigningKeyPair>& key_pair,
BPKUR::KeyTrustLevel expected_trust_level) {
ASSERT_TRUE(key_pair);
EXPECT_EQ(expected_trust_level, key_pair->trust_level());
ASSERT_TRUE(key_pair->key());
// Extract a pubkey should work.
std::vector<uint8_t> pubkey = key_pair->key()->GetSubjectPublicKeyInfo();
ASSERT_GT(pubkey.size(), 0u);
// Signing should work.
auto signed_data = key_pair->key()->SignSlowly(
base::as_bytes(base::make_span("data to sign")));
ASSERT_TRUE(signed_data.has_value());
ASSERT_GT(signed_data->size(), 0u);
}
} // namespace
// Tests that the SigningKeyPair::Create factory function returns nothing if no
// key was persisted.
TEST(SigningKeyPairTest, Create_NoKey) {
testing::StrictMock<test::MockKeyPersistenceDelegate>
mock_persistence_delegate;
EXPECT_CALL(mock_persistence_delegate, LoadKeyPair())
.WillOnce(Return(KeyPersistenceDelegate::KeyInfo(
BPKUR::KEY_TRUST_LEVEL_UNSPECIFIED, std::vector<uint8_t>())));
EXPECT_FALSE(SigningKeyPair::Create(&mock_persistence_delegate));
}
// Tests that the SigningKeyPair::Create factory function returns a properly
// initialized TPM-backed SigningKeyPair if a TPM-backed key was available.
TEST(SigningKeyPairTest, Create_WithTpmKey) {
// The mocked factory returns mock delegates setup with TPM key pairs by
// default.
test::ScopedKeyPersistenceDelegateFactory factory;
auto mocked_delegate = factory.CreateMockedDelegate();
EXPECT_CALL(*mocked_delegate, LoadKeyPair());
EXPECT_CALL(*mocked_delegate, GetTpmBackedKeyProvider());
absl::optional<SigningKeyPair> key_pair =
SigningKeyPair::Create(mocked_delegate.get());
ValidateSigningKey(key_pair, BPKUR::CHROME_BROWSER_TPM_KEY);
}
// Tests that the SigningKeyPair::Create factory function returns a properly
// initialized crypto::ECPrivateKey-backed SigningKeyPair if that is what was
// available.
TEST(SigningKeyPairTest, Create_WithECPrivateKey) {
ECSigningKeyProvider ec_key_provider;
auto acceptable_algorithms = {crypto::SignatureVerifier::ECDSA_SHA256};
auto key = ec_key_provider.GenerateSigningKeySlowly(acceptable_algorithms);
testing::StrictMock<test::MockKeyPersistenceDelegate>
mock_persistence_delegate;
EXPECT_CALL(mock_persistence_delegate, LoadKeyPair)
.WillOnce(Return(KeyPersistenceDelegate::KeyInfo(
BPKUR::CHROME_BROWSER_OS_KEY, key->GetWrappedKey())));
absl::optional<SigningKeyPair> key_pair =
SigningKeyPair::Create(&mock_persistence_delegate);
ValidateSigningKey(key_pair, BPKUR::CHROME_BROWSER_OS_KEY);
}
} // namespace enterprise_connectors
| 40.021053 | 134 | 0.790637 | [
"vector"
] |
e6851e1174f604e1e925e04c4053f82cef6a0817 | 5,836 | cpp | C++ | video-led-driver.cpp | jhurliman/video-led-driver | 63178b69a5501f284440c669b6b826257b3f179d | [
"MIT"
] | null | null | null | video-led-driver.cpp | jhurliman/video-led-driver | 63178b69a5501f284440c669b6b826257b3f179d | [
"MIT"
] | null | null | null | video-led-driver.cpp | jhurliman/video-led-driver | 63178b69a5501f284440c669b6b826257b3f179d | [
"MIT"
] | null | null | null | #include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "rpi_ws281x/ws2811.h"
#include <execinfo.h>
#include <stdlib.h>
#include <unistd.h>
#include <chrono>
#include <csignal>
#include <iostream>
#include <string>
#include <thread>
constexpr int LED_COUNT = 300;
constexpr size_t IMAGE_SIZE = LED_COUNT / 2;
constexpr size_t BORDER_SIZE = 3;
constexpr size_t FPS = 30;
constexpr std::chrono::milliseconds FRAME_TIME(1000 / FPS);
constexpr int DMA = 10;
constexpr int GPIO_PIN = 18;
static const cv::Size RESIZE_SIZE(IMAGE_SIZE + BORDER_SIZE * 2, IMAGE_SIZE + BORDER_SIZE * 2);
static const cv::Rect CROP_RECT(BORDER_SIZE, BORDER_SIZE, IMAGE_SIZE, IMAGE_SIZE);
// This appears to be the max brightness before the end of the 300-LED strand at
// full white starts to go off-white with a single 20A PSU connection at the
// beginning of the strand
static float BRIGHTNESS = 32;
static uint8_t GAMMA_E[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,
2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11,
11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
19, 19, 20, 21, 21, 22, 22, 23, 23, 24, 25, 25, 26, 27, 27, 28,
29, 29, 30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40,
40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 89,
90, 91, 93, 94, 95, 96, 98, 99,100,102,103,104,106,107,109,110,
111,113,114,116,117,119,120,121,123,124,126,128,129,131,132,134,
135,137,138,140,142,143,145,146,148,150,151,153,155,157,158,160,
162,163,165,167,169,170,172,174,176,178,179,181,183,185,187,189,
191,193,194,196,198,200,202,204,206,208,210,212,214,216,218,220,
222,224,227,229,231,233,235,237,239,241,244,246,248,250,252,255
};
static bool gRunning = true;
static ws2811_t gLEDs = []{
ws2811_t leds{};
leds.freq = WS2811_TARGET_FREQ;
leds.dmanum = DMA;
leds.channel[0].gpionum = GPIO_PIN;
leds.channel[0].count = LED_COUNT;
leds.channel[0].invert = 0;
leds.channel[0].brightness = BRIGHTNESS;
leds.channel[0].strip_type = WS2811_STRIP_GRB;
leds.channel[1].gpionum = 0;
leds.channel[1].count = 0;
leds.channel[1].invert = 0;
leds.channel[1].brightness = 0;
return leds;
}();
static void log(const std::string& msg) {
std::cout << msg << std::endl;
}
static void crashHandler(int sig) {
gRunning = false;
void *array[10];
size_t size = backtrace(array, 10);
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
static void signalHandler(int sig) {
gRunning = false;
}
static std::string pixelToString(const cv::Vec3b pixel) {
auto r = pixel.val[0];
auto g = pixel.val[1];
auto b = pixel.val[2];
return "<" + std::to_string(r) + ", " + std::to_string(g) + ", " + std::to_string(b) + ">";
}
static ws2811_led_t pixelToLEDColor(const cv::Vec3b pixel) {
uint8_t red = GAMMA_E[pixel.val[0]];
uint8_t green = GAMMA_E[pixel.val[1]];
uint8_t blue = GAMMA_E[pixel.val[2]];
return (uint32_t(red) << 16) | (uint32_t(green) << 8) | uint32_t(blue);
}
static void transform(cv::Vec3f& p, size_t y) {
float h = p[0];
float s = p[1];
float v = p[2];
}
static void clearLEDs() {
for (size_t i = 0; i < LED_COUNT; ++i) {
gLEDs.channel[0].leds[i] = 0;
}
}
int main(int, char**) {
std::signal(SIGSEGV, crashHandler);
std::signal(SIGINT, signalHandler);
std::signal(SIGTERM, signalHandler);
log("Initializing LED driver. OpenCV version " + std::string(CV_VERSION));
ws2811_return_t ret;
if ((ret = ws2811_init(&gLEDs)) != WS2811_SUCCESS) {
fprintf(stderr, "ws2811_init failed: %s\n", ws2811_get_return_t_str(ret));
return ret;
}
log("Opening video capture device");
cv::VideoCapture cap(0);
if (!cap.isOpened()) {
return -1;
}
log("Starting video capture");
cv::Mat3b frame;
cv::Mat3b downsampled;
cv::Mat3b cropped;
cv::Mat3f inputHSV;
cv::Mat3f outputHSV = cv::Mat::zeros(1, LED_COUNT, CV_32FC3);
cv::Mat3b outputRGB;
while (gRunning) {
auto frameEnd = std::chrono::steady_clock::now() + FRAME_TIME;
cap >> frame;
cv::resize(frame, downsampled, RESIZE_SIZE, 0, 0, cv::INTER_AREA);
cropped = downsampled(CROP_RECT);
cropped.convertTo(inputHSV, CV_32FC3, 1.0 / 255.0);
cv::cvtColor(inputHSV, inputHSV, CV_BGR2HSV);
// Read, transform, and write the left column
for (size_t y = 0; y < IMAGE_SIZE; y++) {
cv::Vec3f p = inputHSV.at<cv::Vec3f>(y, 0);
transform(p, y);
outputHSV.at<cv::Vec3f>(0, y) = p;
}
// Read, transform, and write the right column
for (size_t y = 0; y < IMAGE_SIZE; y++) {
cv::Vec3f p = inputHSV.at<cv::Vec3f>(y, IMAGE_SIZE - 2);
transform(p, y);
outputHSV.at<cv::Vec3f>(0, IMAGE_SIZE + y) = p;
}
// Convert HSV back to RGB
cv::cvtColor(outputHSV, outputHSV, CV_HSV2RGB);
outputHSV.convertTo(outputRGB, CV_8UC3, 255.0f);
// Write the RGB colors out to the driver
for (size_t i = 0; i < LED_COUNT; i++) {
cv::Vec3b pixel = outputRGB.at<cv::Vec3b>(0, i);
gLEDs.channel[0].leds[i] = pixelToLEDColor(pixel);
}
ws2811_render(&gLEDs);
std::this_thread::sleep_until(frameEnd);
}
// Clear the LEDs and gracefully stop DMA writes
clearLEDs();
ws2811_render(&gLEDs);
ws2811_fini(&gLEDs);
return 0;
}
| 31.545946 | 95 | 0.609664 | [
"transform"
] |
e685d25cdb7ec9d2800513132bc63599fbcde0ff | 41,652 | cc | C++ | tests/zlib.cc | lethalbit/libalfheim | e70db0db7a7998e974e08fe2a955814e247e1ff6 | [
"BSD-3-Clause"
] | 1 | 2021-05-05T15:58:36.000Z | 2021-05-05T15:58:36.000Z | tests/zlib.cc | lethalbit/libalfheim | e70db0db7a7998e974e08fe2a955814e247e1ff6 | [
"BSD-3-Clause"
] | null | null | null | tests/zlib.cc | lethalbit/libalfheim | e70db0db7a7998e974e08fe2a955814e247e1ff6 | [
"BSD-3-Clause"
] | null | null | null | /* SPDX-License-Identifier: BSD-3-Clause */
/* zlib.cc - libalfheim zlib test suite */
#include <libalfheim/internal/zlib.hh>
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
using libalfheim::internal::gzfile_t;
using libalfheim::internal::zlib_t;
// HACK!: These tests will explode on any machine other than a little-endian one
// To fix this it takes effort, and I can't be arsed right now.
struct med_t final {
std::uint64_t foo;
std::uint8_t bar;
};
constexpr bool operator==(const med_t& lh, const med_t& rh) noexcept {
return (lh.foo == rh.foo) && (lh.bar == rh.bar);
}
struct chonky_t final {
std::uint64_t foo;
std::uint8_t bar;
std::array<std::uint32_t, 64> baz;
};
TEST_CASE( "inflate type - array source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
SECTION( "small type" ) {
constexpr std::array<std::uint8_t, 9> compressed{{
0x78, 0x9c, 0x5b, 0x05, 0x00, 0x00, 0xab, 0x00,
0xab
}};
auto smol = zlib.inflate<uint8_t>(compressed);
REQUIRE(zlib.valid());
REQUIRE(smol);
REQUIRE(*smol == 0xAA);
}
REQUIRE(zlib.valid());
SECTION( "medium type" ) {
constexpr std::array<std::uint8_t, 17> compressed{{
0x78, 0x9c, 0x63, 0x10, 0x54, 0x32, 0x76, 0x09,
0x4d, 0x2b, 0xef, 0x00, 0x00, 0x08, 0x01, 0x02,
0x65
}};
auto med = zlib.inflate<med_t>(compressed);
REQUIRE(zlib.valid());
REQUIRE(med);
REQUIRE(med->foo == 0x7766554433221100);
REQUIRE(med->bar == 0x88);
}
REQUIRE(zlib.valid());
SECTION( "chonky type" ) {
constexpr std::array<std::uint8_t, 20> compressed{{
0x78, 0x9c, 0x2b, 0x4f, 0x0b, 0x75, 0x31, 0x56,
0x12, 0x64, 0x58, 0xb5, 0x74, 0x84, 0x03, 0x00,
0x6c, 0x32, 0xa7, 0x87
}};
constexpr std::array<std::uint32_t, 64> baz{{
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0x000000a5
}};
auto chonk = zlib.inflate<chonky_t>(compressed);
REQUIRE(zlib.valid());
REQUIRE(chonk);
REQUIRE(chonk->foo == 0x0011223344556677);
REQUIRE(chonk->bar == 0xAA);
REQUIRE(chonk->baz == baz);
}
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate type - vector source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
SECTION( "small type" ) {
const std::vector<std::uint8_t> compressed{{
0x78, 0x9c, 0x5b, 0x05, 0x00, 0x00, 0xab, 0x00,
0xab
}};
auto smol = zlib.inflate<uint8_t>(compressed);
REQUIRE(zlib.valid());
REQUIRE(smol);
REQUIRE(*smol == 0xAA);
}
REQUIRE(zlib.valid());
SECTION( "medium type" ) {
const std::vector<std::uint8_t> compressed{{
0x78, 0x9c, 0x63, 0x10, 0x54, 0x32, 0x76, 0x09,
0x4d, 0x2b, 0xef, 0x00, 0x00, 0x08, 0x01, 0x02,
0x65
}};
auto med = zlib.inflate<med_t>(compressed);
REQUIRE(zlib.valid());
REQUIRE(med);
REQUIRE(med->foo == 0x7766554433221100);
REQUIRE(med->bar == 0x88);
}
REQUIRE(zlib.valid());
SECTION( "chonky type" ) {
const std::vector<std::uint8_t> compressed{{
0x78, 0x9c, 0x2b, 0x4f, 0x0b, 0x75, 0x31, 0x56,
0x12, 0x64, 0x58, 0xb5, 0x74, 0x84, 0x03, 0x00,
0x6c, 0x32, 0xa7, 0x87
}};
constexpr std::array<std::uint32_t, 64> baz{{
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0x000000a5
}};
auto chonk = zlib.inflate<chonky_t>(compressed);
REQUIRE(zlib.valid());
REQUIRE(chonk);
REQUIRE(chonk->foo == 0x0011223344556677);
REQUIRE(chonk->bar == 0xAA);
REQUIRE(chonk->baz == baz);
}
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate type - raw source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
SECTION( "small type" ) {
const std::uint8_t compressed[9] = {
0x78, 0x9c, 0x5b, 0x05, 0x00, 0x00, 0xab, 0x00,
0xab
};
auto smol = zlib.inflate<uint8_t>(compressed, 9);
REQUIRE(zlib.valid());
REQUIRE(smol);
REQUIRE(*smol == 0xAA);
}
REQUIRE(zlib.valid());
SECTION( "medium type" ) {
const std::uint8_t compressed[17] = {
0x78, 0x9c, 0x63, 0x10, 0x54, 0x32, 0x76, 0x09,
0x4d, 0x2b, 0xef, 0x00, 0x00, 0x08, 0x01, 0x02,
0x65
};
auto med = zlib.inflate<med_t>(compressed, 17);
REQUIRE(zlib.valid());
REQUIRE(med);
REQUIRE(med->foo == 0x7766554433221100);
REQUIRE(med->bar == 0x88);
}
REQUIRE(zlib.valid());
SECTION( "chonky type" ) {
const std::uint8_t compressed[20] = {
0x78, 0x9c, 0x2b, 0x4f, 0x0b, 0x75, 0x31, 0x56,
0x12, 0x64, 0x58, 0xb5, 0x74, 0x84, 0x03, 0x00,
0x6c, 0x32, 0xa7, 0x87
};
constexpr std::array<std::uint32_t, 64> baz{{
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0x000000a5
}};
auto chonk = zlib.inflate<chonky_t>(compressed, 20);
REQUIRE(zlib.valid());
REQUIRE(chonk);
REQUIRE(chonk->foo == 0x0011223344556677);
REQUIRE(chonk->bar == 0xAA);
REQUIRE(chonk->baz == baz);
}
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate type array - vector source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
SECTION( "small type" ) {
const std::vector<std::uint8_t> compressed{{
0x78, 0x9c, 0x5b, 0xba, 0x14, 0x08, 0x00, 0x09,
0xb0, 0x03, 0x3a
}};
const std::array<std::uint8_t, 5> decompressed_ref{{
0xA5, 0xA5, 0xA5, 0xA5, 0xA5
}};
auto smol = zlib.inflate<std::array<std::uint8_t, 5>>(compressed);
REQUIRE(zlib.valid());
REQUIRE(smol);
REQUIRE(*smol == decompressed_ref);
}
REQUIRE(zlib.valid());
SECTION( "medium type" ) {
const std::vector<std::uint8_t> compressed{{
0x78, 0x9c, 0x63, 0x10, 0x54, 0x32, 0x76, 0x09,
0x4d, 0x2b, 0xef, 0x60, 0x80, 0x80, 0xf2, 0xb4,
0x50, 0x17, 0x63, 0x25, 0x41, 0x86, 0xa5, 0x50,
0x3e, 0x00, 0x5e, 0x44, 0x04, 0xe6
}};
const std::array<med_t, 2> decompressed_ref{{
{ 0x7766554433221100, 0x88 }, { 0x0011223344556677, 0xA5 }
}};
auto med = zlib.inflate<std::array<med_t, 2>>(compressed);
REQUIRE(zlib.valid());
REQUIRE(med);
REQUIRE(*med == decompressed_ref);
}
REQUIRE(zlib.valid());
SECTION( "chonky type" ) {
}
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate type array - raw source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate type vector - vector source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate type vector - raw source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate raw buffer - array source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
constexpr std::array<std::uint8_t, 525> compressed{{
0x78, 0x9c, 0x7d, 0x53, 0x31, 0x92, 0xdb, 0x30, 0x0c, 0xec, 0xf5, 0x0a,
0x74, 0x6e, 0x74, 0x9e, 0xdc, 0x13, 0xd2, 0x5d, 0x9a, 0xa4, 0x70, 0x95,
0x12, 0x22, 0x21, 0x8b, 0x67, 0x8a, 0xf0, 0x90, 0x90, 0x1d, 0xfd, 0x3e,
0x4b, 0x4a, 0x76, 0x72, 0xc9, 0x24, 0x95, 0x04, 0x12, 0x58, 0x60, 0xb1,
0xcb, 0xb7, 0x60, 0x7c, 0x0e, 0x74, 0x92, 0xf4, 0xae, 0xcb, 0x99, 0x27,
0xce, 0x4c, 0xa1, 0x50, 0x96, 0x33, 0x67, 0x2f, 0xbe, 0xe3, 0x42, 0x4c,
0x45, 0x5f, 0x1c, 0xc7, 0x28, 0x9e, 0xee, 0xc2, 0x17, 0x3a, 0x87, 0x1c,
0x29, 0x24, 0xb2, 0x49, 0xc8, 0x45, 0x2e, 0xe5, 0xd8, 0x51, 0xf7, 0x39,
0xda, 0x04, 0x84, 0x09, 0xa7, 0xb9, 0x7e, 0x75, 0x31, 0x9a, 0x02, 0xe2,
0xe2, 0x26, 0xd5, 0x48, 0x05, 0xc9, 0x53, 0x45, 0x8b, 0x77, 0x5e, 0x0b,
0x0d, 0x22, 0xe9, 0x81, 0x51, 0x78, 0xde, 0x81, 0x08, 0x09, 0xb3, 0xf4,
0xdd, 0xa8, 0x99, 0xc6, 0x90, 0x8b, 0xd1, 0x2a, 0x9c, 0x7b, 0x2a, 0xe2,
0x34, 0xf9, 0x16, 0x10, 0xe3, 0xc7, 0xa6, 0x90, 0xf7, 0xf0, 0x05, 0x01,
0xdb, 0xa1, 0xd4, 0xb3, 0xb2, 0xa7, 0x7f, 0x41, 0xa7, 0x9b, 0x50, 0x92,
0x9b, 0x64, 0xd2, 0xe4, 0xd0, 0x02, 0xed, 0xba, 0x09, 0x91, 0x57, 0x00,
0xac, 0xc8, 0x4d, 0x67, 0x62, 0x67, 0xe1, 0x26, 0x47, 0x3a, 0x4d, 0x72,
0x78, 0x0e, 0xb6, 0xcf, 0x34, 0xb0, 0xbb, 0x90, 0x8e, 0xbf, 0x38, 0x66,
0xd5, 0xb9, 0xf5, 0xce, 0xc2, 0x1e, 0xd5, 0x1d, 0xd3, 0xa0, 0x7a, 0xa1,
0x61, 0x25, 0xe0, 0x16, 0x89, 0x63, 0x03, 0xfa, 0x9d, 0x63, 0x61, 0xfb,
0x2f, 0x5c, 0xdf, 0xed, 0x58, 0x0d, 0xa9, 0x96, 0x69, 0xaa, 0xe3, 0xe8,
0x2c, 0x16, 0x66, 0xc1, 0x2c, 0x56, 0xb5, 0x60, 0x60, 0x66, 0xef, 0xb4,
0x92, 0xa9, 0x5c, 0x29, 0xb6, 0x6c, 0x1f, 0xc6, 0x31, 0xb8, 0x25, 0x5a,
0xdf, 0xa9, 0x55, 0x6a, 0x1f, 0x6b, 0x9c, 0xce, 0xc1, 0x6d, 0x23, 0xde,
0x83, 0x4d, 0xed, 0xa4, 0x22, 0x78, 0x29, 0xe1, 0x5c, 0x57, 0xef, 0x83,
0x63, 0xab, 0x44, 0x1a, 0x26, 0xca, 0xee, 0x21, 0x46, 0x5c, 0x3b, 0x0c,
0x55, 0x84, 0x56, 0x5d, 0x32, 0xb2, 0x4c, 0xa0, 0xbb, 0x33, 0x7a, 0x5f,
0x20, 0x06, 0xb8, 0x3e, 0x26, 0x0e, 0x56, 0x45, 0x3f, 0x2d, 0xb0, 0xcf,
0x10, 0xd7, 0xbe, 0xca, 0x8b, 0x1d, 0x96, 0x99, 0xb3, 0xb5, 0x2d, 0xd5,
0x19, 0xac, 0xd1, 0x35, 0xbd, 0x7e, 0x60, 0x8e, 0xb2, 0xef, 0xba, 0x1c,
0x3c, 0x5a, 0x8d, 0x21, 0x05, 0x34, 0x58, 0xa1, 0x75, 0x13, 0x15, 0x92,
0x55, 0x2b, 0xbc, 0xfd, 0xed, 0xc9, 0xae, 0x72, 0xd8, 0x77, 0x59, 0x01,
0x5f, 0x3f, 0xb5, 0xd4, 0xa7, 0x5c, 0x99, 0xd3, 0x05, 0x63, 0x95, 0xee,
0x8a, 0x0e, 0xf0, 0x69, 0x75, 0x1f, 0x8f, 0x26, 0xd5, 0x2e, 0x24, 0x3f,
0x78, 0x6e, 0xd3, 0x22, 0xd1, 0xab, 0x94, 0x74, 0xb0, 0x6a, 0x88, 0x19,
0x48, 0x9b, 0x51, 0xe0, 0x08, 0x1a, 0x73, 0x90, 0xe4, 0x61, 0xe5, 0xaf,
0x6a, 0x04, 0xe3, 0x24, 0x18, 0x47, 0xe8, 0x0a, 0x69, 0x35, 0xd5, 0xe2,
0x6f, 0x23, 0x16, 0xb8, 0x40, 0xe8, 0x1e, 0x17, 0xad, 0xe7, 0xb6, 0xf5,
0x09, 0x6c, 0xfb, 0xba, 0x2d, 0x72, 0xdc, 0x80, 0x79, 0xdd, 0x54, 0xda,
0x36, 0x32, 0x48, 0xd3, 0x77, 0x89, 0x31, 0x88, 0x3f, 0x76, 0x7f, 0xbe,
0xb3, 0xcd, 0x29, 0xfd, 0x43, 0xa2, 0x91, 0xe1, 0xd5, 0x18, 0x2e, 0x82,
0xfd, 0xa2, 0x38, 0xb1, 0x2d, 0x99, 0x63, 0x5f, 0xdb, 0x65, 0x34, 0xfe,
0x97, 0x99, 0xfa, 0xa7, 0x2c, 0x9b, 0x29, 0x8f, 0x8d, 0xea, 0x1d, 0x4e,
0x1c, 0x96, 0x10, 0xf7, 0x8b, 0x3b, 0x5e, 0x30, 0x31, 0xde, 0x26, 0x56,
0xfd, 0x70, 0x6c, 0xf7, 0x13, 0x99, 0x79, 0x66, 0x60
}};
const std::vector<std::uint8_t> decompressed_ref{{
0x48, 0x69, 0x74, 0x61, 0x67, 0x69, 0x20, 0x53, 0x65, 0x6e, 0x6a, 0x6f,
0x75, 0x67, 0x61, 0x68, 0x61, 0x72, 0x61, 0x20, 0x69, 0x73, 0x20, 0x72,
0x65, 0x67, 0x61, 0x72, 0x64, 0x65, 0x64, 0x0a, 0x61, 0x73, 0x20, 0x61,
0x20, 0x73, 0x6f, 0x2d, 0x63, 0x61, 0x6c, 0x6c, 0x65, 0x64, 0x20, 0x77,
0x65, 0x61, 0x6b, 0x20, 0x67, 0x69, 0x72, 0x6c, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x2e, 0x0a, 0x20,
0x0a, 0x41, 0x6c, 0x74, 0x68, 0x6f, 0x75, 0x67, 0x68, 0x20, 0x74, 0x68,
0x72, 0x6f, 0x75, 0x67, 0x68, 0x6f, 0x75, 0x74, 0x20, 0x68, 0x69, 0x67,
0x68, 0x20, 0x73, 0x63, 0x68, 0x6f, 0x6f, 0x6c, 0x20, 0x73, 0x68, 0x65,
0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20,
0x62, 0x65, 0x65, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x73, 0x61, 0x6d, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x61,
0x73, 0x20, 0x6d, 0x65, 0x2c, 0x0a, 0x66, 0x6f, 0x72, 0x20, 0x66, 0x69,
0x72, 0x73, 0x74, 0x20, 0x79, 0x65, 0x61, 0x72, 0x2c, 0x20, 0x73, 0x65,
0x63, 0x6f, 0x6e, 0x64, 0x20, 0x79, 0x65, 0x61, 0x72, 0x20, 0x61, 0x6e,
0x64, 0x20, 0x74, 0x68, 0x69, 0x72, 0x64, 0x20, 0x79, 0x65, 0x61, 0x72,
0x20, 0x2d, 0x20, 0x74, 0x68, 0x61, 0x74, 0x27, 0x73, 0x20, 0x74, 0x68,
0x69, 0x73, 0x20, 0x79, 0x65, 0x61, 0x72, 0x2c, 0x20, 0x49, 0x20, 0x68,
0x61, 0x76, 0x65, 0x20, 0x6e, 0x65, 0x76, 0x65, 0x72, 0x20, 0x6f, 0x6e,
0x63, 0x65, 0x20, 0x73, 0x65, 0x65, 0x6e, 0x0a, 0x68, 0x65, 0x72, 0x20,
0x64, 0x6f, 0x20, 0x61, 0x6e, 0x79, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x20,
0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x2e, 0x20, 0x53, 0x68, 0x65, 0x27,
0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x72, 0x6f, 0x6f,
0x6d, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69, 0x6e,
0x67, 0x0a, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x20, 0x62, 0x79, 0x20,
0x68, 0x65, 0x72, 0x73, 0x65, 0x6c, 0x66, 0x2e, 0x20, 0x53, 0x68, 0x65,
0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20,
0x73, 0x61, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x62,
0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63,
0x6c, 0x61, 0x73, 0x73, 0x72, 0x6f, 0x6f, 0x6d, 0x2c, 0x0a, 0x72, 0x65,
0x61, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x73, 0x20,
0x61, 0x6c, 0x6f, 0x6e, 0x65, 0x2e, 0x20, 0x53, 0x6f, 0x6d, 0x65, 0x74,
0x69, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x61,
0x20, 0x68, 0x61, 0x72, 0x64, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x73, 0x20, 0x64, 0x69,
0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x2c, 0x0a, 0x6f, 0x74, 0x68,
0x65, 0x72, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x74, 0x20,
0x69, 0x73, 0x20, 0x61, 0x20, 0x63, 0x6f, 0x6d, 0x69, 0x63, 0x20, 0x62,
0x6f, 0x6f, 0x6b, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x63,
0x6f, 0x76, 0x65, 0x72, 0x20, 0x64, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20,
0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x0a, 0x74,
0x68, 0x61, 0x74, 0x20, 0x69, 0x74, 0x20, 0x77, 0x69, 0x6c, 0x6c, 0x20,
0x64, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x20, 0x79, 0x6f, 0x75,
0x72, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x20,
0x6a, 0x75, 0x73, 0x74, 0x20, 0x62, 0x79, 0x20, 0x72, 0x65, 0x61, 0x64,
0x69, 0x6e, 0x67, 0x20, 0x69, 0x74, 0x2e, 0x0a, 0x20, 0x0a, 0x53, 0x75,
0x69, 0x74, 0x61, 0x62, 0x6c, 0x79, 0x2c, 0x20, 0x73, 0x68, 0x65, 0x27,
0x73, 0x20, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x20, 0x61, 0x6e, 0x64, 0x20,
0x69, 0x73, 0x20, 0x61, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x6f,
0x70, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61,
0x73, 0x73, 0x0a, 0x20, 0x0a, 0x59, 0x6f, 0x75, 0x27, 0x64, 0x20, 0x64,
0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x65, 0x6c, 0x79, 0x20, 0x66, 0x69,
0x6e, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20,
0x48, 0x69, 0x74, 0x61, 0x67, 0x69, 0x20, 0x53, 0x65, 0x6e, 0x6a, 0x6f,
0x75, 0x67, 0x61, 0x68, 0x61, 0x72, 0x61, 0x0a, 0x77, 0x69, 0x74, 0x68,
0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x6f, 0x70, 0x20, 0x31,
0x30, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x74,
0x68, 0x65, 0x20, 0x72, 0x61, 0x6e, 0x6b, 0x69, 0x6e, 0x67, 0x73, 0x0a,
0x70, 0x61, 0x73, 0x73, 0x65, 0x64, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x61,
0x66, 0x74, 0x65, 0x72, 0x20, 0x61, 0x6e, 0x20, 0x65, 0x78, 0x61, 0x6d,
0x2e, 0x0a, 0x20, 0x0a, 0x53, 0x68, 0x65, 0x20, 0x64, 0x6f, 0x65, 0x73,
0x6e, 0x27, 0x74, 0x20, 0x73, 0x65, 0x65, 0x6d, 0x20, 0x74, 0x6f, 0x20,
0x68, 0x61, 0x76, 0x65, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x66, 0x72, 0x69,
0x65, 0x6e, 0x64, 0x73, 0x2e, 0x0a, 0x4e, 0x6f, 0x74, 0x20, 0x65, 0x76,
0x65, 0x6e, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x70, 0x65, 0x72, 0x73, 0x6f,
0x6e, 0x2e, 0x0a, 0x20, 0x0a, 0x4f, 0x66, 0x20, 0x63, 0x6f, 0x75, 0x72,
0x73, 0x65, 0x2c, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6f,
0x74, 0x68, 0x65, 0x72, 0x20, 0x68, 0x61, 0x6e, 0x64, 0x2c, 0x20, 0x79,
0x6f, 0x75, 0x20, 0x63, 0x61, 0x6e, 0x27, 0x74, 0x20, 0x73, 0x61, 0x79,
0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x73, 0x68, 0x65, 0x27, 0x73, 0x20,
0x62, 0x65, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x6c, 0x6c, 0x69, 0x65,
0x64, 0x2e, 0x0a, 0x53, 0x65, 0x6e, 0x6a, 0x6f, 0x75, 0x67, 0x61, 0x68,
0x61, 0x72, 0x61, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79,
0x73, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x66, 0x61,
0x63, 0x65, 0x20, 0x6c, 0x69, 0x6b, 0x65, 0x20, 0x69, 0x74, 0x27, 0x73,
0x20, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x61, 0x6c, 0x2c, 0x20, 0x74, 0x68,
0x65, 0x72, 0x65, 0x2c, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x62, 0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20,
0x63, 0x6c, 0x61, 0x73, 0x73, 0x2c, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69,
0x6e, 0x67, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x2e, 0x0a, 0x53,
0x68, 0x65, 0x20, 0x77, 0x61, 0x73, 0x20, 0x62, 0x75, 0x69, 0x6c, 0x64,
0x69, 0x6e, 0x67, 0x20, 0x61, 0x20, 0x77, 0x61, 0x6c, 0x6c, 0x20, 0x61,
0x72, 0x6f, 0x75, 0x6e, 0x64, 0x20, 0x68, 0x65, 0x72, 0x73, 0x65, 0x6c,
0x66, 0x2e, 0x0a,
}};
std::optional<std::vector<std::uint8_t>> decompressed = zlib.inflate(compressed);
REQUIRE(zlib.valid());
REQUIRE(decompressed);
REQUIRE(decompressed->size() == 1023);
REQUIRE(*decompressed == decompressed_ref);
}
TEST_CASE( "inflate raw buffer - vector source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
const std::vector<std::uint8_t> compressed{{
0x78, 0x9c, 0x7d, 0x53, 0x31, 0x92, 0xdb, 0x30, 0x0c, 0xec, 0xf5, 0x0a,
0x74, 0x6e, 0x74, 0x9e, 0xdc, 0x13, 0xd2, 0x5d, 0x9a, 0xa4, 0x70, 0x95,
0x12, 0x22, 0x21, 0x8b, 0x67, 0x8a, 0xf0, 0x90, 0x90, 0x1d, 0xfd, 0x3e,
0x4b, 0x4a, 0x76, 0x72, 0xc9, 0x24, 0x95, 0x04, 0x12, 0x58, 0x60, 0xb1,
0xcb, 0xb7, 0x60, 0x7c, 0x0e, 0x74, 0x92, 0xf4, 0xae, 0xcb, 0x99, 0x27,
0xce, 0x4c, 0xa1, 0x50, 0x96, 0x33, 0x67, 0x2f, 0xbe, 0xe3, 0x42, 0x4c,
0x45, 0x5f, 0x1c, 0xc7, 0x28, 0x9e, 0xee, 0xc2, 0x17, 0x3a, 0x87, 0x1c,
0x29, 0x24, 0xb2, 0x49, 0xc8, 0x45, 0x2e, 0xe5, 0xd8, 0x51, 0xf7, 0x39,
0xda, 0x04, 0x84, 0x09, 0xa7, 0xb9, 0x7e, 0x75, 0x31, 0x9a, 0x02, 0xe2,
0xe2, 0x26, 0xd5, 0x48, 0x05, 0xc9, 0x53, 0x45, 0x8b, 0x77, 0x5e, 0x0b,
0x0d, 0x22, 0xe9, 0x81, 0x51, 0x78, 0xde, 0x81, 0x08, 0x09, 0xb3, 0xf4,
0xdd, 0xa8, 0x99, 0xc6, 0x90, 0x8b, 0xd1, 0x2a, 0x9c, 0x7b, 0x2a, 0xe2,
0x34, 0xf9, 0x16, 0x10, 0xe3, 0xc7, 0xa6, 0x90, 0xf7, 0xf0, 0x05, 0x01,
0xdb, 0xa1, 0xd4, 0xb3, 0xb2, 0xa7, 0x7f, 0x41, 0xa7, 0x9b, 0x50, 0x92,
0x9b, 0x64, 0xd2, 0xe4, 0xd0, 0x02, 0xed, 0xba, 0x09, 0x91, 0x57, 0x00,
0xac, 0xc8, 0x4d, 0x67, 0x62, 0x67, 0xe1, 0x26, 0x47, 0x3a, 0x4d, 0x72,
0x78, 0x0e, 0xb6, 0xcf, 0x34, 0xb0, 0xbb, 0x90, 0x8e, 0xbf, 0x38, 0x66,
0xd5, 0xb9, 0xf5, 0xce, 0xc2, 0x1e, 0xd5, 0x1d, 0xd3, 0xa0, 0x7a, 0xa1,
0x61, 0x25, 0xe0, 0x16, 0x89, 0x63, 0x03, 0xfa, 0x9d, 0x63, 0x61, 0xfb,
0x2f, 0x5c, 0xdf, 0xed, 0x58, 0x0d, 0xa9, 0x96, 0x69, 0xaa, 0xe3, 0xe8,
0x2c, 0x16, 0x66, 0xc1, 0x2c, 0x56, 0xb5, 0x60, 0x60, 0x66, 0xef, 0xb4,
0x92, 0xa9, 0x5c, 0x29, 0xb6, 0x6c, 0x1f, 0xc6, 0x31, 0xb8, 0x25, 0x5a,
0xdf, 0xa9, 0x55, 0x6a, 0x1f, 0x6b, 0x9c, 0xce, 0xc1, 0x6d, 0x23, 0xde,
0x83, 0x4d, 0xed, 0xa4, 0x22, 0x78, 0x29, 0xe1, 0x5c, 0x57, 0xef, 0x83,
0x63, 0xab, 0x44, 0x1a, 0x26, 0xca, 0xee, 0x21, 0x46, 0x5c, 0x3b, 0x0c,
0x55, 0x84, 0x56, 0x5d, 0x32, 0xb2, 0x4c, 0xa0, 0xbb, 0x33, 0x7a, 0x5f,
0x20, 0x06, 0xb8, 0x3e, 0x26, 0x0e, 0x56, 0x45, 0x3f, 0x2d, 0xb0, 0xcf,
0x10, 0xd7, 0xbe, 0xca, 0x8b, 0x1d, 0x96, 0x99, 0xb3, 0xb5, 0x2d, 0xd5,
0x19, 0xac, 0xd1, 0x35, 0xbd, 0x7e, 0x60, 0x8e, 0xb2, 0xef, 0xba, 0x1c,
0x3c, 0x5a, 0x8d, 0x21, 0x05, 0x34, 0x58, 0xa1, 0x75, 0x13, 0x15, 0x92,
0x55, 0x2b, 0xbc, 0xfd, 0xed, 0xc9, 0xae, 0x72, 0xd8, 0x77, 0x59, 0x01,
0x5f, 0x3f, 0xb5, 0xd4, 0xa7, 0x5c, 0x99, 0xd3, 0x05, 0x63, 0x95, 0xee,
0x8a, 0x0e, 0xf0, 0x69, 0x75, 0x1f, 0x8f, 0x26, 0xd5, 0x2e, 0x24, 0x3f,
0x78, 0x6e, 0xd3, 0x22, 0xd1, 0xab, 0x94, 0x74, 0xb0, 0x6a, 0x88, 0x19,
0x48, 0x9b, 0x51, 0xe0, 0x08, 0x1a, 0x73, 0x90, 0xe4, 0x61, 0xe5, 0xaf,
0x6a, 0x04, 0xe3, 0x24, 0x18, 0x47, 0xe8, 0x0a, 0x69, 0x35, 0xd5, 0xe2,
0x6f, 0x23, 0x16, 0xb8, 0x40, 0xe8, 0x1e, 0x17, 0xad, 0xe7, 0xb6, 0xf5,
0x09, 0x6c, 0xfb, 0xba, 0x2d, 0x72, 0xdc, 0x80, 0x79, 0xdd, 0x54, 0xda,
0x36, 0x32, 0x48, 0xd3, 0x77, 0x89, 0x31, 0x88, 0x3f, 0x76, 0x7f, 0xbe,
0xb3, 0xcd, 0x29, 0xfd, 0x43, 0xa2, 0x91, 0xe1, 0xd5, 0x18, 0x2e, 0x82,
0xfd, 0xa2, 0x38, 0xb1, 0x2d, 0x99, 0x63, 0x5f, 0xdb, 0x65, 0x34, 0xfe,
0x97, 0x99, 0xfa, 0xa7, 0x2c, 0x9b, 0x29, 0x8f, 0x8d, 0xea, 0x1d, 0x4e,
0x1c, 0x96, 0x10, 0xf7, 0x8b, 0x3b, 0x5e, 0x30, 0x31, 0xde, 0x26, 0x56,
0xfd, 0x70, 0x6c, 0xf7, 0x13, 0x99, 0x79, 0x66, 0x60
}};
const std::vector<std::uint8_t> decompressed_ref{{
0x48, 0x69, 0x74, 0x61, 0x67, 0x69, 0x20, 0x53, 0x65, 0x6e, 0x6a, 0x6f,
0x75, 0x67, 0x61, 0x68, 0x61, 0x72, 0x61, 0x20, 0x69, 0x73, 0x20, 0x72,
0x65, 0x67, 0x61, 0x72, 0x64, 0x65, 0x64, 0x0a, 0x61, 0x73, 0x20, 0x61,
0x20, 0x73, 0x6f, 0x2d, 0x63, 0x61, 0x6c, 0x6c, 0x65, 0x64, 0x20, 0x77,
0x65, 0x61, 0x6b, 0x20, 0x67, 0x69, 0x72, 0x6c, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x2e, 0x0a, 0x20,
0x0a, 0x41, 0x6c, 0x74, 0x68, 0x6f, 0x75, 0x67, 0x68, 0x20, 0x74, 0x68,
0x72, 0x6f, 0x75, 0x67, 0x68, 0x6f, 0x75, 0x74, 0x20, 0x68, 0x69, 0x67,
0x68, 0x20, 0x73, 0x63, 0x68, 0x6f, 0x6f, 0x6c, 0x20, 0x73, 0x68, 0x65,
0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20,
0x62, 0x65, 0x65, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x73, 0x61, 0x6d, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x61,
0x73, 0x20, 0x6d, 0x65, 0x2c, 0x0a, 0x66, 0x6f, 0x72, 0x20, 0x66, 0x69,
0x72, 0x73, 0x74, 0x20, 0x79, 0x65, 0x61, 0x72, 0x2c, 0x20, 0x73, 0x65,
0x63, 0x6f, 0x6e, 0x64, 0x20, 0x79, 0x65, 0x61, 0x72, 0x20, 0x61, 0x6e,
0x64, 0x20, 0x74, 0x68, 0x69, 0x72, 0x64, 0x20, 0x79, 0x65, 0x61, 0x72,
0x20, 0x2d, 0x20, 0x74, 0x68, 0x61, 0x74, 0x27, 0x73, 0x20, 0x74, 0x68,
0x69, 0x73, 0x20, 0x79, 0x65, 0x61, 0x72, 0x2c, 0x20, 0x49, 0x20, 0x68,
0x61, 0x76, 0x65, 0x20, 0x6e, 0x65, 0x76, 0x65, 0x72, 0x20, 0x6f, 0x6e,
0x63, 0x65, 0x20, 0x73, 0x65, 0x65, 0x6e, 0x0a, 0x68, 0x65, 0x72, 0x20,
0x64, 0x6f, 0x20, 0x61, 0x6e, 0x79, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x20,
0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x2e, 0x20, 0x53, 0x68, 0x65, 0x27,
0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x72, 0x6f, 0x6f,
0x6d, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69, 0x6e,
0x67, 0x0a, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x20, 0x62, 0x79, 0x20,
0x68, 0x65, 0x72, 0x73, 0x65, 0x6c, 0x66, 0x2e, 0x20, 0x53, 0x68, 0x65,
0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20,
0x73, 0x61, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x62,
0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63,
0x6c, 0x61, 0x73, 0x73, 0x72, 0x6f, 0x6f, 0x6d, 0x2c, 0x0a, 0x72, 0x65,
0x61, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x73, 0x20,
0x61, 0x6c, 0x6f, 0x6e, 0x65, 0x2e, 0x20, 0x53, 0x6f, 0x6d, 0x65, 0x74,
0x69, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x61,
0x20, 0x68, 0x61, 0x72, 0x64, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x73, 0x20, 0x64, 0x69,
0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x2c, 0x0a, 0x6f, 0x74, 0x68,
0x65, 0x72, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x74, 0x20,
0x69, 0x73, 0x20, 0x61, 0x20, 0x63, 0x6f, 0x6d, 0x69, 0x63, 0x20, 0x62,
0x6f, 0x6f, 0x6b, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x63,
0x6f, 0x76, 0x65, 0x72, 0x20, 0x64, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20,
0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x0a, 0x74,
0x68, 0x61, 0x74, 0x20, 0x69, 0x74, 0x20, 0x77, 0x69, 0x6c, 0x6c, 0x20,
0x64, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x20, 0x79, 0x6f, 0x75,
0x72, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x20,
0x6a, 0x75, 0x73, 0x74, 0x20, 0x62, 0x79, 0x20, 0x72, 0x65, 0x61, 0x64,
0x69, 0x6e, 0x67, 0x20, 0x69, 0x74, 0x2e, 0x0a, 0x20, 0x0a, 0x53, 0x75,
0x69, 0x74, 0x61, 0x62, 0x6c, 0x79, 0x2c, 0x20, 0x73, 0x68, 0x65, 0x27,
0x73, 0x20, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x20, 0x61, 0x6e, 0x64, 0x20,
0x69, 0x73, 0x20, 0x61, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x6f,
0x70, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61,
0x73, 0x73, 0x0a, 0x20, 0x0a, 0x59, 0x6f, 0x75, 0x27, 0x64, 0x20, 0x64,
0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x65, 0x6c, 0x79, 0x20, 0x66, 0x69,
0x6e, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20,
0x48, 0x69, 0x74, 0x61, 0x67, 0x69, 0x20, 0x53, 0x65, 0x6e, 0x6a, 0x6f,
0x75, 0x67, 0x61, 0x68, 0x61, 0x72, 0x61, 0x0a, 0x77, 0x69, 0x74, 0x68,
0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x6f, 0x70, 0x20, 0x31,
0x30, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x74,
0x68, 0x65, 0x20, 0x72, 0x61, 0x6e, 0x6b, 0x69, 0x6e, 0x67, 0x73, 0x0a,
0x70, 0x61, 0x73, 0x73, 0x65, 0x64, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x61,
0x66, 0x74, 0x65, 0x72, 0x20, 0x61, 0x6e, 0x20, 0x65, 0x78, 0x61, 0x6d,
0x2e, 0x0a, 0x20, 0x0a, 0x53, 0x68, 0x65, 0x20, 0x64, 0x6f, 0x65, 0x73,
0x6e, 0x27, 0x74, 0x20, 0x73, 0x65, 0x65, 0x6d, 0x20, 0x74, 0x6f, 0x20,
0x68, 0x61, 0x76, 0x65, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x66, 0x72, 0x69,
0x65, 0x6e, 0x64, 0x73, 0x2e, 0x0a, 0x4e, 0x6f, 0x74, 0x20, 0x65, 0x76,
0x65, 0x6e, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x70, 0x65, 0x72, 0x73, 0x6f,
0x6e, 0x2e, 0x0a, 0x20, 0x0a, 0x4f, 0x66, 0x20, 0x63, 0x6f, 0x75, 0x72,
0x73, 0x65, 0x2c, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6f,
0x74, 0x68, 0x65, 0x72, 0x20, 0x68, 0x61, 0x6e, 0x64, 0x2c, 0x20, 0x79,
0x6f, 0x75, 0x20, 0x63, 0x61, 0x6e, 0x27, 0x74, 0x20, 0x73, 0x61, 0x79,
0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x73, 0x68, 0x65, 0x27, 0x73, 0x20,
0x62, 0x65, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x6c, 0x6c, 0x69, 0x65,
0x64, 0x2e, 0x0a, 0x53, 0x65, 0x6e, 0x6a, 0x6f, 0x75, 0x67, 0x61, 0x68,
0x61, 0x72, 0x61, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79,
0x73, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x66, 0x61,
0x63, 0x65, 0x20, 0x6c, 0x69, 0x6b, 0x65, 0x20, 0x69, 0x74, 0x27, 0x73,
0x20, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x61, 0x6c, 0x2c, 0x20, 0x74, 0x68,
0x65, 0x72, 0x65, 0x2c, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x62, 0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20,
0x63, 0x6c, 0x61, 0x73, 0x73, 0x2c, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69,
0x6e, 0x67, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x2e, 0x0a, 0x53,
0x68, 0x65, 0x20, 0x77, 0x61, 0x73, 0x20, 0x62, 0x75, 0x69, 0x6c, 0x64,
0x69, 0x6e, 0x67, 0x20, 0x61, 0x20, 0x77, 0x61, 0x6c, 0x6c, 0x20, 0x61,
0x72, 0x6f, 0x75, 0x6e, 0x64, 0x20, 0x68, 0x65, 0x72, 0x73, 0x65, 0x6c,
0x66, 0x2e, 0x0a,
}};
std::optional<std::vector<std::uint8_t>> decompressed = zlib.inflate(compressed);
REQUIRE(zlib.valid());
REQUIRE(decompressed);
REQUIRE(decompressed->size() == 1023);
REQUIRE(*decompressed == decompressed_ref);
}
TEST_CASE( "inflate raw buffer - raw source", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
const std::uint8_t compressed[525] = {
0x78, 0x9c, 0x7d, 0x53, 0x31, 0x92, 0xdb, 0x30, 0x0c, 0xec, 0xf5, 0x0a,
0x74, 0x6e, 0x74, 0x9e, 0xdc, 0x13, 0xd2, 0x5d, 0x9a, 0xa4, 0x70, 0x95,
0x12, 0x22, 0x21, 0x8b, 0x67, 0x8a, 0xf0, 0x90, 0x90, 0x1d, 0xfd, 0x3e,
0x4b, 0x4a, 0x76, 0x72, 0xc9, 0x24, 0x95, 0x04, 0x12, 0x58, 0x60, 0xb1,
0xcb, 0xb7, 0x60, 0x7c, 0x0e, 0x74, 0x92, 0xf4, 0xae, 0xcb, 0x99, 0x27,
0xce, 0x4c, 0xa1, 0x50, 0x96, 0x33, 0x67, 0x2f, 0xbe, 0xe3, 0x42, 0x4c,
0x45, 0x5f, 0x1c, 0xc7, 0x28, 0x9e, 0xee, 0xc2, 0x17, 0x3a, 0x87, 0x1c,
0x29, 0x24, 0xb2, 0x49, 0xc8, 0x45, 0x2e, 0xe5, 0xd8, 0x51, 0xf7, 0x39,
0xda, 0x04, 0x84, 0x09, 0xa7, 0xb9, 0x7e, 0x75, 0x31, 0x9a, 0x02, 0xe2,
0xe2, 0x26, 0xd5, 0x48, 0x05, 0xc9, 0x53, 0x45, 0x8b, 0x77, 0x5e, 0x0b,
0x0d, 0x22, 0xe9, 0x81, 0x51, 0x78, 0xde, 0x81, 0x08, 0x09, 0xb3, 0xf4,
0xdd, 0xa8, 0x99, 0xc6, 0x90, 0x8b, 0xd1, 0x2a, 0x9c, 0x7b, 0x2a, 0xe2,
0x34, 0xf9, 0x16, 0x10, 0xe3, 0xc7, 0xa6, 0x90, 0xf7, 0xf0, 0x05, 0x01,
0xdb, 0xa1, 0xd4, 0xb3, 0xb2, 0xa7, 0x7f, 0x41, 0xa7, 0x9b, 0x50, 0x92,
0x9b, 0x64, 0xd2, 0xe4, 0xd0, 0x02, 0xed, 0xba, 0x09, 0x91, 0x57, 0x00,
0xac, 0xc8, 0x4d, 0x67, 0x62, 0x67, 0xe1, 0x26, 0x47, 0x3a, 0x4d, 0x72,
0x78, 0x0e, 0xb6, 0xcf, 0x34, 0xb0, 0xbb, 0x90, 0x8e, 0xbf, 0x38, 0x66,
0xd5, 0xb9, 0xf5, 0xce, 0xc2, 0x1e, 0xd5, 0x1d, 0xd3, 0xa0, 0x7a, 0xa1,
0x61, 0x25, 0xe0, 0x16, 0x89, 0x63, 0x03, 0xfa, 0x9d, 0x63, 0x61, 0xfb,
0x2f, 0x5c, 0xdf, 0xed, 0x58, 0x0d, 0xa9, 0x96, 0x69, 0xaa, 0xe3, 0xe8,
0x2c, 0x16, 0x66, 0xc1, 0x2c, 0x56, 0xb5, 0x60, 0x60, 0x66, 0xef, 0xb4,
0x92, 0xa9, 0x5c, 0x29, 0xb6, 0x6c, 0x1f, 0xc6, 0x31, 0xb8, 0x25, 0x5a,
0xdf, 0xa9, 0x55, 0x6a, 0x1f, 0x6b, 0x9c, 0xce, 0xc1, 0x6d, 0x23, 0xde,
0x83, 0x4d, 0xed, 0xa4, 0x22, 0x78, 0x29, 0xe1, 0x5c, 0x57, 0xef, 0x83,
0x63, 0xab, 0x44, 0x1a, 0x26, 0xca, 0xee, 0x21, 0x46, 0x5c, 0x3b, 0x0c,
0x55, 0x84, 0x56, 0x5d, 0x32, 0xb2, 0x4c, 0xa0, 0xbb, 0x33, 0x7a, 0x5f,
0x20, 0x06, 0xb8, 0x3e, 0x26, 0x0e, 0x56, 0x45, 0x3f, 0x2d, 0xb0, 0xcf,
0x10, 0xd7, 0xbe, 0xca, 0x8b, 0x1d, 0x96, 0x99, 0xb3, 0xb5, 0x2d, 0xd5,
0x19, 0xac, 0xd1, 0x35, 0xbd, 0x7e, 0x60, 0x8e, 0xb2, 0xef, 0xba, 0x1c,
0x3c, 0x5a, 0x8d, 0x21, 0x05, 0x34, 0x58, 0xa1, 0x75, 0x13, 0x15, 0x92,
0x55, 0x2b, 0xbc, 0xfd, 0xed, 0xc9, 0xae, 0x72, 0xd8, 0x77, 0x59, 0x01,
0x5f, 0x3f, 0xb5, 0xd4, 0xa7, 0x5c, 0x99, 0xd3, 0x05, 0x63, 0x95, 0xee,
0x8a, 0x0e, 0xf0, 0x69, 0x75, 0x1f, 0x8f, 0x26, 0xd5, 0x2e, 0x24, 0x3f,
0x78, 0x6e, 0xd3, 0x22, 0xd1, 0xab, 0x94, 0x74, 0xb0, 0x6a, 0x88, 0x19,
0x48, 0x9b, 0x51, 0xe0, 0x08, 0x1a, 0x73, 0x90, 0xe4, 0x61, 0xe5, 0xaf,
0x6a, 0x04, 0xe3, 0x24, 0x18, 0x47, 0xe8, 0x0a, 0x69, 0x35, 0xd5, 0xe2,
0x6f, 0x23, 0x16, 0xb8, 0x40, 0xe8, 0x1e, 0x17, 0xad, 0xe7, 0xb6, 0xf5,
0x09, 0x6c, 0xfb, 0xba, 0x2d, 0x72, 0xdc, 0x80, 0x79, 0xdd, 0x54, 0xda,
0x36, 0x32, 0x48, 0xd3, 0x77, 0x89, 0x31, 0x88, 0x3f, 0x76, 0x7f, 0xbe,
0xb3, 0xcd, 0x29, 0xfd, 0x43, 0xa2, 0x91, 0xe1, 0xd5, 0x18, 0x2e, 0x82,
0xfd, 0xa2, 0x38, 0xb1, 0x2d, 0x99, 0x63, 0x5f, 0xdb, 0x65, 0x34, 0xfe,
0x97, 0x99, 0xfa, 0xa7, 0x2c, 0x9b, 0x29, 0x8f, 0x8d, 0xea, 0x1d, 0x4e,
0x1c, 0x96, 0x10, 0xf7, 0x8b, 0x3b, 0x5e, 0x30, 0x31, 0xde, 0x26, 0x56,
0xfd, 0x70, 0x6c, 0xf7, 0x13, 0x99, 0x79, 0x66, 0x60
};
const std::vector<std::uint8_t> decompressed_ref{{
0x48, 0x69, 0x74, 0x61, 0x67, 0x69, 0x20, 0x53, 0x65, 0x6e, 0x6a, 0x6f,
0x75, 0x67, 0x61, 0x68, 0x61, 0x72, 0x61, 0x20, 0x69, 0x73, 0x20, 0x72,
0x65, 0x67, 0x61, 0x72, 0x64, 0x65, 0x64, 0x0a, 0x61, 0x73, 0x20, 0x61,
0x20, 0x73, 0x6f, 0x2d, 0x63, 0x61, 0x6c, 0x6c, 0x65, 0x64, 0x20, 0x77,
0x65, 0x61, 0x6b, 0x20, 0x67, 0x69, 0x72, 0x6c, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x2e, 0x0a, 0x20,
0x0a, 0x41, 0x6c, 0x74, 0x68, 0x6f, 0x75, 0x67, 0x68, 0x20, 0x74, 0x68,
0x72, 0x6f, 0x75, 0x67, 0x68, 0x6f, 0x75, 0x74, 0x20, 0x68, 0x69, 0x67,
0x68, 0x20, 0x73, 0x63, 0x68, 0x6f, 0x6f, 0x6c, 0x20, 0x73, 0x68, 0x65,
0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20,
0x62, 0x65, 0x65, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x73, 0x61, 0x6d, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x61,
0x73, 0x20, 0x6d, 0x65, 0x2c, 0x0a, 0x66, 0x6f, 0x72, 0x20, 0x66, 0x69,
0x72, 0x73, 0x74, 0x20, 0x79, 0x65, 0x61, 0x72, 0x2c, 0x20, 0x73, 0x65,
0x63, 0x6f, 0x6e, 0x64, 0x20, 0x79, 0x65, 0x61, 0x72, 0x20, 0x61, 0x6e,
0x64, 0x20, 0x74, 0x68, 0x69, 0x72, 0x64, 0x20, 0x79, 0x65, 0x61, 0x72,
0x20, 0x2d, 0x20, 0x74, 0x68, 0x61, 0x74, 0x27, 0x73, 0x20, 0x74, 0x68,
0x69, 0x73, 0x20, 0x79, 0x65, 0x61, 0x72, 0x2c, 0x20, 0x49, 0x20, 0x68,
0x61, 0x76, 0x65, 0x20, 0x6e, 0x65, 0x76, 0x65, 0x72, 0x20, 0x6f, 0x6e,
0x63, 0x65, 0x20, 0x73, 0x65, 0x65, 0x6e, 0x0a, 0x68, 0x65, 0x72, 0x20,
0x64, 0x6f, 0x20, 0x61, 0x6e, 0x79, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x20,
0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x2e, 0x20, 0x53, 0x68, 0x65, 0x27,
0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x72, 0x6f, 0x6f,
0x6d, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69, 0x6e,
0x67, 0x0a, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x20, 0x62, 0x79, 0x20,
0x68, 0x65, 0x72, 0x73, 0x65, 0x6c, 0x66, 0x2e, 0x20, 0x53, 0x68, 0x65,
0x20, 0x68, 0x61, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x20,
0x73, 0x61, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x62,
0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63,
0x6c, 0x61, 0x73, 0x73, 0x72, 0x6f, 0x6f, 0x6d, 0x2c, 0x0a, 0x72, 0x65,
0x61, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x73, 0x20,
0x61, 0x6c, 0x6f, 0x6e, 0x65, 0x2e, 0x20, 0x53, 0x6f, 0x6d, 0x65, 0x74,
0x69, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x61,
0x20, 0x68, 0x61, 0x72, 0x64, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x6c, 0x6f, 0x6f, 0x6b, 0x73, 0x20, 0x64, 0x69,
0x66, 0x66, 0x69, 0x63, 0x75, 0x6c, 0x74, 0x2c, 0x0a, 0x6f, 0x74, 0x68,
0x65, 0x72, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x74, 0x20,
0x69, 0x73, 0x20, 0x61, 0x20, 0x63, 0x6f, 0x6d, 0x69, 0x63, 0x20, 0x62,
0x6f, 0x6f, 0x6b, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x63,
0x6f, 0x76, 0x65, 0x72, 0x20, 0x64, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20,
0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x0a, 0x74,
0x68, 0x61, 0x74, 0x20, 0x69, 0x74, 0x20, 0x77, 0x69, 0x6c, 0x6c, 0x20,
0x64, 0x65, 0x63, 0x72, 0x65, 0x61, 0x73, 0x65, 0x20, 0x79, 0x6f, 0x75,
0x72, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x20,
0x6a, 0x75, 0x73, 0x74, 0x20, 0x62, 0x79, 0x20, 0x72, 0x65, 0x61, 0x64,
0x69, 0x6e, 0x67, 0x20, 0x69, 0x74, 0x2e, 0x0a, 0x20, 0x0a, 0x53, 0x75,
0x69, 0x74, 0x61, 0x62, 0x6c, 0x79, 0x2c, 0x20, 0x73, 0x68, 0x65, 0x27,
0x73, 0x20, 0x73, 0x6d, 0x61, 0x72, 0x74, 0x20, 0x61, 0x6e, 0x64, 0x20,
0x69, 0x73, 0x20, 0x61, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x6f,
0x70, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61,
0x73, 0x73, 0x0a, 0x20, 0x0a, 0x59, 0x6f, 0x75, 0x27, 0x64, 0x20, 0x64,
0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x65, 0x6c, 0x79, 0x20, 0x66, 0x69,
0x6e, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20,
0x48, 0x69, 0x74, 0x61, 0x67, 0x69, 0x20, 0x53, 0x65, 0x6e, 0x6a, 0x6f,
0x75, 0x67, 0x61, 0x68, 0x61, 0x72, 0x61, 0x0a, 0x77, 0x69, 0x74, 0x68,
0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x6f, 0x70, 0x20, 0x31,
0x30, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x74,
0x68, 0x65, 0x20, 0x72, 0x61, 0x6e, 0x6b, 0x69, 0x6e, 0x67, 0x73, 0x0a,
0x70, 0x61, 0x73, 0x73, 0x65, 0x64, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x61,
0x66, 0x74, 0x65, 0x72, 0x20, 0x61, 0x6e, 0x20, 0x65, 0x78, 0x61, 0x6d,
0x2e, 0x0a, 0x20, 0x0a, 0x53, 0x68, 0x65, 0x20, 0x64, 0x6f, 0x65, 0x73,
0x6e, 0x27, 0x74, 0x20, 0x73, 0x65, 0x65, 0x6d, 0x20, 0x74, 0x6f, 0x20,
0x68, 0x61, 0x76, 0x65, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x66, 0x72, 0x69,
0x65, 0x6e, 0x64, 0x73, 0x2e, 0x0a, 0x4e, 0x6f, 0x74, 0x20, 0x65, 0x76,
0x65, 0x6e, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x70, 0x65, 0x72, 0x73, 0x6f,
0x6e, 0x2e, 0x0a, 0x20, 0x0a, 0x4f, 0x66, 0x20, 0x63, 0x6f, 0x75, 0x72,
0x73, 0x65, 0x2c, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6f,
0x74, 0x68, 0x65, 0x72, 0x20, 0x68, 0x61, 0x6e, 0x64, 0x2c, 0x20, 0x79,
0x6f, 0x75, 0x20, 0x63, 0x61, 0x6e, 0x27, 0x74, 0x20, 0x73, 0x61, 0x79,
0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x73, 0x68, 0x65, 0x27, 0x73, 0x20,
0x62, 0x65, 0x69, 0x6e, 0x67, 0x20, 0x62, 0x75, 0x6c, 0x6c, 0x69, 0x65,
0x64, 0x2e, 0x0a, 0x53, 0x65, 0x6e, 0x6a, 0x6f, 0x75, 0x67, 0x61, 0x68,
0x61, 0x72, 0x61, 0x20, 0x69, 0x73, 0x20, 0x61, 0x6c, 0x77, 0x61, 0x79,
0x73, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x66, 0x61,
0x63, 0x65, 0x20, 0x6c, 0x69, 0x6b, 0x65, 0x20, 0x69, 0x74, 0x27, 0x73,
0x20, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x61, 0x6c, 0x2c, 0x20, 0x74, 0x68,
0x65, 0x72, 0x65, 0x2c, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x62, 0x61, 0x63, 0x6b, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20,
0x63, 0x6c, 0x61, 0x73, 0x73, 0x2c, 0x20, 0x72, 0x65, 0x61, 0x64, 0x69,
0x6e, 0x67, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x6b, 0x2e, 0x0a, 0x53,
0x68, 0x65, 0x20, 0x77, 0x61, 0x73, 0x20, 0x62, 0x75, 0x69, 0x6c, 0x64,
0x69, 0x6e, 0x67, 0x20, 0x61, 0x20, 0x77, 0x61, 0x6c, 0x6c, 0x20, 0x61,
0x72, 0x6f, 0x75, 0x6e, 0x64, 0x20, 0x68, 0x65, 0x72, 0x73, 0x65, 0x6c,
0x66, 0x2e, 0x0a,
}};
std::optional<std::vector<std::uint8_t>> decompressed = zlib.inflate(compressed, 525);
REQUIRE(zlib.valid());
REQUIRE(decompressed);
REQUIRE(decompressed->size() == 1023);
REQUIRE(*decompressed == decompressed_ref);
}
TEST_CASE( "inflate failure", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
constexpr std::array<std::uint8_t, 25> garbage{{
0x7c, 0x12, 0xdd, 0x76, 0xfe, 0xe7, 0x50, 0x10,
0x3e, 0x2e, 0x70, 0xb4, 0xfd, 0x4f, 0x54, 0xe0,
0x70, 0x00, 0x32, 0xa5, 0x22, 0x75, 0xcf, 0xa3,
0xfa
}};
std::optional<std::vector<std::uint8_t>> decompressed = zlib.inflate(garbage);
REQUIRE(!decompressed);
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate - type", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
SECTION( "small type" ) {
const std::vector<std::uint8_t> compressed_ref{{
0x78, 0x9c, 0x5b, 0x05, 0x00, 0x00, 0xab, 0x00,
0xab
}};
const uint8_t smol = 0xAA;
auto compressed = zlib.deflate(smol);
REQUIRE(zlib.valid());
REQUIRE(compressed);
REQUIRE(*compressed == compressed_ref);
}
// REQUIRE(zlib.valid());
// SECTION( "medium type" ) {
// constexpr std::array<std::uint8_t, 17> compressed{{
// 0x78, 0x9c, 0x63, 0x10, 0x54, 0x32, 0x76, 0x09,
// 0x4d, 0x2b, 0xef, 0x00, 0x00, 0x08, 0x01, 0x02,
// 0x65
// }};
// auto med = zlib.inflate<med_t>(compressed);
// REQUIRE(zlib.valid());
// REQUIRE(med);
// REQUIRE(med->foo == 0x7766554433221100);
// REQUIRE(med->bar == 0x88);
// }
// REQUIRE(zlib.valid());
// SECTION( "chonky type" ) {
// constexpr std::array<std::uint8_t, 20> compressed{{
// 0x78, 0x9c, 0x2b, 0x4f, 0x0b, 0x75, 0x31, 0x56,
// 0x12, 0x64, 0x58, 0xb5, 0x74, 0x84, 0x03, 0x00,
// 0x6c, 0x32, 0xa7, 0x87
// }};
// constexpr std::array<std::uint32_t, 64> baz{{
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5,
// 0xa5a5a5a5, 0xa5a5a5a5, 0xa5a5a5a5, 0x000000a5
// }};
// auto chonk = zlib.inflate<chonky_t>(compressed);
// REQUIRE(zlib.valid());
// REQUIRE(chonk);
// REQUIRE(chonk->foo == 0x0011223344556677);
// REQUIRE(chonk->bar == 0xAA);
// REQUIRE(chonk->baz == baz);
// }
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate - type array", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate - type vector", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate - raw array", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate - raw vector", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate failure", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "deflate then inflate", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
TEST_CASE( "inflate then deflate", "[zlib]" ) {
zlib_t zlib{};
REQUIRE(zlib.valid());
}
| 46.695067 | 87 | 0.656919 | [
"vector"
] |
e68cda5a98102da7f9c4352564c4e057dd5f24a4 | 4,753 | hpp | C++ | src/include/strie/louds.hpp | MatsuTaku/succinct-tries | 58cf61bd05b78aadaee478a78f0dcf4e558a50c1 | [
"MIT"
] | null | null | null | src/include/strie/louds.hpp | MatsuTaku/succinct-tries | 58cf61bd05b78aadaee478a78f0dcf4e558a50c1 | [
"MIT"
] | null | null | null | src/include/strie/louds.hpp | MatsuTaku/succinct-tries | 58cf61bd05b78aadaee478a78f0dcf4e558a50c1 | [
"MIT"
] | null | null | null | #ifndef SUCCINCT_TRIES__LOUDS_HPP_
#define SUCCINCT_TRIES__LOUDS_HPP_
#include <string>
#include <cstring>
#include <string_view>
#include <iterator>
#include <type_traits>
#include <cassert>
#include <exception>
#include <vector>
#include <queue>
#include <tuple>
#include <initializer_list>
#include <iostream>
#include <sdsl/int_vector.hpp>
#include <sdsl/rank_support.hpp>
#include <sdsl/select_support.hpp>
#include <sdsl/util.hpp>
namespace strie {
class Louds {
public:
using value_type = std::string;
using char_type = char;
static constexpr char_type kEndLabel = '\0';
static constexpr char_type kDelim = '\0';
static constexpr char_type kRootLabel = '^'; // for visualization
using index_type = size_t;
private:
sdsl::bit_vector bv_;
sdsl::rank_support_v<1, 1> rank1_;
sdsl::select_support_mcl<0, 1> select0_;
sdsl::bit_vector leaf_;
sdsl::rank_support_v<1, 1> rank_leaf_;
std::vector<char_type> chars_;
size_t size_;
private:
template<typename It>
void _build(It begin, It end);
template<typename It>
void _check_valid_input(It begin, It end) const {
// Check input be sorted.
if (begin == end)
return;
for (auto pre = begin, it = std::next(begin); it != end; ++pre, ++it)
if (not (*pre < *it))
throw std::domain_error("Input string collection is not sorted.");
}
index_type _rank0(index_type i) const {
return i - rank1_(i);
}
index_type _child(index_type i) const {
return select0_(rank1_(i) + 1);
}
public:
Louds() : size_(0) {}
template<typename It>
Louds(It begin, It end) : Louds() {
_build(begin, end);
}
Louds(std::initializer_list<value_type> list) : Louds(list.begin(), list.end()) {}
size_t size() const { return size_; }
bool empty() const { return size() == 0; }
template<typename STR>
bool contains(STR&& key, index_type len) const;
bool contains(const std::string& key) const { return contains(key, key.length()); }
bool contains(std::string_view key) const { return contains(key, key.length()); }
bool contains(const char* key) const { return contains(key, std::strlen(key)); }
public:
void print_for_debug() const {
for (int i = 0; i < bv_.size(); i++)
std::cout << bv_[i];
std::cout << std::endl;
// std::cout << "rank0" << std::endl;
// for (int i = 0; i < bv_.size(); i++)
// std::cout << rank0_(i);
// std::cout << std::endl;
// std::cout << "rank1" << std::endl;
// for (int i = 0; i < bv_.size(); i++)
// std::cout << rank1_(i);
// std::cout << std::endl;
// std::cout << "child" << std::endl;
// for (int i = 0; i < bv_.size(); i++) if (bv_[i] == 1)
// std::cout << _child(i) << ' ';
// std::cout << std::endl;
for (int i = 0; i < chars_.size(); i++)
std::cout << chars_[i];
std::cout << std::endl;
for (int i = 0; i < leaf_.size(); i++)
std::cout << leaf_[i];
std::cout << std::endl;
}
};
template<typename It>
void Louds::_build(It begin, It end) {
using traits = std::iterator_traits<It>;
static_assert(std::is_convertible_v<typename traits::value_type, value_type>);
static_assert(std::is_base_of_v<std::forward_iterator_tag, typename traits::iterator_category>);
_check_valid_input(begin, end);
bv_.resize(1);
bv_[0] = 1;
chars_.resize(1);
chars_[0] = kRootLabel;
std::queue<std::tuple<It, It, size_t>> qs;
qs.emplace(begin, end, 0);
std::vector<char_type> cs;
while (!qs.empty()) {
auto [b,e,d] = qs.front(); qs.pop();
assert(b != e);
cs.clear();
bool has_leaf = false;
auto it = b;
if ((*b).size() == d) {
has_leaf = true;
++it;
}
while (it != e) {
auto f = it++;
assert(f->length() > d);
auto c = (*f)[d];
cs.push_back(c);
while (it != e and (*it)[d] == c)
++it;
qs.emplace(f, it, d+1);
}
size_t t = bv_.size();
bv_.resize(t + 1 + cs.size());
bv_[t] = 0;
chars_.resize(t + 1 + cs.size());
chars_[t] = kDelim;
for (int i = 0; i < cs.size(); i++) {
bv_[t + 1 + i] = 1;
chars_[t + 1 + i] = cs[i];
}
leaf_.resize(leaf_.size()+1);
leaf_[leaf_.size()-1] = has_leaf;
}
sdsl::util::init_support(rank1_, &bv_);
sdsl::util::init_support(select0_, &bv_);
sdsl::util::init_support(rank_leaf_, &leaf_);
size_ = rank_leaf_(leaf_.size());
}
template<typename STR>
bool Louds::contains(STR&& key, index_type len) const {
index_type i, idx = 1;
for (i = 0; i < len; i++) {
idx++;
char_type c;
while ((c = chars_[idx]) != kDelim and c < key[i])
++idx;
if (c != key[i])
return false;
idx = _child(idx);
}
return leaf_[_rank0(idx)];
}
} // namespace strie
#endif //SUCCINCT_TRIES__LOUDS_HPP_
| 26.853107 | 98 | 0.601515 | [
"vector"
] |
e68e974b36fd03a4fe88f0db4e16a2f55ea14907 | 1,064 | cpp | C++ | samples/plot-function.cpp | franko/elementary-plotlib | d11b56a13893781d84a8e93183f01b13140dd4e3 | [
"MIT"
] | 14 | 2020-04-03T02:14:08.000Z | 2021-07-16T21:05:56.000Z | samples/plot-function.cpp | franko/elementary-plotlib | d11b56a13893781d84a8e93183f01b13140dd4e3 | [
"MIT"
] | 2 | 2020-04-22T15:40:42.000Z | 2020-04-28T21:17:23.000Z | samples/plot-function.cpp | franko/libcanvas | d11b56a13893781d84a8e93183f01b13140dd4e3 | [
"MIT"
] | 1 | 2020-04-30T07:49:02.000Z | 2020-04-30T07:49:02.000Z | #include <cmath>
#include "elem/elem.h"
using namespace elem;
int main() {
// The function FxLine generate a Path object based on a
// mathematical function (x) -> f(x).
Path sin_line = FxLine(0.0001, 8 * math::Tau(), [](double x) { return std::sin(x) / x; });
// Declare a plot object.
Plot plot;
// Add the line just created with a blue color and 1.5 pixel
// line's width.
plot.AddStroke(sin_line, color::Blue, 1.5);
// Set Plot titles.
plot.SetTitle("Function plot example");
plot.SetXAxisTitle("x variable");
plot.SetYAxisTitle("y variable");
// Show the plot on the screen.
plot.Show(640, 480, WindowResize);
// Add one more line corresponding to a different function.
// Note that objects can be added after the plot is already
// shown on the screen.
Path cos_line = FxLine(0.8, 8 * math::Tau(), [](double x) { return std::cos(x) / x; });
plot.AddStroke(cos_line, color::Red, 1.5);
// Wait until the window showing the plot is closed.
plot.Wait();
return 0;
}
| 29.555556 | 94 | 0.632519 | [
"object"
] |
e6971e27d57c57f34f88dfa1fdf0fb69d6f850f9 | 1,281 | cpp | C++ | Week4/PriorityQueue/TestPriorityQueue.cpp | AvansTi/TMTI-DATC-Voorbeelden | 572d009ad9378228d125e4025bc0f9aa7763d053 | [
"BSD-3-Clause"
] | 2 | 2019-04-26T07:13:05.000Z | 2020-04-24T09:47:20.000Z | Week4/PriorityQueue/TestPriorityQueue.cpp | AvansTi/TMTI-DATC-Voorbeelden | 572d009ad9378228d125e4025bc0f9aa7763d053 | [
"BSD-3-Clause"
] | null | null | null | Week4/PriorityQueue/TestPriorityQueue.cpp | AvansTi/TMTI-DATC-Voorbeelden | 572d009ad9378228d125e4025bc0f9aa7763d053 | [
"BSD-3-Clause"
] | 1 | 2020-05-08T12:19:30.000Z | 2020-05-08T12:19:30.000Z | #include <iostream>
#include <functional>
#include <string>
#include <queue>
#include <deque>
#include <vector>
using namespace std;
template<typename T>
void printQueue(T& pQueue) {
while (!pQueue.empty()) {
cout << pQueue.top() << " ";
pQueue.pop();
}
}
int main() {
auto cmp = [](const int lhs, const int rhs) {
return (lhs % 3) > (rhs % 3);
};
priority_queue<int> queue1;
priority_queue<int, vector<int>, greater<>> queue2;
priority_queue<int, vector<int>, decltype(cmp)> queue3(cmp);
for (auto v : { 7,4,9,2,1 }) {
queue1.push(v);
queue2.push(v);
queue3.push(v);
}
cout << "Contents in queue1: ";
printQueue(queue1);
cout << "\nContents in queue2: ";
printQueue(queue2);
cout << "\nContents in queue3: ";
printQueue(queue3);
return 0;
}
/*
int main() {
std::priority_queue<std::pair<int, std::string> > pq;
pq.push(std::make_pair(3, "Start visual studio"));
pq.push(std::make_pair(4, "plug laptop in"));
pq.push(std::make_pair(5, "Haal koffie"));
pq.push(std::make_pair(1, "Test, test en ... debug"));
pq.push(std::make_pair(2, "Start coding..."));
while (!pq.empty()) {
std::pair<int, std::string> top = pq.top();
std::cout << top.first << ", " << top.second << std::endl;
pq.pop();
}
std::cin.get();
return 0;
}
*/ | 19.119403 | 61 | 0.618267 | [
"vector"
] |
e6a157d42580ffc2aa33106f9241197902097e94 | 3,196 | cpp | C++ | samples/softrender/MipMap.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 6 | 2019-01-25T08:41:14.000Z | 2021-08-22T07:06:11.000Z | samples/softrender/MipMap.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | null | null | null | samples/softrender/MipMap.cpp | kunka/SoftRender | 8089844e9ab00ab71ef1a820641ec07ae8df248d | [
"MIT"
] | 3 | 2019-01-25T08:41:16.000Z | 2020-09-04T06:04:29.000Z | //
// Created by huangkun on 2018/8/19.
//
#include "MipMap.h"
#include "Input.h"
TEST_NODE_IMP_BEGIN
MipMap::MipMap() {
TEX_WIDTH = 1024;
TEX_HEIGHT = 1024;
}
bool MipMap::init() {
SoftRender::init();
verticesPlane = {
// postions // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // bottom top
};
indicesPlane = { // note that we start from 0!
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
Mesh *mesh = new Mesh(createVertexs(verticesPlane, 3, 0, 2), indicesPlane);
planeMeshes.push_back(mesh);
texture2D.load("../res/wood.png");
texture2D.setWrap(GL_CLAMP_TO_EDGE);
texture2D.setMinFilter(GL_NEAREST_MIPMAP_NEAREST);
texture2D.genMipmaps();
texture2DNoMM.load("../res/wood.png");
texture2DNoMM.setWrap(GL_CLAMP_TO_EDGE);
texture2DNoMM.setMinFilter(GL_NEAREST);
return true;
}
void MipMap::draw(const mat4 &transform) {
clearColor(25, 50, 75, 255);
vec3 target = cameraPos + cameraDir;
viewMatrix = Matrix::lookAt(Vector(cameraPos.x, cameraPos.y, cameraPos.z), Vector(target.x, target.y, target.z),
Vector(cameraUp.x, cameraUp.y, cameraUp.z));
if (Input::getInstance()->isKeyPressed(GLFW_KEY_SPACE)) {
bindTextures({&texture2DNoMM});
} else {
bindTextures({&texture2D});
}
// modelMatrix.setIdentity();
// viewMatrix.setIdentity();
// projectMatrix.setIdentity();
std::vector<vec3> ps = {
vec3(-1, -1, 1.5),
vec3(-3, 3.5, -5),
vec3(3, 3, -5),
vec3(0, 0, -10),
vec3(-10, 1, -15),
vec3(5, 2, -15),
vec3(8, -2, -12),
vec3(3, -4, -8),
};
for (int i = 0; i < ps.size(); i++) {
modelMatrix.setIdentity();
// modelMatrix.scale(Vector(1.9, 1.9, 1));
modelMatrix.translate(ps[i]);
Matrix m = modelMatrix;
m.mult(viewMatrix);
m.mult(projectMatrix);
for (unsigned int i = 0; i < planeMeshes.size(); i++)
drawMesh(*planeMeshes[i], m, 2);
}
SoftRender::draw(transform);
}
void MipMap::setPixel(int x, int y, float z, float u, float v, vec3 varying[],
const std::vector<vec3> &uniforms, float dudx, float dvdy) {
Texture2D *texture = _bindTextures["texture0"];
if (texture) {
const vec3 &textureColor = texture->sample(u, v, dudx, dvdy);
vec4 color = vec4(vec3(textureColor), 255);
SoftRender::setPixel(x, y, z, color);
}
}
MipMap::~MipMap() {
for (unsigned int i = 0; i < planeMeshes.size(); i++)
delete planeMeshes[i];
}
TEST_NODE_IMP_END | 32.612245 | 120 | 0.508135 | [
"mesh",
"vector",
"transform"
] |
e6a250a3943ea40bf2f5ee140b197ad076214968 | 2,953 | hpp | C++ | source/globals.hpp | Vortetty/GBATextLib | d2643169c64e645076f6c97a2948a830ffd69eb4 | [
"Apache-2.0"
] | null | null | null | source/globals.hpp | Vortetty/GBATextLib | d2643169c64e645076f6c97a2948a830ffd69eb4 | [
"Apache-2.0"
] | null | null | null | source/globals.hpp | Vortetty/GBATextLib | d2643169c64e645076f6c97a2948a830ffd69eb4 | [
"Apache-2.0"
] | null | null | null | #ifndef globals
#define globals
#include <math.h>
#include <climits>
#include <cstring>
#include <initializer_list>
#define color uint16_t
#define colorSet std::vector<color>
unsigned short* videoBuffer = (unsigned short*)0x06000000;
struct Vector2 {
int_fast32_t x;
int_fast32_t y;
};
int Vec2Int(Vector2 vec2, int_fast32_t width){ // 2D position to 1d index
return vec2.x + vec2.y * width;
}
uint_fast32_t Vec2Int(int_fast32_t x, int_fast32_t y, int_fast32_t width){ // 2D position to 1d index
return x + y * width;
}
Vector2 int2Vec(int_fast32_t idx, int_fast32_t width){ // 1D index to 2D position
return {
idx % width,
idx / width
};
}
unsigned short randint(unsigned short a, unsigned short b){ // Random integer
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return (unsigned short)(a + r);
}
unsigned short RGBToColor(unsigned short r, unsigned short g, unsigned short b){ // RGB to gba color
return b/8*1024 + g/8*32 + r/8;
}
unsigned short RGBToColor(int rgb){ // hex to gba color
unsigned short r = (rgb >> 16) & 0xff;
unsigned short g = (rgb >> 8) & 0xff;
unsigned short b = rgb & 0xff;
return b/8*1024 + g/8*32 + r/8;
}
void drawNxN(unsigned short xoffset, unsigned short yoffset, unsigned short width, unsigned short height, unsigned short color){ // Draw a rectangle at position, position is top left corner
for (unsigned short x = 0; x < width; x++){
for (unsigned short y = 0; y < height; y++){
videoBuffer[(xoffset+x)+(yoffset+y)*240] = color;
}
}
}
void setPixel(unsigned short x, unsigned short y, unsigned short color){ // Set a single pixel
videoBuffer[x+y*240] = color;
}
bool isPressed(unsigned short keys, unsigned short key){ // Check if a key is pressed given a uint16_t containing pressed keys, meant to be used with mgba
return (keys & key) == key;
}
bool inRange(int low, int high, int x) // https://www.geeksforgeeks.org/how-to-check-whether-a-number-is-in-the-rangea-b-using-one-comparison/
{
return (low <= x) && (x <= high);
}
int wrapInt(int x, int x_min, int x_max){ // wrap integer around to stay in range, https://stackoverflow.com/a/14416133
return (((x - x_min) % (x_max - x_min)) + (x_max - x_min)) % (x_max - x_min) + x_min;
}
void sleep(uint_fast32_t ms){ // Sleep but in a hacky way since no sleep command exists
for (int i = 0; i < ms; i++){
uint_fast64_t goal = 16800;
uint_fast64_t counter = 0;
while (counter < goal){
counter += 22;
asm("");
}
}
}
#endif | 34.337209 | 193 | 0.586861 | [
"vector"
] |
e6a29ec255730c45eb1ccf6f0cb75ac037765e1b | 8,011 | cpp | C++ | B2G/gecko/content/svg/content/src/SVGAnimatedLengthList.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/content/svg/content/src/SVGAnimatedLengthList.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/content/svg/content/src/SVGAnimatedLengthList.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "SVGAnimatedLengthList.h"
#include "DOMSVGAnimatedLengthList.h"
#include "nsSVGElement.h"
#include "nsSVGAttrTearoffTable.h"
#include "nsSMILValue.h"
#include "SVGLengthListSMILType.h"
namespace mozilla {
nsresult
SVGAnimatedLengthList::SetBaseValueString(const nsAString& aValue)
{
SVGLengthList newBaseValue;
nsresult rv = newBaseValue.SetValueFromString(aValue);
if (NS_FAILED(rv)) {
return rv;
}
DOMSVGAnimatedLengthList *domWrapper =
DOMSVGAnimatedLengthList::GetDOMWrapperIfExists(this);
if (domWrapper) {
// We must send this notification *before* changing mBaseVal! If the length
// of our baseVal is being reduced, our baseVal's DOM wrapper list may have
// to remove DOM items from itself, and any removed DOM items need to copy
// their internal counterpart values *before* we change them.
//
domWrapper->InternalBaseValListWillChangeTo(newBaseValue);
}
// We don't need to call DidChange* here - we're only called by
// nsSVGElement::ParseAttribute under nsGenericElement::SetAttr,
// which takes care of notifying.
rv = mBaseVal.CopyFrom(newBaseValue);
if (NS_FAILED(rv) && domWrapper) {
// Attempting to increase mBaseVal's length failed - reduce domWrapper
// back to the same length:
domWrapper->InternalBaseValListWillChangeTo(mBaseVal);
}
return rv;
}
void
SVGAnimatedLengthList::ClearBaseValue(uint32_t aAttrEnum)
{
DOMSVGAnimatedLengthList *domWrapper =
DOMSVGAnimatedLengthList::GetDOMWrapperIfExists(this);
if (domWrapper) {
// We must send this notification *before* changing mBaseVal! (See above.)
domWrapper->InternalBaseValListWillChangeTo(SVGLengthList());
}
mBaseVal.Clear();
// Caller notifies
}
nsresult
SVGAnimatedLengthList::SetAnimValue(const SVGLengthList& aNewAnimValue,
nsSVGElement *aElement,
uint32_t aAttrEnum)
{
DOMSVGAnimatedLengthList *domWrapper =
DOMSVGAnimatedLengthList::GetDOMWrapperIfExists(this);
if (domWrapper) {
// A new animation may totally change the number of items in the animVal
// list, replacing what was essentially a mirror of the baseVal list, or
// else replacing and overriding an existing animation. When this happens
// we must try and keep our animVal's DOM wrapper in sync (see the comment
// in DOMSVGAnimatedLengthList::InternalBaseValListWillChangeTo).
//
// It's not possible for us to reliably distinguish between calls to this
// method that are setting a new sample for an existing animation, and
// calls that are setting the first sample of an animation that will
// override an existing animation. Happily it's cheap to just blindly
// notify our animVal's DOM wrapper of its internal counterpart's new value
// each time this method is called, so that's what we do.
//
// Note that we must send this notification *before* setting or changing
// mAnimVal! (See the comment in SetBaseValueString above.)
//
domWrapper->InternalAnimValListWillChangeTo(aNewAnimValue);
}
if (!mAnimVal) {
mAnimVal = new SVGLengthList();
}
nsresult rv = mAnimVal->CopyFrom(aNewAnimValue);
if (NS_FAILED(rv)) {
// OOM. We clear the animation, and, importantly, ClearAnimValue() ensures
// that mAnimVal and its DOM wrapper (if any) will have the same length!
ClearAnimValue(aElement, aAttrEnum);
return rv;
}
aElement->DidAnimateLengthList(aAttrEnum);
return NS_OK;
}
void
SVGAnimatedLengthList::ClearAnimValue(nsSVGElement *aElement,
uint32_t aAttrEnum)
{
DOMSVGAnimatedLengthList *domWrapper =
DOMSVGAnimatedLengthList::GetDOMWrapperIfExists(this);
if (domWrapper) {
// When all animation ends, animVal simply mirrors baseVal, which may have
// a different number of items to the last active animated value. We must
// keep the length of our animVal's DOM wrapper list in sync, and again we
// must do that before touching mAnimVal. See comments above.
//
domWrapper->InternalAnimValListWillChangeTo(mBaseVal);
}
mAnimVal = nullptr;
aElement->DidAnimateLengthList(aAttrEnum);
}
nsISMILAttr*
SVGAnimatedLengthList::ToSMILAttr(nsSVGElement *aSVGElement,
uint8_t aAttrEnum,
uint8_t aAxis,
bool aCanZeroPadList)
{
return new SMILAnimatedLengthList(this, aSVGElement, aAttrEnum, aAxis, aCanZeroPadList);
}
nsresult
SVGAnimatedLengthList::
SMILAnimatedLengthList::ValueFromString(const nsAString& aStr,
const nsISMILAnimationElement* /*aSrcElement*/,
nsSMILValue& aValue,
bool& aPreventCachingOfSandwich) const
{
nsSMILValue val(&SVGLengthListSMILType::sSingleton);
SVGLengthListAndInfo *llai = static_cast<SVGLengthListAndInfo*>(val.mU.mPtr);
nsresult rv = llai->SetValueFromString(aStr);
if (NS_SUCCEEDED(rv)) {
llai->SetInfo(mElement, mAxis, mCanZeroPadList);
aValue.Swap(val);
// If any of the lengths in the list depend on their context, then we must
// prevent caching of the entire animation sandwich. This is because the
// units of a length at a given index can change from sandwich layer to
// layer, and indeed even be different within a single sandwich layer. If
// any length in the result of an animation sandwich is the result of the
// addition of lengths where one or more of those lengths is context
// dependent, then naturally the resultant length is also context
// dependent, regardless of whether its actual unit is context dependent or
// not. Unfortunately normal invalidation mechanisms won't cause us to
// recalculate the result of the sandwich if the context changes, so we
// take the (substantial) performance hit of preventing caching of the
// sandwich layer, causing the animation sandwich to be recalculated every
// single sample.
aPreventCachingOfSandwich = false;
for (uint32_t i = 0; i < llai->Length(); ++i) {
uint8_t unit = (*llai)[i].GetUnit();
if (unit == nsIDOMSVGLength::SVG_LENGTHTYPE_PERCENTAGE ||
unit == nsIDOMSVGLength::SVG_LENGTHTYPE_EMS ||
unit == nsIDOMSVGLength::SVG_LENGTHTYPE_EXS) {
aPreventCachingOfSandwich = true;
break;
}
}
}
return rv;
}
nsSMILValue
SVGAnimatedLengthList::SMILAnimatedLengthList::GetBaseValue() const
{
// To benefit from Return Value Optimization and avoid copy constructor calls
// due to our use of return-by-value, we must return the exact same object
// from ALL return points. This function must only return THIS variable:
nsSMILValue val;
nsSMILValue tmp(&SVGLengthListSMILType::sSingleton);
SVGLengthListAndInfo *llai = static_cast<SVGLengthListAndInfo*>(tmp.mU.mPtr);
nsresult rv = llai->CopyFrom(mVal->mBaseVal);
if (NS_SUCCEEDED(rv)) {
llai->SetInfo(mElement, mAxis, mCanZeroPadList);
val.Swap(tmp);
}
return val;
}
nsresult
SVGAnimatedLengthList::SMILAnimatedLengthList::SetAnimValue(const nsSMILValue& aValue)
{
NS_ASSERTION(aValue.mType == &SVGLengthListSMILType::sSingleton,
"Unexpected type to assign animated value");
if (aValue.mType == &SVGLengthListSMILType::sSingleton) {
mVal->SetAnimValue(*static_cast<SVGLengthListAndInfo*>(aValue.mU.mPtr),
mElement,
mAttrEnum);
}
return NS_OK;
}
void
SVGAnimatedLengthList::SMILAnimatedLengthList::ClearAnimValue()
{
if (mVal->mAnimVal) {
mVal->ClearAnimValue(mElement, mAttrEnum);
}
}
} // namespace mozilla
| 38.147619 | 90 | 0.705655 | [
"object"
] |
e6a9023bb77e191f4771ea8e5e76e4bb4fe13d62 | 586 | cpp | C++ | Arrays/Simulation array/Anti Diagonals.cpp | cenation092/InterviewBit-Solutions | ac4510a10d965fb681f7b3c80990407e18bc2668 | [
"MIT"
] | 7 | 2019-06-29T08:57:07.000Z | 2021-02-13T06:43:40.000Z | Arrays/Simulation array/Anti Diagonals.cpp | cenation092/InterviewBit-Solutions | ac4510a10d965fb681f7b3c80990407e18bc2668 | [
"MIT"
] | null | null | null | Arrays/Simulation array/Anti Diagonals.cpp | cenation092/InterviewBit-Solutions | ac4510a10d965fb681f7b3c80990407e18bc2668 | [
"MIT"
] | 3 | 2020-06-17T04:26:26.000Z | 2021-02-12T04:51:40.000Z | vector<vector<int> > Solution::diagonal(vector<vector<int> > &A) {
int n = A.size() + A.size()-1;
vector<vector<int> > v(n);
for( int i = 0; i < A.size(); i++ ){
int x = 0, y = i;
while( x >= 0 && y >= 0 && x < A.size() && y < A.size()){
v[i].push_back(A[x][y]);
x++, y--;
}
}
for( int i = 1; i < A.size(); i++ ){
int x = i, y = A.size()-1;
while( x >= 0 && y >= 0 && x < A.size() && y < A.size() ){
v[A.size()+i-1].push_back(A[x][y]);
x++, y--;
}
}
return v;
}
| 29.3 | 66 | 0.366894 | [
"vector"
] |
e6b17a2f1247f62e1cac238632586d7ee0d31ced | 654 | cpp | C++ | engine/modules/physx/editor/physx_controller_capsule_editor.cpp | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | engine/modules/physx/editor/physx_controller_capsule_editor.cpp | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | engine/modules/physx/editor/physx_controller_capsule_editor.cpp | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | #include "physx_controller_capsule_editor.h"
#include "engine/core/editor/editor.h"
#include "engine/core/math/Curve.h"
#include "engine/core/main/Engine.h"
namespace Echo
{
#ifdef ECHO_EDITOR_MODE
PhysxControllerCapsuleEditor::PhysxControllerCapsuleEditor(Object* object)
: ObjectEditor(object)
{
}
PhysxControllerCapsuleEditor::~PhysxControllerCapsuleEditor()
{
}
ImagePtr PhysxControllerCapsuleEditor::getThumbnail() const
{
return Image::loadFromFile(Engine::instance()->getRootPath() + "engine/modules/physx/editor/icon/physx_controller_capsule.png");
}
void PhysxControllerCapsuleEditor::onEditorSelectThisNode()
{
}
#endif
}
| 21.8 | 130 | 0.787462 | [
"object"
] |
e6b3265f29e682ce175debaf13dff6e79e8fad21 | 4,579 | cpp | C++ | aws-cpp-sdk-backup/source/model/BackupPlansListMember.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-backup/source/model/BackupPlansListMember.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-backup/source/model/BackupPlansListMember.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/backup/model/BackupPlansListMember.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Backup
{
namespace Model
{
BackupPlansListMember::BackupPlansListMember() :
m_backupPlanArnHasBeenSet(false),
m_backupPlanIdHasBeenSet(false),
m_creationDateHasBeenSet(false),
m_deletionDateHasBeenSet(false),
m_versionIdHasBeenSet(false),
m_backupPlanNameHasBeenSet(false),
m_creatorRequestIdHasBeenSet(false),
m_lastExecutionDateHasBeenSet(false),
m_advancedBackupSettingsHasBeenSet(false)
{
}
BackupPlansListMember::BackupPlansListMember(JsonView jsonValue) :
m_backupPlanArnHasBeenSet(false),
m_backupPlanIdHasBeenSet(false),
m_creationDateHasBeenSet(false),
m_deletionDateHasBeenSet(false),
m_versionIdHasBeenSet(false),
m_backupPlanNameHasBeenSet(false),
m_creatorRequestIdHasBeenSet(false),
m_lastExecutionDateHasBeenSet(false),
m_advancedBackupSettingsHasBeenSet(false)
{
*this = jsonValue;
}
BackupPlansListMember& BackupPlansListMember::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("BackupPlanArn"))
{
m_backupPlanArn = jsonValue.GetString("BackupPlanArn");
m_backupPlanArnHasBeenSet = true;
}
if(jsonValue.ValueExists("BackupPlanId"))
{
m_backupPlanId = jsonValue.GetString("BackupPlanId");
m_backupPlanIdHasBeenSet = true;
}
if(jsonValue.ValueExists("CreationDate"))
{
m_creationDate = jsonValue.GetDouble("CreationDate");
m_creationDateHasBeenSet = true;
}
if(jsonValue.ValueExists("DeletionDate"))
{
m_deletionDate = jsonValue.GetDouble("DeletionDate");
m_deletionDateHasBeenSet = true;
}
if(jsonValue.ValueExists("VersionId"))
{
m_versionId = jsonValue.GetString("VersionId");
m_versionIdHasBeenSet = true;
}
if(jsonValue.ValueExists("BackupPlanName"))
{
m_backupPlanName = jsonValue.GetString("BackupPlanName");
m_backupPlanNameHasBeenSet = true;
}
if(jsonValue.ValueExists("CreatorRequestId"))
{
m_creatorRequestId = jsonValue.GetString("CreatorRequestId");
m_creatorRequestIdHasBeenSet = true;
}
if(jsonValue.ValueExists("LastExecutionDate"))
{
m_lastExecutionDate = jsonValue.GetDouble("LastExecutionDate");
m_lastExecutionDateHasBeenSet = true;
}
if(jsonValue.ValueExists("AdvancedBackupSettings"))
{
Array<JsonView> advancedBackupSettingsJsonList = jsonValue.GetArray("AdvancedBackupSettings");
for(unsigned advancedBackupSettingsIndex = 0; advancedBackupSettingsIndex < advancedBackupSettingsJsonList.GetLength(); ++advancedBackupSettingsIndex)
{
m_advancedBackupSettings.push_back(advancedBackupSettingsJsonList[advancedBackupSettingsIndex].AsObject());
}
m_advancedBackupSettingsHasBeenSet = true;
}
return *this;
}
JsonValue BackupPlansListMember::Jsonize() const
{
JsonValue payload;
if(m_backupPlanArnHasBeenSet)
{
payload.WithString("BackupPlanArn", m_backupPlanArn);
}
if(m_backupPlanIdHasBeenSet)
{
payload.WithString("BackupPlanId", m_backupPlanId);
}
if(m_creationDateHasBeenSet)
{
payload.WithDouble("CreationDate", m_creationDate.SecondsWithMSPrecision());
}
if(m_deletionDateHasBeenSet)
{
payload.WithDouble("DeletionDate", m_deletionDate.SecondsWithMSPrecision());
}
if(m_versionIdHasBeenSet)
{
payload.WithString("VersionId", m_versionId);
}
if(m_backupPlanNameHasBeenSet)
{
payload.WithString("BackupPlanName", m_backupPlanName);
}
if(m_creatorRequestIdHasBeenSet)
{
payload.WithString("CreatorRequestId", m_creatorRequestId);
}
if(m_lastExecutionDateHasBeenSet)
{
payload.WithDouble("LastExecutionDate", m_lastExecutionDate.SecondsWithMSPrecision());
}
if(m_advancedBackupSettingsHasBeenSet)
{
Array<JsonValue> advancedBackupSettingsJsonList(m_advancedBackupSettings.size());
for(unsigned advancedBackupSettingsIndex = 0; advancedBackupSettingsIndex < advancedBackupSettingsJsonList.GetLength(); ++advancedBackupSettingsIndex)
{
advancedBackupSettingsJsonList[advancedBackupSettingsIndex].AsObject(m_advancedBackupSettings[advancedBackupSettingsIndex].Jsonize());
}
payload.WithArray("AdvancedBackupSettings", std::move(advancedBackupSettingsJsonList));
}
return payload;
}
} // namespace Model
} // namespace Backup
} // namespace Aws
| 24.751351 | 154 | 0.762175 | [
"model"
] |
e6b62a75c4acb0f326756bc651d1e813470635dd | 11,948 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/plugins/clangcodemodel/clangcompletionchunkstotextconverter.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/src/plugins/clangcodemodel/clangcompletionchunkstotextconverter.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/src/plugins/clangcodemodel/clangcompletionchunkstotextconverter.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "clangcompletionchunkstotextconverter.h"
#include <algorithm>
#include <functional>
namespace ClangCodeModel {
namespace Internal {
void CompletionChunksToTextConverter::parseChunks(
const ClangBackEnd::CodeCompletionChunks &codeCompletionChunks)
{
m_text.clear();
m_placeholderPositions.clear();
m_codeCompletionChunks = codeCompletionChunks;
addExtraVerticalSpaceBetweenBraces();
std::for_each(m_codeCompletionChunks.cbegin(),
m_codeCompletionChunks.cend(),
[this] (const ClangBackEnd::CodeCompletionChunk &chunk)
{
parseDependendOnTheOptionalState(chunk);
m_previousCodeCompletionChunk = chunk;
});
}
void CompletionChunksToTextConverter::setAddPlaceHolderText(bool addPlaceHolderText)
{
m_addPlaceHolderText = addPlaceHolderText;
}
void CompletionChunksToTextConverter::setAddPlaceHolderPositions(bool addPlaceHolderPositions)
{
m_addPlaceHolderPositions = addPlaceHolderPositions;
}
void CompletionChunksToTextConverter::setAddResultType(bool addResultType)
{
m_addResultType = addResultType;
}
void CompletionChunksToTextConverter::setAddSpaces(bool addSpaces)
{
m_addSpaces = addSpaces;
}
void CompletionChunksToTextConverter::setAddExtraVerticalSpaceBetweenBraces(
bool addExtraVerticalSpaceBetweenBraces)
{
m_addExtraVerticalSpaceBetweenBraces = addExtraVerticalSpaceBetweenBraces;
}
void CompletionChunksToTextConverter::setEmphasizeOptional(bool emphasizeOptional)
{
m_emphasizeOptional = emphasizeOptional;
}
void CompletionChunksToTextConverter::setAddOptional(bool addOptional)
{
m_addOptional = addOptional;
}
void CompletionChunksToTextConverter::setPlaceHolderToEmphasize(int placeHolderNumber)
{
m_placeHolderPositionToEmphasize = placeHolderNumber;
}
void CompletionChunksToTextConverter::setCompletionKind(const ClangBackEnd::CodeCompletion::Kind kind)
{
m_codeCompletionKind = kind;
}
void CompletionChunksToTextConverter::setupForKeywords()
{
setAddPlaceHolderPositions(true);
setAddSpaces(true);
setAddExtraVerticalSpaceBetweenBraces(true);
}
const QString &CompletionChunksToTextConverter::text() const
{
return m_text;
}
const std::vector<int> &CompletionChunksToTextConverter::placeholderPositions() const
{
return m_placeholderPositions;
}
bool CompletionChunksToTextConverter::hasPlaceholderPositions() const
{
return m_placeholderPositions.size() > 0;
}
QString CompletionChunksToTextConverter::convertToFunctionSignatureWithHtml(
const ClangBackEnd::CodeCompletionChunks &codeCompletionChunks,
ClangBackEnd::CodeCompletion::Kind codeCompletionKind,
int parameterToEmphasize)
{
CompletionChunksToTextConverter converter;
converter.setAddPlaceHolderText(true);
converter.setAddResultType(true);
converter.setTextFormat(TextFormat::Html);
converter.setAddOptional(true);
converter.setEmphasizeOptional(true);
converter.setAddPlaceHolderPositions(true);
converter.setPlaceHolderToEmphasize(parameterToEmphasize);
converter.setCompletionKind(codeCompletionKind);
converter.parseChunks(codeCompletionChunks);
return converter.text();
}
QString CompletionChunksToTextConverter::convertToName(
const ClangBackEnd::CodeCompletionChunks &codeCompletionChunks)
{
CompletionChunksToTextConverter converter;
converter.parseChunks(codeCompletionChunks);
return converter.text();
}
QString CompletionChunksToTextConverter::convertToToolTipWithHtml(
const ClangBackEnd::CodeCompletionChunks &codeCompletionChunks,
ClangBackEnd::CodeCompletion::Kind codeCompletionKind)
{
CompletionChunksToTextConverter converter;
converter.setAddPlaceHolderText(true);
converter.setAddSpaces(true);
converter.setAddExtraVerticalSpaceBetweenBraces(true);
converter.setAddOptional(true);
converter.setTextFormat(TextFormat::Html);
converter.setEmphasizeOptional(true);
converter.setAddResultType(true);
converter.setCompletionKind(codeCompletionKind);
converter.parseChunks(codeCompletionChunks);
return converter.text();
}
void CompletionChunksToTextConverter::parse(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk)
{
using ClangBackEnd::CodeCompletionChunk;
switch (codeCompletionChunk.kind()) {
case CodeCompletionChunk::ResultType: parseResultType(codeCompletionChunk.text()); break;
// Do not rely on CurrentParameter because it might be wrong for
// invalid code. Instead, handle it as PlaceHolder.
case CodeCompletionChunk::CurrentParameter:
case CodeCompletionChunk::Placeholder:
parsePlaceHolder(codeCompletionChunk); break;
case CodeCompletionChunk::LeftParen: parseLeftParen(codeCompletionChunk); break;
case CodeCompletionChunk::LeftBrace: parseLeftBrace(codeCompletionChunk); break;
default: parseText(codeCompletionChunk.text()); break;
}
}
void CompletionChunksToTextConverter::parseDependendOnTheOptionalState(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk)
{
wrapInCursiveTagIfOptional(codeCompletionChunk);
if (isNotOptionalOrAddOptionals(codeCompletionChunk))
parse(codeCompletionChunk);
}
void CompletionChunksToTextConverter::parseResultType(const Utf8String &resultTypeText)
{
if (m_addResultType)
m_text += inDesiredTextFormat(resultTypeText) + QChar(QChar::Space);
}
void CompletionChunksToTextConverter::parseText(const Utf8String &text)
{
if (canAddSpace()
&& m_previousCodeCompletionChunk.kind() == ClangBackEnd::CodeCompletionChunk::RightBrace) {
m_text += QChar(QChar::Space);
}
m_text += inDesiredTextFormat(text);
}
void CompletionChunksToTextConverter::wrapInCursiveTagIfOptional(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk)
{
if (m_addOptional) {
if (m_emphasizeOptional && m_textFormat == TextFormat::Html) {
if (!m_previousCodeCompletionChunk.isOptional() && codeCompletionChunk.isOptional())
m_text += QStringLiteral("<i>");
else if (m_previousCodeCompletionChunk.isOptional() && !codeCompletionChunk.isOptional())
m_text += QStringLiteral("</i>");
}
}
}
void CompletionChunksToTextConverter::parsePlaceHolder(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk)
{
if (m_addPlaceHolderText) {
appendText(inDesiredTextFormat(codeCompletionChunk.text()),
emphasizeCurrentPlaceHolder());
}
if (m_addPlaceHolderPositions)
m_placeholderPositions.push_back(m_text.size());
}
void CompletionChunksToTextConverter::parseLeftParen(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk)
{
if (canAddSpace())
m_text += QChar(QChar::Space);
m_text += codeCompletionChunk.text().toString();
}
void CompletionChunksToTextConverter::parseLeftBrace(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk)
{
if (canAddSpace())
m_text += QChar(QChar::Space);
m_text += codeCompletionChunk.text().toString();
}
void CompletionChunksToTextConverter::addExtraVerticalSpaceBetweenBraces()
{
if (m_addExtraVerticalSpaceBetweenBraces)
addExtraVerticalSpaceBetweenBraces(m_codeCompletionChunks.begin());
}
void CompletionChunksToTextConverter::addExtraVerticalSpaceBetweenBraces(
const ClangBackEnd::CodeCompletionChunks::iterator &begin)
{
using ClangBackEnd::CodeCompletionChunk;
const auto leftBraceCompare = [] (const CodeCompletionChunk &chunk) {
return chunk.kind() == CodeCompletionChunk::LeftBrace;
};
const auto rightBraceCompare = [] (const CodeCompletionChunk &chunk) {
return chunk.kind() == CodeCompletionChunk::RightBrace;
};
const auto verticalSpaceCompare = [] (const CodeCompletionChunk &chunk) {
return chunk.kind() == CodeCompletionChunk::VerticalSpace;
};
auto leftBrace = std::find_if(begin, m_codeCompletionChunks.end(), leftBraceCompare);
if (leftBrace != m_codeCompletionChunks.end()) {
auto rightBrace = std::find_if(leftBrace, m_codeCompletionChunks.end(), rightBraceCompare);
if (rightBrace != m_codeCompletionChunks.end()) {
auto verticalSpaceCount = std::count_if(leftBrace, rightBrace, verticalSpaceCompare);
if (verticalSpaceCount <= 1) {
auto distance = std::distance(leftBrace, rightBrace);
CodeCompletionChunk verticalSpaceChunck(CodeCompletionChunk::VerticalSpace,
Utf8StringLiteral("\n"));
auto verticalSpace = m_codeCompletionChunks.insert(std::next(leftBrace),
verticalSpaceChunck);
std::advance(verticalSpace, distance);
rightBrace = verticalSpace;
}
auto begin = std::next(rightBrace);
if (begin != m_codeCompletionChunks.end())
addExtraVerticalSpaceBetweenBraces(begin);
}
}
}
QString CompletionChunksToTextConverter::inDesiredTextFormat(const Utf8String &text) const
{
if (m_textFormat == TextFormat::Html)
return text.toString().toHtmlEscaped();
else
return text.toString();
}
bool CompletionChunksToTextConverter::emphasizeCurrentPlaceHolder() const
{
if (m_addPlaceHolderPositions) {
const uint currentPlaceHolderPosition = uint(m_placeholderPositions.size() + 1);
return uint(m_placeHolderPositionToEmphasize) == currentPlaceHolderPosition;
}
return false;
}
void CompletionChunksToTextConverter::setTextFormat(TextFormat textFormat)
{
m_textFormat = textFormat;
}
void CompletionChunksToTextConverter::appendText(const QString &text, bool boldFormat)
{
if (boldFormat && m_textFormat == TextFormat::Html)
m_text += QStringLiteral("<b>") + text + QStringLiteral("</b>");
else
m_text += text;
}
bool CompletionChunksToTextConverter::canAddSpace() const
{
return m_addSpaces
&& m_previousCodeCompletionChunk.kind() != ClangBackEnd::CodeCompletionChunk::HorizontalSpace
&& m_previousCodeCompletionChunk.kind() != ClangBackEnd::CodeCompletionChunk::RightAngle
&& m_codeCompletionKind != ClangBackEnd::CodeCompletion::FunctionCompletionKind;
}
bool CompletionChunksToTextConverter::isNotOptionalOrAddOptionals(
const ClangBackEnd::CodeCompletionChunk &codeCompletionChunk) const
{
return !codeCompletionChunk.isOptional() || m_addOptional;
}
} // namespace Internal
} // namespace ClangCodeModel
| 33.751412 | 103 | 0.732675 | [
"vector"
] |
e6b94f6717cb5abc70e878547d37e2c5278ed372 | 10,064 | cpp | C++ | Common/Geometry/Buffer/plgnsbak.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/Geometry/Buffer/plgnsbak.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/Geometry/Buffer/plgnsbak.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
//------------------------------------------------------------------------------
//
// FILE: plgnsbak.cpp.
//
// PURPOSE: Implementation of the PolygonSetback class.
//
//------------------------------------------------------------------------------
#include "Foundation.h"
#include "buffer.h"
//#include <mapobjec.h>
//#include <plgnobj.h>
//------------------------------------------------------------------------------
//
// METHOD: Constructor.
//
// PURPOSE: Create and initialize a PolygonSetback object.
//
// PARAMETERS:
//
// Input:
//
// polygonObj - passes a reference to the polygon object that the
// setback is to be generated for.
// pBufferUtil - passes the number of segments that would be used in
// the polygonization of a complete circle, and also
// the buffer offset distance.
//
// Output:
//
// None.
//
// EXCEPTIONS: A CMemoryException is thrown if there is insufficient memory
// available to create the PolygonSetback object.
//
//------------------------------------------------------------------------------
//PolygonSetback::PolygonSetback(const PolygonObject &polygonObj, BufferUtility *pBufferUtil) :
// PolygonBuffer(polygonObj, pBufferUtil)
//{
//} // end: constructor
//------------------------------------------------------------------------------
//
// METHOD: Constructor.
//
// PURPOSE: Create and initialize a PolygonSetback object.
//
// PARAMETERS:
//
// Input:
//
// polygon - passes a reference to the OpsPolygon object that
// the setback is to be generated for.
// pBufferUtil - passes the number of segments that would be used in
// the polygonization of a complete circle, and also
// the buffer offset distance.
//
// Output:
//
// None.
//
// EXCEPTIONS: A CMemoryException is thrown if there is insufficient memory
// available to create the PolygonSetback object.
//
//------------------------------------------------------------------------------
PolygonSetback::PolygonSetback(const OpsPolygon &polygon, BufferUtility *pBufferUtil) :
PolygonBuffer(polygon, pBufferUtil)
{
} // end: constructor
//------------------------------------------------------------------------------
//
// METHOD: Constructor.
//
// PURPOSE: Create and initialize a PolygonSetback object.
//
// PARAMETERS:
//
// Input:
//
// polyPolygon - passes a reference to the OpsPolyPolygon object that
// the setback is to be generated for.
// pBufferUtil - passes the number of segments that would be used in
// the polygonization of a complete circle, and also
// the buffer offset distance.
//
// Output:
//
// None.
//
// EXCEPTIONS: A CMemoryException is thrown if there is insufficient memory
// available to create the PolygonSetback object.
//
//------------------------------------------------------------------------------
PolygonSetback::PolygonSetback(const OpsPolyPolygon &polyPolygon, BufferUtility *pBufferUtil) :
PolygonBuffer(polyPolygon, pBufferUtil)
{
} // end: constructor
//------------------------------------------------------------------------------
//
// METHOD: CreateSetback().
//
// PURPOSE: Create a setback inside the polygon object specified at construc-
// tion time.
//
// PARAMETERS:
//
// Input:
//
// callback - passes a pointer to a ProgressCallback object. The
// object is periodically notified of progress, and
// checked to determine if the setback operation has
// been canceled.
//
// Output:
//
// setbackPolygon - passes a reference to an OrientedPolyPolygon object.
// The boundaries of the setback polygon are copied
// to the referenced object.
//
// EXCEPTIONS: A CMemoryException is thrown if there is insufficient memory
// available to create the setback. A PlaneSweepException is thrown
// if an error is detected during the execution of the planesweep
// algorithm.
//
//------------------------------------------------------------------------------
void PolygonSetback::CreateSetback(ProgressCallback &callback,
OrientedPolyPolygon &setbackPolygon)
{
// forward call to base class method. Although it may seem a little odd to
// call the buffering method of the base-class to generate the setback, it
// is the AcceptBoundary method (below) that determines which boundaries to
// include in the output that makes it all work
CreateBufferZone(callback, setbackPolygon);
} // end: CreateSetback()
//------------------------------------------------------------------------------
//
// METHOD: AcceptBoundary().
//
// PURPOSE: Determine whether a potential polygon boundary should be included
// as part of the setback polygon.
//
// PARAMETERS:
//
// Input:
//
// boundaryExt - passes a reference to an OpsFloatExtent containing
// the extent of the boundary.
// boundaryOrient - passes an enumerated value of type Orientation,
// specifying the orientation of the boundary.
// boundaryVert - passes a reference to an OpsFloatPoint. The refer-
// enced object contains the coordinates of a point
// that lies on the polygon boundary.
// interiorPt - passes a reference to a OpsDoublePoint containing
// the coordinates of a point that is strictly interior
// to the boundary.
//
// Output:
//
// None.
//
// RETURNS: TRUE if the polygon boundary should be accepted as part of the
// output and FALSE otherwise.
//
// EXCEPTIONS: None.
//
//------------------------------------------------------------------------------
BOOL PolygonSetback::AcceptBoundary(const OpsFloatExtent &, Orientation,
const OpsFloatPoint &boundaryVert, const OpsDoublePoint &interiorPt) const
{
// first, test the boundary vertex and if it is not contained in the input
// polygon, then the boundary is not part of the setback polygon - return
// FALSE
OpsDoublePoint vertex(boundaryVert.x, boundaryVert.y);
if (!PointInPolygon(vertex))
return FALSE;
// otherwise, test the interior point to ensure that it does not lie within
// the inset distance of the input polygon boundary
for (int i = 0, j = 0; i < m_nPolyObjects; i++) {
if (PointWithinOffsetDist(&m_pVertices[j], m_pnPolyVerts[i], interiorPt))
return FALSE;
j += m_pnPolyVerts[i];
}
// if we got here, then it must be a legitimate output boundary - return
// TRUE
return TRUE;
} // end: AcceptBoundary()
//------------------------------------------------------------------------------
//
// METHOD: GenerateBufferZone().
//
// PURPOSE: Create the buffer zone polygon for the specified poly-object (where
// a poly-object is a poly-polyline or poly-polygon).
//
// PARAMETERS:
//
// vertices - passes an array of the poly-object vertices.
// nPolyVerts - passes an array of the counts of the number of
// vertices in each sub-object (polyline or polygon).
// nPolyObjects - passes the number of sub-objects.
// callback - passes a reference to a ProgressCallback object. The
// object is periodically notified of progress, and
// checked to determine if the buffer operation has
// been canceled.
//
// Output:
//
// bufferPolygon - passes a reference to an OrientedPolyPolygon object.
// The buffer zone polygon containing for the poly-
// object is copied to the referenced object.
//
// RETURNS: None.
//
// EXCEPTIONS: A CMemoryException is thrown if there is insufficient memory
// available to create the buffer zone. A PlaneSweepException is
// thrown if an error is detected during the execution of the plane
// sweep algorithm.
//
//------------------------------------------------------------------------------
void PolygonSetback::GenerateBufferZone(const OpsFloatPoint vertices[],
const int nPolyVerts[], int nPolyObjects, ProgressCallback &callback,
OrientedPolyPolygon &bufferPolygon)
{
// We'll get a PlaneSweepException if the setback distance causes the
// polygon to shrink to zero area. Catch this and don't pass it on.
try
{
// call the base class first - this will generate an OrientedPolyPolygon
// with reversed orientation
PolyObjectBuffer::GenerateBufferZone(vertices, nPolyVerts, nPolyObjects, callback, bufferPolygon);
// reverse the boundaries / points of the polygon
bufferPolygon.ReverseBoundaries();
}
catch (PlaneSweepException* ex)
{
delete ex;
}
} // end: GenerateBufferZone()
| 35.312281 | 106 | 0.56558 | [
"object"
] |
e6bd47048fb05b3890c5d28f8da825e6ee6bb2db | 5,104 | hpp | C++ | octopus/global_variable.hpp | STEllAR-GROUP/octopus | a1f910d63380e4ebf91198ac2bc2896505ce6146 | [
"BSL-1.0"
] | 4 | 2016-01-30T14:47:21.000Z | 2017-11-19T19:03:19.000Z | octopus/global_variable.hpp | STEllAR-GROUP/octopus | a1f910d63380e4ebf91198ac2bc2896505ce6146 | [
"BSL-1.0"
] | null | null | null | octopus/global_variable.hpp | STEllAR-GROUP/octopus | a1f910d63380e4ebf91198ac2bc2896505ce6146 | [
"BSL-1.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2012 Bryce Adelstein-Lelbach
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
#if !defined(OCTOPUS_EEC57C22_4221_4E32_8288_DC2A4F9D957B)
#define OCTOPUS_EEC57C22_4221_4E32_8288_DC2A4F9D957B
#include <octopus/traits.hpp>
#include <hpx/util/static.hpp>
#include <hpx/include/actions.hpp>
#include <hpx/lcos/future_wait.hpp>
namespace octopus
{
template <typename T, typename Tag>
void update_here(typename parameter_type<T>::type t)
{
hpx::util::static_<T, Tag> storage;
storage.get() = t;
}
template <typename T, typename Tag>
struct update_here_action
: hpx::actions::make_action<
void (*)(typename parameter_type<T>::type)
, &update_here<T, Tag>
, update_here_action<T, Tag>
>
{};
template <typename T, typename Tag>
struct global_variable
{
private:
void update_everywhere(typename parameter_type<T>::type t)
{
std::vector<hpx::id_type> targets = hpx::find_all_localities();
std::vector<hpx::future<void> > futures;
futures.reserve(targets.size());
for (boost::uint64_t i = 0; i < targets.size(); ++i)
{
futures.push_back(hpx::async<update_here_action<T, Tag> >
(targets[i], t));
}
hpx::lcos::wait(futures);
}
public:
global_variable() {}
global_variable(typename parameter_type<T>::type t)
{
hpx::util::static_<T, Tag> storage;
storage.get() = t;
}
global_variable& operator=(typename parameter_type<T>::type t)
{
update_everywhere(t);
return *this;
}
operator T const&() const
{
hpx::util::static_<T, Tag> storage;
return storage.get();
}
T const& get() const
{
hpx::util::static_<T, Tag> storage;
return storage.get();
}
};
/// Let the INI config reader get to the real type.
template <typename T, typename Tag>
struct proxied_type<global_variable<T, Tag> >
{
typedef T type;
};
/// Ensure that the INI config reader handles bools properly.
template <typename Tag>
struct is_bool<global_variable<bool, Tag> > : boost::mpl::true_ {};
/// The compiler won't do the right thing in this (e.g. call the conversion
/// operator). Necessary for the INI config reader.
template <typename T, typename Tag>
inline std::ostream& operator<<(
std::ostream& os
, global_variable<T, Tag> gv
)
{
return os << gv.get();
}
}
HPX_REGISTER_PLAIN_ACTION_TEMPLATE(
(template <typename T, typename Tag>),
(octopus::update_here_action<T, Tag>))
/// Usage: OCTOPUS_GLOBAL_VARIABLE((type), name)
/// Usage: OCTOPUS_GLOBAL_VARIABLE((type), name, (initial_value))
#define OCTOPUS_GLOBAL_VARIABLE(...) \
HPX_UTIL_EXPAND_(BOOST_PP_CAT( \
OCTOPUS_GLOBAL_VARIABLE_, HPX_UTIL_PP_NARG(__VA_ARGS__) \
)(__VA_ARGS__)) \
/**/
#define OCTOPUS_GLOBAL_VARIABLE_2(type, name) \
struct BOOST_PP_CAT( \
BOOST_PP_CAT(__hpx_global_variable_tag_, __LINE__), \
BOOST_PP_CAT(_, name)) {}; \
\
octopus::global_variable<HPX_UTIL_STRIP(type), BOOST_PP_CAT( \
BOOST_PP_CAT(__hpx_global_variable_tag_, __LINE__), \
BOOST_PP_CAT(_, name))> name = \
octopus::global_variable<HPX_UTIL_STRIP(type), BOOST_PP_CAT( \
BOOST_PP_CAT(__hpx_global_variable_tag_, __LINE__), \
BOOST_PP_CAT(_, name))>(); \
/**/
#define OCTOPUS_GLOBAL_VARIABLE_3(type, name, initial_value) \
struct BOOST_PP_CAT( \
BOOST_PP_CAT(__hpx_global_variable_tag_, __LINE__), \
BOOST_PP_CAT(_, name)) {}; \
\
octopus::global_variable<HPX_UTIL_STRIP(type), BOOST_PP_CAT( \
BOOST_PP_CAT(__hpx_global_variable_tag_, __LINE__), \
BOOST_PP_CAT(_, name))> name = \
octopus::global_variable<HPX_UTIL_STRIP(type), BOOST_PP_CAT( \
BOOST_PP_CAT(__hpx_global_variable_tag_, __LINE__), \
BOOST_PP_CAT(_, name))>(HPX_UTIL_STRIP(initial_value)); \
/**/
#endif // OCTOPUS_EEC57C22_4221_4E32_8288_DC2A4F9D957B
| 34.255034 | 80 | 0.536442 | [
"vector"
] |
e6c099dbdf0dd4aba9d1781622b229fed478595b | 6,177 | cpp | C++ | Udemy/07. [CODING] Uniform Variables/main.cpp | Mavrikant/OpenGL-Course | c65c1bb4360e1de056c7a5616cd55e55b91ed9d4 | [
"MIT"
] | null | null | null | Udemy/07. [CODING] Uniform Variables/main.cpp | Mavrikant/OpenGL-Course | c65c1bb4360e1de056c7a5616cd55e55b91ed9d4 | [
"MIT"
] | null | null | null | Udemy/07. [CODING] Uniform Variables/main.cpp | Mavrikant/OpenGL-Course | c65c1bb4360e1de056c7a5616cd55e55b91ed9d4 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Window dimensions
const GLint WIDTH = 800;
const GLint HEIGHT = 600;
GLuint VBO, VAO, shader, Rotate_GLuint;
glm::mat4 transform = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
// Vertex Shader code
static const char *vShader = " \n\
#version 330 \n\
layout (location = 0) in vec3 pos; \n\
uniform mat4 Rotate_mat4; \n\
\n\
void main() \n\
{ \n\
gl_Position = Rotate_mat4 * vec4( 0.4*pos.x,0.4* pos.y, pos.z, 1.0); \n\
}";
// Fragment Shader
static const char *fShader = " \n\
#version 330 \n\
out vec4 colour; \n\
\n\
void main() \n\
{ \n\
colour = vec4(1.0, 0.0, 0.0, 1.0); \n\
}";
void CreateTriangle()
{
GLfloat vertices[] = {-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f};
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void AddShader(GLuint theProgram, const char *shaderCode, GLenum shaderType)
{
GLuint theShader = glCreateShader(shaderType);
const GLchar *theCode[1];
theCode[0] = shaderCode;
GLint codeLength[1];
codeLength[0] = strlen(shaderCode);
glShaderSource(theShader, 1, theCode, codeLength);
glCompileShader(theShader);
GLint result = 0;
GLchar eLog[1024] = {0};
glGetShaderiv(theShader, GL_COMPILE_STATUS, &result);
if (!result)
{
glGetShaderInfoLog(theShader, 1024, NULL, eLog);
fprintf(stderr, "Error compiling the %d shader: '%s'\n", shaderType, eLog);
return;
}
glAttachShader(theProgram, theShader);
}
void CompileShaders()
{
shader = glCreateProgram();
if (!shader)
{
printf("Failed to create shader\n");
return;
}
AddShader(shader, vShader, GL_VERTEX_SHADER);
AddShader(shader, fShader, GL_FRAGMENT_SHADER);
GLint result = 0;
GLchar eLog[1024] = {0};
glLinkProgram(shader);
glGetProgramiv(shader, GL_LINK_STATUS, &result);
if (!result)
{
glGetProgramInfoLog(shader, sizeof(eLog), NULL, eLog);
printf("Error linking program: '%s'\n", eLog);
return;
}
glValidateProgram(shader);
glGetProgramiv(shader, GL_VALIDATE_STATUS, &result);
if (!result)
{
glGetProgramInfoLog(shader, sizeof(eLog), NULL, eLog);
printf("Error validating program: '%s'\n", eLog);
return;
}
Rotate_GLuint = glGetUniformLocation(shader, "Rotate_mat4");
}
int main()
{
// Initialise GLFW
if (!glfwInit())
{
printf("GLFW initialisation failed!");
glfwTerminate();
return 1;
}
// Setup GLFW window properties
// OpenGL version
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Core Profile
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Allow Forward Compatbility
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// Create the window
GLFWwindow *mainWindow = glfwCreateWindow(WIDTH, HEIGHT, "Test Window", NULL, NULL);
if (!mainWindow)
{
printf("GLFW window creation failed!");
glfwTerminate();
return 1;
}
// Get Buffer Size information
int bufferWidth, bufferHeight;
glfwGetFramebufferSize(mainWindow, &bufferWidth, &bufferHeight);
// Set context for GLEW to use
glfwMakeContextCurrent(mainWindow);
// Allow modern extension features
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
printf("GLEW initialisation failed!");
glfwDestroyWindow(mainWindow);
glfwTerminate();
return 1;
}
// Setup Viewport size
glViewport(0, 0, bufferWidth, bufferHeight);
CreateTriangle();
CompileShaders();
double lastTime = glfwGetTime();
int nbFrames = 0;
// Loop until window closed
while (!glfwWindowShouldClose(mainWindow))
{
// Measure speed
double currentTime = glfwGetTime();
nbFrames++;
if (currentTime - lastTime >= 1.0)
{ // If last prinf() was more than 1 sec ago
// printf and reset timer
std::cout << "FPS: " << nbFrames << std::endl;
nbFrames = 0;
lastTime += 1.0;
}
// Get + Handle user input events
glfwPollEvents();
transform = glm::rotate(transform, (GLfloat)glfwGetTime() / 100000, glm::vec3(0.0f, 0.0f, 1.0f));
// Clear window
glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader);
glUniformMatrix4fv(Rotate_GLuint, 1, GL_FALSE, glm::value_ptr(transform)); // ID , size, transpose?, location
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3); // mode , first, size
glBindVertexArray(0);
glUseProgram(0);
glfwSwapBuffers(mainWindow);
}
return 0;
}
| 28.465438 | 117 | 0.54962 | [
"transform"
] |
e6c3a18d04962204898b085f40d9450131b7858a | 8,566 | cc | C++ | compiler/utils/assembler.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 234 | 2017-07-18T05:30:27.000Z | 2022-01-07T02:21:31.000Z | compiler/utils/assembler.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 21 | 2017-07-18T04:56:09.000Z | 2018-08-10T17:32:16.000Z | compiler/utils/assembler.cc | lifansama/xposed_art_n | ec3fbe417d74d4664cec053d91dd4e3881176374 | [
"MIT"
] | 56 | 2017-07-18T10:37:10.000Z | 2022-01-07T02:19:22.000Z | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "assembler.h"
#include <algorithm>
#include <vector>
#ifdef ART_ENABLE_CODEGEN_arm
#include "arm/assembler_arm32.h"
#include "arm/assembler_thumb2.h"
#endif
#ifdef ART_ENABLE_CODEGEN_arm64
#include "arm64/assembler_arm64.h"
#endif
#ifdef ART_ENABLE_CODEGEN_mips
#include "mips/assembler_mips.h"
#endif
#ifdef ART_ENABLE_CODEGEN_mips64
#include "mips64/assembler_mips64.h"
#endif
#ifdef ART_ENABLE_CODEGEN_x86
#include "x86/assembler_x86.h"
#endif
#ifdef ART_ENABLE_CODEGEN_x86_64
#include "x86_64/assembler_x86_64.h"
#endif
#include "base/casts.h"
#include "globals.h"
#include "memory_region.h"
namespace art {
AssemblerBuffer::AssemblerBuffer(ArenaAllocator* arena)
: arena_(arena) {
static const size_t kInitialBufferCapacity = 4 * KB;
contents_ = arena_->AllocArray<uint8_t>(kInitialBufferCapacity, kArenaAllocAssembler);
cursor_ = contents_;
limit_ = ComputeLimit(contents_, kInitialBufferCapacity);
fixup_ = nullptr;
slow_path_ = nullptr;
#ifndef NDEBUG
has_ensured_capacity_ = false;
fixups_processed_ = false;
#endif
// Verify internal state.
CHECK_EQ(Capacity(), kInitialBufferCapacity);
CHECK_EQ(Size(), 0U);
}
AssemblerBuffer::~AssemblerBuffer() {
if (arena_->IsRunningOnMemoryTool()) {
arena_->MakeInaccessible(contents_, Capacity());
}
}
void AssemblerBuffer::ProcessFixups(const MemoryRegion& region) {
AssemblerFixup* fixup = fixup_;
while (fixup != nullptr) {
fixup->Process(region, fixup->position());
fixup = fixup->previous();
}
}
void AssemblerBuffer::FinalizeInstructions(const MemoryRegion& instructions) {
// Copy the instructions from the buffer.
MemoryRegion from(reinterpret_cast<void*>(contents()), Size());
instructions.CopyFrom(0, from);
// Process fixups in the instructions.
ProcessFixups(instructions);
#ifndef NDEBUG
fixups_processed_ = true;
#endif
}
void AssemblerBuffer::ExtendCapacity(size_t min_capacity) {
size_t old_size = Size();
size_t old_capacity = Capacity();
DCHECK_GT(min_capacity, old_capacity);
size_t new_capacity = std::min(old_capacity * 2, old_capacity + 1 * MB);
new_capacity = std::max(new_capacity, min_capacity);
// Allocate the new data area and copy contents of the old one to it.
contents_ = reinterpret_cast<uint8_t*>(
arena_->Realloc(contents_, old_capacity, new_capacity, kArenaAllocAssembler));
// Update the cursor and recompute the limit.
cursor_ = contents_ + old_size;
limit_ = ComputeLimit(contents_, new_capacity);
// Verify internal state.
CHECK_EQ(Capacity(), new_capacity);
CHECK_EQ(Size(), old_size);
}
void DebugFrameOpCodeWriterForAssembler::ImplicitlyAdvancePC() {
uint32_t pc = dchecked_integral_cast<uint32_t>(assembler_->CodeSize());
if (delay_emitting_advance_pc_) {
uint32_t stream_pos = dchecked_integral_cast<uint32_t>(opcodes_.size());
delayed_advance_pcs_.push_back(DelayedAdvancePC {stream_pos, pc});
} else {
AdvancePC(pc);
}
}
std::unique_ptr<Assembler> Assembler::Create(
ArenaAllocator* arena,
InstructionSet instruction_set,
const InstructionSetFeatures* instruction_set_features) {
switch (instruction_set) {
#ifdef ART_ENABLE_CODEGEN_arm
case kArm:
return std::unique_ptr<Assembler>(new (arena) arm::Arm32Assembler(arena));
case kThumb2:
return std::unique_ptr<Assembler>(new (arena) arm::Thumb2Assembler(arena));
#endif
#ifdef ART_ENABLE_CODEGEN_arm64
case kArm64:
return std::unique_ptr<Assembler>(new (arena) arm64::Arm64Assembler(arena));
#endif
#ifdef ART_ENABLE_CODEGEN_mips
case kMips:
return std::unique_ptr<Assembler>(new (arena) mips::MipsAssembler(
arena,
instruction_set_features != nullptr
? instruction_set_features->AsMipsInstructionSetFeatures()
: nullptr));
#endif
#ifdef ART_ENABLE_CODEGEN_mips64
case kMips64:
return std::unique_ptr<Assembler>(new (arena) mips64::Mips64Assembler(arena));
#endif
#ifdef ART_ENABLE_CODEGEN_x86
case kX86:
return std::unique_ptr<Assembler>(new (arena) x86::X86Assembler(arena));
#endif
#ifdef ART_ENABLE_CODEGEN_x86_64
case kX86_64:
return std::unique_ptr<Assembler>(new (arena) x86_64::X86_64Assembler(arena));
#endif
default:
LOG(FATAL) << "Unknown InstructionSet: " << instruction_set;
return nullptr;
}
}
void Assembler::StoreImmediateToThread32(ThreadOffset<4> dest ATTRIBUTE_UNUSED,
uint32_t imm ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::StoreImmediateToThread64(ThreadOffset<8> dest ATTRIBUTE_UNUSED,
uint32_t imm ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::StoreStackOffsetToThread32(ThreadOffset<4> thr_offs ATTRIBUTE_UNUSED,
FrameOffset fr_offs ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::StoreStackOffsetToThread64(ThreadOffset<8> thr_offs ATTRIBUTE_UNUSED,
FrameOffset fr_offs ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::StoreStackPointerToThread32(ThreadOffset<4> thr_offs ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::StoreStackPointerToThread64(ThreadOffset<8> thr_offs ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::LoadFromThread32(ManagedRegister dest ATTRIBUTE_UNUSED,
ThreadOffset<4> src ATTRIBUTE_UNUSED,
size_t size ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::LoadFromThread64(ManagedRegister dest ATTRIBUTE_UNUSED,
ThreadOffset<8> src ATTRIBUTE_UNUSED,
size_t size ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::LoadRawPtrFromThread32(ManagedRegister dest ATTRIBUTE_UNUSED,
ThreadOffset<4> offs ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::LoadRawPtrFromThread64(ManagedRegister dest ATTRIBUTE_UNUSED,
ThreadOffset<8> offs ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::CopyRawPtrFromThread32(FrameOffset fr_offs ATTRIBUTE_UNUSED,
ThreadOffset<4> thr_offs ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::CopyRawPtrFromThread64(FrameOffset fr_offs ATTRIBUTE_UNUSED,
ThreadOffset<8> thr_offs ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::CopyRawPtrToThread32(ThreadOffset<4> thr_offs ATTRIBUTE_UNUSED,
FrameOffset fr_offs ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::CopyRawPtrToThread64(ThreadOffset<8> thr_offs ATTRIBUTE_UNUSED,
FrameOffset fr_offs ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::CallFromThread32(ThreadOffset<4> offset ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
void Assembler::CallFromThread64(ThreadOffset<8> offset ATTRIBUTE_UNUSED,
ManagedRegister scratch ATTRIBUTE_UNUSED) {
UNIMPLEMENTED(FATAL);
}
} // namespace art
| 33.724409 | 88 | 0.692272 | [
"vector"
] |
e6c837fa309538799a44d6461f5053a59d4a67f9 | 4,154 | cpp | C++ | source/RightPopupMenu.cpp | xzrunner/sketch | e16ffae33e6e583c13591e027e664f3a14c41dcb | [
"MIT"
] | null | null | null | source/RightPopupMenu.cpp | xzrunner/sketch | e16ffae33e6e583c13591e027e664f3a14c41dcb | [
"MIT"
] | null | null | null | source/RightPopupMenu.cpp | xzrunner/sketch | e16ffae33e6e583c13591e027e664f3a14c41dcb | [
"MIT"
] | null | null | null | #include "sketch/RightPopupMenu.h"
#include "sketch/ConsEditView.h"
#include <ee0/EditPanelImpl.h>
#include <ee0/WxStagePage.h>
#include <SM_Calc.h>
#include <geoshape/Shape2D.h>
#include <geoshape/Point2D.h>
#include <geoshape/Line2D.h>
#include <node0/SceneNode.h>
#include <node2/CompShape.h>
#include <wx/window.h>
namespace
{
enum MenuID
{
// Geometric constraints
ConsHorizontal = 20000,
ConsVertical,
// Dimensional constraints
ConsDistance,
ClearAll,
};
}
namespace sketch
{
RightPopupMenu::RightPopupMenu(ee0::WxStagePage* stage, ConsEditView& view)
: ee0::RightPopupMenu(stage, &stage->GetImpl())
, m_stage(stage)
, m_view(view)
{
}
void RightPopupMenu::SetRightPopupMenu(wxMenu& menu, int x, int y)
{
std::vector<std::shared_ptr<gs::Shape2D>> shapes;
GetAllShapes(shapes);
if (HaveConstriants(shapes, ConstriantsType::Horizontal))
{
m_stage->Bind(wxEVT_COMMAND_MENU_SELECTED,
&ee0::EditPanelImpl::OnRightPopupMenu, &m_stage->GetImpl(), ConsHorizontal);
menu.Append(ConsHorizontal, "Horizontal", "Line length or Points horizontal");
}
if (HaveConstriants(shapes, ConstriantsType::Vertical))
{
m_stage->Bind(wxEVT_COMMAND_MENU_SELECTED,
&ee0::EditPanelImpl::OnRightPopupMenu, &m_stage->GetImpl(), ConsVertical);
menu.Append(ConsVertical, "Vertical", "Line length or Points vertical");
}
if (HaveConstriants(shapes, ConstriantsType::Distance))
{
m_stage->Bind(wxEVT_COMMAND_MENU_SELECTED,
&ee0::EditPanelImpl::OnRightPopupMenu, &m_stage->GetImpl(), ConsDistance);
menu.Append(ConsDistance, "Distance", "Line length or Points distance");
}
menu.AppendSeparator();
m_stage->Bind(wxEVT_COMMAND_MENU_SELECTED,
&ee0::EditPanelImpl::OnRightPopupMenu, &m_stage->GetImpl(), ClearAll);
menu.Append(ClearAll, "Clear", "Clear all Constriants");
}
void RightPopupMenu::OnRightPopupMenu(int id)
{
std::vector<std::shared_ptr<gs::Shape2D>> shapes;
GetAllShapes(shapes);
switch (id)
{
case ConsHorizontal:
{
if (shapes.size() == 1 && shapes[0]->get_type() == rttr::type::get<gs::Line2D>())
{
auto line = std::static_pointer_cast<gs::Line2D>(shapes[0]);
m_view.AddHorizontalConstraint(line);
}
}
break;
case ConsVertical:
{
if (shapes.size() == 1 && shapes[0]->get_type() == rttr::type::get<gs::Line2D>())
{
auto line = std::static_pointer_cast<gs::Line2D>(shapes[0]);
m_view.AddVerticalConstraint(line);
}
}
break;
case ConsDistance:
{
if (shapes.size() == 1 && shapes[0]->get_type() == rttr::type::get<gs::Line2D>())
{
auto line = std::static_pointer_cast<gs::Line2D>(shapes[0]);
auto dist = sm::dis_pos_to_pos(line->GetStart(), line->GetEnd());
m_view.AddDistanceConstraint(line, dist);
}
}
break;
case ClearAll:
m_view.ClearConstraints();
break;
}
}
void RightPopupMenu::GetAllShapes(std::vector<std::shared_ptr<gs::Shape2D>>& shapes) const
{
m_stage->GetSelection().Traverse([&](const ee0::GameObjWithPos& nwp)->bool
{
auto node = nwp.GetNode();
if (!node->HasSharedComp<n2::CompShape>()) {
return true;
}
auto& cshape = node->GetSharedComp<n2::CompShape>();
auto& shape = cshape.GetShape();
if (shape) {
shapes.push_back(shape);
}
return true;
});
}
bool RightPopupMenu::HaveConstriants(const std::vector<std::shared_ptr<gs::Shape2D>>& shapes, ConstriantsType type)
{
switch (type)
{
case ConstriantsType::Horizontal:
case ConstriantsType::Vertical:
case ConstriantsType::Distance:
return (shapes.size() == 1 && shapes[0]->get_type() == rttr::type::get<gs::Line2D>())
|| (shapes.size() == 2 && shapes[0]->get_type() == rttr::type::get<gs::Point2D>()
&& shapes[1]->get_type() == rttr::type::get<gs::Point2D>());
}
return false;
}
} | 27.879195 | 115 | 0.624699 | [
"shape",
"vector"
] |
e6cc7819fb0e049190a96cba25e42fc06bed5383 | 2,073 | cpp | C++ | GoogleServiceServer/xmlParser.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null | GoogleServiceServer/xmlParser.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null | GoogleServiceServer/xmlParser.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null |
#include <windows.h>
#include <iostream>
#include "xmlParser.h"
#include <stdarg.h>
#include "Base64.h"
#include "Coder.h"
using namespace std;
int XMLParser::getvalue(char * str,char * name,char *dst,int * dstlen,int base64flag) {
int strsize = lstrlenA(str);
string h = string("<") + (name) + ">";
int cmpsize = strsize - h.length();
for (int i = 0;i < cmpsize; i++)
{
if (memcmp(str+i,h.c_str(),h.length()) == 0)
{
i += h.length();
string e = string("</") + (name) + ">";
cmpsize = strsize - e.length();
for (int j = i; j < cmpsize; j++)
{
if (memcmp(str + j , e.c_str(), e.length()) == 0)
{
int len = j - i;
memcpy(dst, str + i, len);
*(dst + len) = 0;
if (base64flag)
{
len = Base64::Base64Decode(dst, dst, len);
if (len )
{
// char * utf8 = 0;
// len = Coder::GBKToUTF8((const char*)dst, &utf8);
// if (len > 0)
// {
// memcpy(dst, utf8, len);
// *(dst + len) = 0;
// delete utf8;
// }
}
}
*dstlen = len;
return j + e.length();
}
}
}
}
return 0;
}
vector<string> XMLParser::getvalues(char * str, char * node, vector<string>names,int utf8flags) {
vector<string> vr;
int result = 0;
char arrays[1024];
int arrayslen = 0;
char item[1024];
int itemsize = 0;
char*buf = str;
int pos = 0;
while(pos = getvalue(buf, node, arrays,&arrayslen,FALSE))
{
if (pos > 0)
{
buf += pos;
char *subarray = arrays;
for (int i = 0; i< names.size();i ++)
{
itemsize = 0;
int subarraylen = getvalue(subarray,(char*) names[i].c_str(), item,&itemsize,FALSE);
//subarray += subarraylen;
result = Base64::Base64Decode(item, item, itemsize);
if (result > 0)
{
if (utf8flags)
{
char * utf8 = 0;
int len = Coder::GBKToUTF8((const char*)item, &utf8);
if (len > 0)
{
memcpy(item, utf8, len);
*(item + len) = 0;
delete utf8;
}
}
vr.push_back(item);
}
}
}
}
return vr;
} | 17.717949 | 97 | 0.51616 | [
"vector"
] |
e6cf9365aa35cf83e63ce6638a21aba944e3821e | 16,175 | cpp | C++ | parser/Parser.cpp | stefaniatadama/cps2000-minilang-interpreter | 9cde131af3491ad453d21f8e5de767fdc677a6e1 | [
"MIT"
] | 1 | 2020-02-13T08:06:58.000Z | 2020-02-13T08:06:58.000Z | parser/Parser.cpp | stefaniatadama/cps2000-minilang-interpreter | 9cde131af3491ad453d21f8e5de767fdc677a6e1 | [
"MIT"
] | null | null | null | parser/Parser.cpp | stefaniatadama/cps2000-minilang-interpreter | 9cde131af3491ad453d21f8e5de767fdc677a6e1 | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <vector>
#include <iostream>
#include "Parser.h"
#include "../AST/ASTProgramNode.h"
#include "../AST/ASTRealLiteralExpressionNode.h"
#include "../AST/ASTIntLiteralExpressionNode.h"
#include "../AST/ASTBoolLiteralExpressionNode.h"
#include "../AST/ASTStringLiteralExpressionNode.h"
#include "../AST/ASTIdentifierExpressionNode.h"
#include "../AST/ASTBinaryExpressionNode.h"
#include "../AST/ASTAssignmentStatementNode.h"
#include "../AST/ASTPrintStatementNode.h"
#include "../AST/ASTReturnStatementNode.h"
#include "../AST/ASTUnaryExpressionNode.h"
//Sets Parser class lexer to l
Parser::Parser(Lexer* l) : lexer(l){
}
ASTProgramNode* Parser::parse(){
auto statements = new vector<ASTNode*>;
while(lexer->getLookahead().tokenType != TOK_EOF)
statements->push_back(parseStatement());
return new ASTProgramNode(*statements);
}
TYPE Parser::getType(string lexeme){
if(lexeme == "real")
return REAL;
else if(lexeme == "int")
return INT;
else if(lexeme == "bool")
return BOOL;
else if(lexeme == "string")
return STRING;
}
bool Parser::toBool(string str){
return str == "true";
}
ASTNode* Parser::parseStatement(){
switch(lexer->getLookahead().tokenType){
case(TOK_Var):{
currentToken = lexer->getNextToken();
return parseVariableDeclaration();
}
case(TOK_Set):{
currentToken = lexer->getNextToken();
return parseAssignment();
}
case(TOK_Print):{
currentToken = lexer->getNextToken();
ASTExpressionNode * expressionNode = parseExpression();
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Delimeter){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ';' at the end of statement.");
}
return new ASTPrintStatementNode(expressionNode);
}
case(TOK_If):{
currentToken = lexer->getNextToken();
return parseIfStatement();
}
case(TOK_While):{
currentToken = lexer->getNextToken();
return parseWhileStatement();
}
case(TOK_Return):{
currentToken = lexer->getNextToken();
ASTExpressionNode * expressionNode = parseExpression();
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Delimeter){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ';' at the end of statement.");
}
return new ASTReturnStatementNode(expressionNode);
}
case(TOK_Def):{
currentToken = lexer->getNextToken();
return parseFunctionDeclaration();
}
case(TOK_OpenScope):{
return parseBlock();
}
default:
throw runtime_error("Error on line " + to_string(lexer->getLookahead().lineNumber) + ".");
}
}
ASTExpressionNode* Parser::parseExpression(){
ASTExpressionNode * expressionNode = parseSimpleExpression();
string op;
if(lexer->getLookahead().tokenType == TOK_RelOp){
currentToken = lexer->getNextToken();
op = currentToken.lexeme;
//Recursively parse the right expression
return new ASTBinaryExpressionNode(op, expressionNode, parseExpression());
}
return expressionNode;
}
ASTExpressionNode* Parser::parseSimpleExpression(){
ASTExpressionNode * expressionNode = parseTerm();
string op;
if(lexer->getLookahead().tokenType == TOK_AdditiveOp || lexer->getLookahead().tokenType == TOK_Or){
currentToken = lexer->getNextToken();
op = currentToken.lexeme;
//Recursively parse the right expression
return new ASTBinaryExpressionNode(op, expressionNode, parseSimpleExpression());
}
return expressionNode;
}
ASTExpressionNode* Parser::parseTerm(){
ASTExpressionNode * expressionNode = parseFactor();
string op;
if(lexer->getLookahead().tokenType == TOK_MultiplicativeOp || lexer->getLookahead().tokenType == TOK_And){
currentToken = lexer->getNextToken();
op = currentToken.lexeme;
//Recursively parse the right expression
return new ASTBinaryExpressionNode(op, expressionNode, parseTerm());
}
return expressionNode;
}
ASTFunctionCallExpressionNode* Parser::parseFunctionCall(){
string functionName = currentToken.lexeme;
//Make currentToken '('
currentToken = lexer->getNextToken();
auto expressionNode = new vector<ASTExpressionNode*>;
//If next token is not ')', function is being passed some argument(s)
if(lexer->getLookahead().tokenType != TOK_CloseParenthesis)
expressionNode = parseActualParams();
else
lexer->getNextToken(); //Consume ')' in case there are no arguments
return new ASTFunctionCallExpressionNode(*expressionNode, functionName);
}
vector<ASTExpressionNode*>* Parser::parseActualParams(){
//Storing arguments in a vector
auto arguments = new vector<ASTExpressionNode*>;
arguments->push_back(parseExpression());
//If ',' follows, more arguments were passed
while(lexer->getLookahead().tokenType == TOK_Comma){
//Consume ','
currentToken = lexer->getNextToken();
arguments->push_back(parseExpression());
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_CloseParenthesis)
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ')' after list of arguments in function call.");
return arguments;
}
ASTExpressionNode* Parser::parseFactor(){
currentToken = lexer->getNextToken();
switch(currentToken.tokenType){
//Literal
case(TOK_FloatLiteral):
case(TOK_IntLiteral):
case(TOK_Boolean):
case(TOK_String):{
ASTLiteralExpressionNode* literalNode = parseLiteral();
return literalNode;
}
/* Identifier & FunctionCall
* Upon meeting an identifier, we check if there is a parenthesis directly after it,
* in which case it would be a function call */
case(TOK_Identifier):{
if (lexer->getLookahead().tokenType == TOK_OpenParenthesis) {
ASTFunctionCallExpressionNode *expressionNode = parseFunctionCall();
return expressionNode;
} else {
return new ASTIdentifierExpressionNode(currentToken.lexeme);
}
}
//SubExpression
case(TOK_OpenParenthesis):{
ASTExpressionNode *expressionNode = parseExpression();
currentToken = lexer->getNextToken();
if (currentToken.tokenType != TOK_CloseParenthesis)
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ')' after subexpression." + currentToken.lexeme);
return expressionNode;
}
//Unary
case(TOK_AdditiveOp):
case(TOK_Not): {
return new ASTUnaryExpressionNode(currentToken.lexeme, parseExpression());
}
default:
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": invalid expression.");
}
}
ASTLiteralExpressionNode* Parser::parseLiteral(){
switch(currentToken.tokenType){
case(TOK_FloatLiteral):
return new ASTRealLiteralExpressionNode(stof(currentToken.lexeme));
case(TOK_IntLiteral):
return new ASTIntLiteralExpressionNode(stoi(currentToken.lexeme));
case(TOK_Boolean):
return new ASTBoolLiteralExpressionNode(toBool(currentToken.lexeme));
case(TOK_String):
return new ASTStringLiteralExpressionNode(currentToken.lexeme.substr(1, currentToken.lexeme.size() - 2));
default:
return nullptr;
}
}
ASTDeclarationStatementNode* Parser::parseVariableDeclaration(){
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Identifier){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + " : expected identifier after var keyword.");
}
string identifier = currentToken.lexeme;
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Colon){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ':' after identifier.");
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_LangType){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected variable type after ':'.");
}
TYPE type = getType(currentToken.lexeme);
ASTIdentifierExpressionNode* identifierExpressionNode = new ASTIdentifierExpressionNode(identifier, type);
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Equals){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '=' after variable type.");
}
ASTExpressionNode * expressionNode = parseExpression();
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Delimeter){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ';' at the end of statement.");
}
return new ASTDeclarationStatementNode(identifierExpressionNode, expressionNode);
}
ASTAssignmentStatementNode* Parser::parseAssignment(){
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Identifier){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected identifier after set keyword.");
}
string identifier = currentToken.lexeme;
currentToken = lexer->getNextToken();
ASTIdentifierExpressionNode* identifierExpressionNode = new ASTIdentifierExpressionNode(identifier);
if(currentToken.tokenType != TOK_Equals){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '=' after identifier.");
}
ASTExpressionNode * expressionNode = parseExpression();
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Delimeter){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ';' at the end of statement.");
}
return new ASTAssignmentStatementNode(identifierExpressionNode, expressionNode);
}
ASTIfStatementNode* Parser::parseIfStatement(){
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_OpenParenthesis){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '(' after if keyword.");
}
ASTExpressionNode * ifConditionExpressionNode = parseExpression();
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_CloseParenthesis){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ')' after expression.");
}
ASTBlockStatementNode* ifBody = parseBlock();
ASTBlockStatementNode* elseBody = nullptr;
if(lexer->getLookahead().tokenType == TOK_Else){
//Make current token 'else'
currentToken = lexer->getNextToken();
elseBody = parseBlock();
}
return new ASTIfStatementNode(ifConditionExpressionNode, ifBody, elseBody);
}
ASTBlockStatementNode* Parser::parseBlock(){
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_OpenScope){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '{' at the beginning of a block.");
}
auto statements = new vector<ASTNode*>;
while(lexer->getLookahead().tokenType != TOK_CloseScope){
statements->push_back(parseStatement());
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_CloseScope){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '}' at the end of a block.");
}
return new ASTBlockStatementNode(*statements);
}
ASTWhileStatementNode* Parser::parseWhileStatement(){
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_OpenParenthesis){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '(' after while keyword.");
}
ASTExpressionNode * whileConditionExpressionNode = parseExpression();
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_CloseParenthesis){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ')' after expression.");
}
ASTBlockStatementNode* whileBody = parseBlock();
return new ASTWhileStatementNode(whileConditionExpressionNode, whileBody);
}
ASTFunctionDeclarationStatementNode* Parser::parseFunctionDeclaration(){
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Identifier){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected identifier after def keyword.");
}
string identifier = currentToken.lexeme;
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_OpenParenthesis){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected '(' after identifier.");
}
currentToken = lexer->getNextToken();
auto params = new vector<ASTIdentifierExpressionNode*>;
if(currentToken.tokenType != TOK_CloseParenthesis) {
params = parseFormalParams();
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Colon){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ':' after ')'.");
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_LangType){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected variable type after ':'.");
}
TYPE type = getType(currentToken.lexeme);
ASTBlockStatementNode* functionBody = parseBlock();
return new ASTFunctionDeclarationStatementNode(identifier, *params, type, functionBody);
}
vector<ASTIdentifierExpressionNode*>* Parser::parseFormalParams(){
auto params = new vector<ASTIdentifierExpressionNode*>;
params->push_back(parseFormalParam());
//If ',' follows, more parameters were passed
while(lexer->getLookahead().tokenType == TOK_Comma){
//Consume ','
currentToken = lexer->getNextToken();
//Get token identifier
currentToken = lexer->getNextToken();
params->push_back(parseFormalParam());
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_CloseParenthesis){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ')' after parameter list.");
}
return params;
}
ASTIdentifierExpressionNode* Parser::parseFormalParam(){
if(currentToken.tokenType != TOK_Identifier){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected identifier.");
}
string identifier = currentToken.lexeme;
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_Colon){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected ':' after identifier.");
}
currentToken = lexer->getNextToken();
if(currentToken.tokenType != TOK_LangType){
throw runtime_error("Unexpected token on line " + to_string(currentToken.lineNumber) + ": expected variable type after ':'.");
}
TYPE type = getType(currentToken.lexeme);
return new ASTIdentifierExpressionNode(identifier, type);
} | 34.414894 | 164 | 0.679815 | [
"vector"
] |
5c7fadd499e6c2987ed50365b84c53d2dc0a4150 | 1,157 | cpp | C++ | 10-arrays-and-vectors/10.32-optional-peoples-weights/solution.cpp | trangnart/cis22a | 498a7b37d12a13efa7749849dc95d9892d1786be | [
"MIT"
] | 2 | 2020-09-04T22:06:06.000Z | 2020-09-09T04:00:25.000Z | 10-arrays-and-vectors/10.32-optional-peoples-weights/solution.cpp | trangnart/cis22a | 498a7b37d12a13efa7749849dc95d9892d1786be | [
"MIT"
] | 14 | 2020-08-24T01:44:36.000Z | 2021-01-01T08:44:17.000Z | 10-arrays-and-vectors/10.32-optional-peoples-weights/solution.cpp | trangnart/cis22a | 498a7b37d12a13efa7749849dc95d9892d1786be | [
"MIT"
] | 1 | 2020-09-04T22:13:13.000Z | 2020-09-04T22:13:13.000Z | #include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
using namespace std;
void OutputStats(vector<double>& weights);
void ReadWeights(const string& filename, vector<double>& weights);
int main() {
const string FILENAME = "input.txt";
vector<double> weights;
ReadWeights(FILENAME, weights);
OutputStats(weights);
return 0;
}
void OutputStats(vector<double>& weights) {
double total = 0,
average,
max = 0;
for (auto w : weights) {
total += w;
if (w > max) {
max = w;
}
}
average = total / weights.size();
cout << fixed << setprecision(2);
cout << "Total weight: " << total << endl
<< "Average weight: " << average << endl
<< "Max weight: " << max << endl;
}
void ReadWeights(const string& filename, vector<double>& weights) {
ifstream inFS(filename);
if (inFS.is_open()) {
double weight;
while (!inFS.eof()) {
inFS >> weight;
if (!inFS.fail()) {
weights.push_back(weight);
}
}
inFS.close();
}
} | 22.25 | 67 | 0.548833 | [
"vector"
] |
5c828377c5539607796e55c705f5a3808d13d9d1 | 9,341 | cpp | C++ | native/rambo/CPU/rambo_wo_mkl.cpp | geexie/dpbench | 7d41409ded3c816f35003bc5aea071852bceb892 | [
"BSD-2-Clause"
] | 8 | 2021-03-26T15:17:58.000Z | 2022-01-21T21:56:19.000Z | native/rambo/CPU/rambo_wo_mkl.cpp | geexie/dpbench | 7d41409ded3c816f35003bc5aea071852bceb892 | [
"BSD-2-Clause"
] | 22 | 2021-03-30T21:20:57.000Z | 2022-02-22T13:42:17.000Z | native/rambo/CPU/rambo_wo_mkl.cpp | geexie/dpbench | 7d41409ded3c816f35003bc5aea071852bceb892 | [
"BSD-2-Clause"
] | 7 | 2021-03-23T11:00:43.000Z | 2022-02-02T12:28:55.000Z | /*
Copyright (c) 2020, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <vector>
#include <random>
using namespace std;
thread_local std::minstd_rand myRand;
const size_t SIZE3 = 4;
double genRand() {
return (double) rand() / RAND_MAX;
}
double genRandFast() {
return uniform_real_distribution<>(0.0, 1.0)(myRand);
}
vector<double> vectMultiply(vector<double> a, vector<double> b, size_t nPoints) {
size_t nOut = a.size() / nPoints / SIZE3;
vector<double> result(nPoints * nOut);
size_t idx2;
double res;
for(size_t i = 0; i < nPoints; i++) {
for(size_t j = 0; j < nOut; j++) {
idx2 = i * nOut + j;
res = a[idx2 * SIZE3] * b[idx2 * SIZE3];
for(size_t k = 1; k < SIZE3; k++) {
res -= a[idx2 * SIZE3 + k] * b[idx2 * SIZE3 + k];
}
result[idx2] = res;
}
}
return result;
}
vector<double> getMomentumSum(vector<double> inputParticles, size_t nPoints) {
size_t size2 = inputParticles.size() / nPoints / SIZE3;
vector<double> momentumSum(nPoints * SIZE3);
double sum;
size_t idx2;
for(size_t i = 0; i < nPoints; i++) {
for(size_t k = 0; k < SIZE3; k++) {
sum = 0.0;
for(size_t j = 0; j < size2; j++) {
idx2 = i * size2 + j;
sum += inputParticles[idx2 * SIZE3 + k];
}
momentumSum[i * SIZE3 + k] = sum;
}
}
return momentumSum;
}
vector<double> getMass(vector<double> inputParticles, size_t nPoints) {
vector<double> mass(nPoints);
double mom2, val;
for(size_t i = 0; i < nPoints; i++) {
mom2 = 0.0;
for(size_t k = 1; k < SIZE3; k++) {
val = inputParticles[i * SIZE3 + k];
mom2 += val * val;
}
val = inputParticles[i * SIZE3];
mass[i] = sqrt(val * val - mom2);
}
return mass;
}
vector<double> getCombinedMass(vector<double> inputParticles, size_t nPoints) {
vector<double> momentumSum = getMomentumSum(inputParticles, nPoints);
return getMass(momentumSum, nPoints);
}
vector<double> getInputs(int ecms, size_t nPoints) {
vector<double> pa = {ecms / 2.0, 0.0, 0.0, ecms / 2.0};
vector<double> pb = {ecms / 2.0, 0.0, 0.0, -ecms / 2.0};
size_t size2 = 2;
vector<double> inputParticles(nPoints * size2 * SIZE3);
size_t idx2;
for(size_t i = 0; i < nPoints; i++) {
idx2 = i * size2;
for(size_t k = 0; k < SIZE3; k++) {
inputParticles[idx2 * SIZE3 + k] = pa[k];
}
idx2 += 1;
for(size_t k = 0; k < SIZE3; k++) {
inputParticles[idx2 * SIZE3 + k] = pb[k];
}
}
return inputParticles;
}
vector<double> getOutputMom2(size_t nPoints, size_t nOut) {
vector<double> C1(nPoints * nOut);
vector<double> F1(nPoints * nOut);
vector<double> Q1(nPoints * nOut);
vector<double> output(nPoints * nOut * SIZE3);
size_t idx2;
for(size_t i = 0; i < nPoints; i++) {
for(size_t j = 0; j < nOut; j++) {
idx2 = i * nOut + j;
C1[idx2] = genRand();
F1[idx2] = genRand();
Q1[idx2] = genRand() * genRand();
}
}
double C, S, F, Q;
/* omp slows down the algorithm */
#pragma omp parallel for simd private(idx2, C, S, F, Q)
for(size_t i = 0; i < nPoints; i++) {
for(size_t j = 0; j < nOut; j++) {
idx2 = i * nOut + j;
C = 2.0 * C1[idx2] - 1.0;
S = sqrt(1 - C * C);
F = 2.0 * M_PI * F1[idx2];
Q = -log(Q1[idx2]);
output[idx2 * SIZE3] = Q;
output[idx2 * SIZE3 + 1] = Q * S * sin(F);
output[idx2 * SIZE3 + 2] = Q * S * cos(F);
output[idx2 * SIZE3 + 3] = Q * C;
}
}
return output;
}
vector<double> getOutputMom2Fast(size_t nPoints, size_t nOut) {
vector<double> output(nPoints * nOut * SIZE3);
#pragma omp parallel
{
myRand.seed(random_device()());
}
size_t idx2;
double C1, F1, Q1, C, S, F, Q;
#pragma omp parallel for simd private(idx2, C1, F1, Q1, C, S, F, Q)
for(size_t i = 0; i < nPoints; i++) {
for(size_t j = 0; j < nOut; j++) {
idx2 = i * nOut + j;
C1 = genRandFast();
F1 = genRandFast();
Q1 = genRandFast() * genRandFast();
C = 2.0 * C1 - 1.0;
S = sqrt(1 - C * C);
F = 2.0 * M_PI * F1;
Q = -log(Q1);
output[idx2 * SIZE3] = Q;
output[idx2 * SIZE3 + 1] = Q * S * sin(F);
output[idx2 * SIZE3 + 2] = Q * S * cos(F);
output[idx2 * SIZE3 + 3] = Q * C;
}
}
return output;
}
vector<double> generatePoints(size_t ecms, size_t nPoints, size_t nOut) {
vector<double> inputParticles = getInputs(ecms, nPoints);
vector<double> inputMass = getCombinedMass(inputParticles, nPoints);
vector<double> outputParticles = getOutputMom2(nPoints, nOut);
vector<double> outputMomSum = getMomentumSum(outputParticles, nPoints);
vector<double> outputMass = getMass(outputMomSum, nPoints);
double G, X, B, BQ, A, E, D, C1, C;
size_t inputParticlesSize2 = inputParticles.size() / nPoints / SIZE3;
size_t outputParticlesSize2 = outputParticles.size() / nPoints / SIZE3;
size_t pointsSize2 = inputParticlesSize2 + outputParticlesSize2;
vector<double> points(nPoints * pointsSize2 * SIZE3);
double val;
size_t idx2, idx3, pointsIdx2, pointsIdx3;
double res;
for(size_t i = 0; i < nPoints; i++) {
for(size_t j = 0; j < inputParticlesSize2; j++) {
idx2 = i * inputParticlesSize2 + j;
pointsIdx2 = i * pointsSize2 + j;
for(size_t k = 0; k < SIZE3; k++) {
idx3 = idx2 * SIZE3 + k;
pointsIdx3 = pointsIdx2 * SIZE3 + k;
points[pointsIdx3] = inputParticles[idx3];
}
}
for(size_t j = 0; j < nOut; j++) {
idx2 = i * nOut + j;
G = outputMomSum[i * SIZE3] / outputMass[i];
X = inputMass[i] / outputMass[i];
res = 0.0;
for(size_t k = 1; k < SIZE3; k++) {
idx3 = idx2 * SIZE3 + k;
B = -outputMomSum[i * SIZE3 + k] / outputMass[i];
res -= B * outputParticles[idx3];
}
BQ = -1.0 * res;
A = 1.0 / (1.0 + G);
E = outputParticles[idx2 * SIZE3];
D = G * E + BQ;
C1 = E + A * BQ;
pointsIdx2 = i * pointsSize2 + j + inputParticlesSize2;
pointsIdx3 = pointsIdx2 * SIZE3;
points[pointsIdx3] = X * D;
for(size_t k = 1; k < SIZE3; k++) {
idx3 = idx2 * SIZE3 + k;
pointsIdx3 = pointsIdx2 * SIZE3 + k;
B = -outputMomSum[i * SIZE3 + k] / outputMass[i];
C = outputParticles[idx3] + B * C1;
points[pointsIdx3] = X * C;
}
}
}
return points;
}
void rambo(size_t nPoints) {
size_t ecms = 100;
size_t nOut = 4;
vector<double> e = generatePoints(ecms, nPoints, nOut);
size_t eSize2 = e.size() / nPoints / SIZE3;
vector<double> h(SIZE3 * nPoints);
size_t idx2, idx3;
double max, val;
for(size_t i = 0; i < SIZE3; i++) {
for(size_t j = 0; j < nPoints; j++) {
idx2 = j * eSize2 + 2;
idx3 = idx2 * SIZE3 + i;
max = e[idx3];
for(size_t k = 3; k < 5; k++) {
idx2 = j * eSize2 + k;
idx3 = idx2 * SIZE3 + i;
val = e[idx3];
if(val > max) {
max = val;
}
}
h[i * nPoints + j] = max;
}
}
}
| 31.451178 | 81 | 0.554009 | [
"vector"
] |
5c82d68bca26821ca9ef9cc3c98e21ac941e7e4e | 566 | cpp | C++ | Graph/topSort.cpp | GajuuKool/DSA_CPP | c63b64783238680fcb97f908298c7378f9109063 | [
"MIT"
] | null | null | null | Graph/topSort.cpp | GajuuKool/DSA_CPP | c63b64783238680fcb97f908298c7378f9109063 | [
"MIT"
] | null | null | null | Graph/topSort.cpp | GajuuKool/DSA_CPP | c63b64783238680fcb97f908298c7378f9109063 | [
"MIT"
] | 4 | 2021-10-04T09:52:06.000Z | 2021-10-04T10:11:08.000Z | void DFS_Top(vector<int> adj[], int start, int &label, vector<bool> &visited, vector<int> &order)
{
visited[start] = true;
for(int v: adj[start])
if(!visited[v])
DFS_Top(adj,v,label,visited,order);
order[start] = label--;
}
vector<int> TopSort(vector<int> adj[], int n)
{
vector<bool> visited(n+1,false);
int label = n,i;
vector<int> order(n+1);
for(i = 1; i < n+1; i++)
if(!visited[i])
DFS_Top(adj,i,label,visited,order);
vector<int> ordered_nodes(n);
for(i = 1; i < n+1; i++)
ordered_nodes[order[i]-1] = i;
return ordered_nodes;
}
| 20.214286 | 97 | 0.627208 | [
"vector"
] |
5c861538c9553781541758299b9ad617a472a691 | 7,262 | cpp | C++ | src/ofxOpenCvDnnSegmentation.cpp | TetsuakiBaba/ofxOpenCvDnnSegmentation | f5f207de53ff82f4573e1381ed7c0277eca3f36b | [
"MIT"
] | 11 | 2019-07-13T16:53:35.000Z | 2022-01-06T11:12:24.000Z | src/ofxOpenCvDnnSegmentation.cpp | bemoregt/ofxOpenCvDnnSegmentation | f5f207de53ff82f4573e1381ed7c0277eca3f36b | [
"MIT"
] | 1 | 2020-09-03T17:18:52.000Z | 2021-07-27T01:33:37.000Z | src/ofxOpenCvDnnSegmentation.cpp | bemoregt/ofxOpenCvDnnSegmentation | f5f207de53ff82f4573e1381ed7c0277eca3f36b | [
"MIT"
] | 1 | 2019-07-15T13:21:15.000Z | 2019-07-15T13:21:15.000Z | #include "ofxOpenCvDnnSegmentation.h"
vector<string> split(string& input, char delimiter)
{
istringstream stream(input);
string field;
vector<string> result;
while (getline(stream, field, delimiter)) {
result.push_back(field);
}
return result;
}
ofxOpenCvDnnSegmentation::ofxOpenCvDnnSegmentation()
{
}
ofxOpenCvDnnSegmentation::~ofxOpenCvDnnSegmentation()
{
}
template <typename T>
static cv::Mat toCvMat(ofPixels_<T>& pix)
{
int depth;
switch(pix.getBytesPerChannel())
{
case 4: depth = CV_32F; break;
case 2: depth = CV_16U; break;
case 1: default: depth = CV_8U; break;
}
return cv::Mat(pix.getHeight(), pix.getWidth(), CV_MAKETYPE(depth, pix.getNumChannels()), pix.getData(), 0);
}
cv::Mat ofxOpenCvDnnSegmentation::toCV(ofPixels &pix)
{
return cv::Mat(pix.getHeight(), pix.getWidth(), CV_MAKETYPE(CV_8U, pix.getNumChannels()), pix.getData(), 0);
}
void ofxOpenCvDnnSegmentation::update(ofPixels &op)
{
if( image_segmented.isAllocated() ){
image_segmented.clear();
}
Mat img = toCvMat(op);
input_width = (int)op.getWidth();
input_height = (int)op.getHeight();
Mat blob;
Scalar *mean = new Scalar(0,0,0);
bool swapRB = false;
blobFromImage(img, blob, scale, cv::Size(network_width, network_height), *mean, swapRB, false);
net.setInput(blob);
Mat score = net.forward();
Mat segm;
colorizeSegmentation(score, segm);
image_segmented.allocate(network_width, network_height,
OF_IMAGE_COLOR);
unsigned char *pixels = new unsigned char[network_width*network_height*3];
int pos = 0;
for( int y = 0; y < segm.rows; y++ ) {
cv::Vec3b* ptr = segm.ptr<cv::Vec3b>( y );
for( int x = 0; x < segm.cols; x++ ) {
cv::Vec3b bgr = ptr[x];
pixels[pos] = bgr[2];pos++;
pixels[pos] = bgr[1];pos++;
pixels[pos] = bgr[0];pos++;
}
}
image_segmented.setFromPixels(pixels, network_width, network_height, OF_IMAGE_COLOR);
delete mean;
delete[] pixels;
}
void ofxOpenCvDnnSegmentation::colorizeSegmentation(const Mat &score, Mat &segm)
{
const int rows = score.size[2];
const int cols = score.size[3];
const int chns = score.size[1];
if (chns != (int)cv_colors.size())
{
CV_Error(Error::StsError, format("Number of output classes does not match "
"number of colors (%d != %d)", chns, cv_colors.size()));
}
Mat maxCl = Mat::zeros(rows, cols, CV_8UC1);
Mat maxVal(rows, cols, CV_32FC1, score.data);
for (int ch = 1; ch < chns; ch++)
{
for (int row = 0; row < rows; row++)
{
const float *ptrScore = score.ptr<float>(0, ch, row);
uint8_t *ptrMaxCl = maxCl.ptr<uint8_t>(row);
float *ptrMaxVal = maxVal.ptr<float>(row);
for (int col = 0; col < cols; col++)
{
if (ptrScore[col] > ptrMaxVal[col])
{
ptrMaxVal[col] = ptrScore[col];
ptrMaxCl[col] = (uchar)ch;
}
}
}
}
segm.create(rows, cols, CV_8UC3);
for (int row = 0; row < rows; row++)
{
const uchar *ptrMaxCl = maxCl.ptr<uchar>(row);
Vec3b *ptrSegm = segm.ptr<Vec3b>(row);
for (int col = 0; col < cols; col++)
{
ptrSegm[col] = cv_colors[ptrMaxCl[col]];
}
}
}
void ofxOpenCvDnnSegmentation::setup(string _path_to_weights,
string _path_to_classlist)
{
setup(_path_to_weights, "", _path_to_classlist);
}
void ofxOpenCvDnnSegmentation::setup(string _path_to_weights,
string _path_to_config,
string _path_to_classlist)
{
// read the network model
String modelBinary = _path_to_weights;
net = readNet(modelBinary,_path_to_config);
std::vector<String> lname = net.getLayerNames();
for (int i = 0; i < lname.size();i++) {
std::cout << i+1 << " " << lname[i] << std::endl;
}
ocl::setUseOpenCL( true );
net.setPreferableTarget(DNN_TARGET_CPU);
if (net.empty())
{
cout << "Can't load network by using the following files: " << endl;
cout << "model-file: " << modelBinary << endl;
}
// open class list file which includes rgb infomation
{
ifstream ifs(_path_to_classlist);
string line;
while (getline(ifs, line)) {
vector<string> strvec = split(line, ' ');
Vec3b color;
for (int i=1; i<strvec.size();i++){
color[strvec.size()-i-1] = ofToInt(strvec.at(i));
}
classes.push_back(strvec.at(0));
cv_colors.push_back(color);
colors.push_back(ofColor(color[2],color[1],color[0]));
}
}
contourFinder.setMinAreaRadius(10);
//contourFinder.setMaxAreaRadius(150);
targetColor = colors[1];
contourFinder.setTargetColor(targetColor, true ? TRACK_COLOR_HS : TRACK_COLOR_RGB);
contourFinder.setThreshold(0.5);
}
void ofxOpenCvDnnSegmentation::setNetworkImageSize(int _w, int _h)
{
network_width = _w;
network_height = _h;
}
void ofxOpenCvDnnSegmentation::drawColorPalette(int _x, int _y, int _w, int _h)
{
float w = _w;
float h = _h/(float)colors.size();
for( int i = 0; i < colors.size(); i++){
ofSetColor(colors[i]);
ofDrawRectangle(_x, _y+h*i, w, h);
ofSetColor(255);
ofDrawBitmapString(classes[i], _x, _y+h*i+14);
}
}
vector<ofPolyline> ofxOpenCvDnnSegmentation::getBlobs(int _class_number, float _threshold)
{
targetColor = colors[_class_number];
contourFinder.setTargetColor(targetColor, true ? TRACK_COLOR_HS : TRACK_COLOR_RGB);
contourFinder.setThreshold(_threshold);
contourFinder.findContours(image_segmented);
vector<ofPolyline> p;
cout << contourFinder.size() << endl;
if( contourFinder.size() > 0){
p = contourFinder.getPolylines();
}
return p;
}
void ofxOpenCvDnnSegmentation::drawClass(int _class_id, int _alpha,
int _x, int _y, int _w, int _h)
{
ofSetLineWidth(3);
int i = _class_id;
vector<ofPolyline>p = getBlobs(i,0);
for( int j = 0; j < p.size(); j++ ){
ofPushMatrix();
ofTranslate(_x, _y);
ofScale(_w/(float)network_width,_h/(float)network_height);
ofSetColor(ofColor::white);
p[j].draw();
ofSetColor(colors[i],_alpha);
ofBeginShape();
for( int k = 0; k < p[j].getVertices().size() ; k++){
ofVertex(p[j].getVertices()[k].x,p[j].getVertices()[k].y);
}
ofEndShape();
ofSetColor(ofColor::white);
ofDrawBitmapString(classes[i], p[j].getBoundingBox().getCenter());
ofPopMatrix();
}
}
void ofxOpenCvDnnSegmentation::draw(int _x, int _y, int _w, int _h)
{
image_segmented.draw(_x, _y, _w, _h);
}
| 28.478431 | 112 | 0.574497 | [
"vector",
"model"
] |
5c88c28a76f95b93b840facd2af4815dbc21be62 | 16,216 | cpp | C++ | lib/tlrGL/Mesh.cpp | darbyjohnston/tlRender | 0bdb8aa3795a0098811a7c3ed6add3023bcfd55a | [
"BSD-3-Clause"
] | 59 | 2021-04-26T23:38:35.000Z | 2022-03-23T15:21:44.000Z | lib/tlrGL/Mesh.cpp | darbyjohnston/tlRender | 0bdb8aa3795a0098811a7c3ed6add3023bcfd55a | [
"BSD-3-Clause"
] | 17 | 2021-04-30T02:03:08.000Z | 2022-01-11T19:54:47.000Z | lib/tlrGL/Mesh.cpp | darbyjohnston/tlRender | 0bdb8aa3795a0098811a7c3ed6add3023bcfd55a | [
"BSD-3-Clause"
] | 5 | 2021-06-07T16:11:53.000Z | 2021-12-10T23:29:45.000Z | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2021-2022 Darby Johnston
// All rights reserved.
#include <tlrGL/Mesh.h>
#include <tlrCore/Math.h>
#include <tlrCore/Mesh.h>
#include <array>
namespace tlr
{
namespace gl
{
namespace
{
struct PackedNormal
{
unsigned int x : 10;
unsigned int y : 10;
unsigned int z : 10;
unsigned int unused : 2;
};
struct PackedColor
{
unsigned int r : 8;
unsigned int g : 8;
unsigned int b : 8;
unsigned int a : 8;
};
}
std::size_t getByteCount(VBOType value)
{
const std::array<size_t, static_cast<size_t>(VBOType::Count)> data =
{
12, // 2 * sizeof(float) + 2 * sizeof(uint16_t)
12, // 3 * sizeof(float)
16, // 3 * sizeof(float) + 2 * sizeof(uint16_t)
20, // 3 * sizeof(float) + 2 * sizeof(uint16_t) + sizeof(PackedNormal)
24, // 3 * sizeof(float) + 2 * sizeof(uint16_t) + sizeof(PackedNormal) + sizeof(PackedColor)
32, // 3 * sizeof(float) + 2 * sizeof(float) + 3 * sizeof(float)
44, // 3 * sizeof(float) + 2 * sizeof(float) + 3 * sizeof(float) + 3 * sizeof(float)
16 // 3 * sizeof(float) + sizeof(PackedColor)
};
return data[static_cast<size_t>(value)];
}
std::vector<uint8_t> convert(
const geom::TriangleMesh3& mesh,
gl::VBOType type,
const math::SizeTRange& range)
{
const size_t vertexByteCount = gl::getByteCount(type);
std::vector<uint8_t> out((range.getMax() - range.getMin() + 1) * 3 * vertexByteCount);
uint8_t* p = out.data();
switch (type)
{
case gl::VBOType::Pos3_F32_UV_U16:
for (size_t i = range.getMin(); i <= range.getMax(); ++i)
{
const geom::Vertex3* vertices[] =
{
&mesh.triangles[i].v[0],
&mesh.triangles[i].v[1],
&mesh.triangles[i].v[2]
};
for (size_t k = 0; k < 3; ++k)
{
const size_t v = vertices[k]->v;
float* pf = reinterpret_cast<float*>(p);
pf[0] = v ? mesh.v[v - 1].x : 0.F;
pf[1] = v ? mesh.v[v - 1].y : 0.F;
pf[2] = v ? mesh.v[v - 1].z : 0.F;
p += 3 * sizeof(float);
const size_t t = vertices[k]->t;
uint16_t* pu16 = reinterpret_cast<uint16_t*>(p);
pu16[0] = t ? math::clamp(static_cast<int>(mesh.t[t - 1].x * 65535.F), 0, 65535) : 0;
pu16[1] = t ? math::clamp(static_cast<int>(mesh.t[t - 1].y * 65535.F), 0, 65535) : 0;
p += 2 * sizeof(uint16_t);
}
}
break;
case gl::VBOType::Pos3_F32_UV_U16_Normal_U10:
for (size_t i = range.getMin(); i <= range.getMax(); ++i)
{
const geom::Vertex3* vertices[] =
{
&mesh.triangles[i].v[0],
&mesh.triangles[i].v[1],
&mesh.triangles[i].v[2]
};
for (size_t k = 0; k < 3; ++k)
{
const size_t v = vertices[k]->v;
float* pf = reinterpret_cast<float*>(p);
pf[0] = v ? mesh.v[v - 1].x : 0.F;
pf[1] = v ? mesh.v[v - 1].y : 0.F;
pf[2] = v ? mesh.v[v - 1].z : 0.F;
p += 3 * sizeof(float);
const size_t t = vertices[k]->t;
uint16_t* pu16 = reinterpret_cast<uint16_t*>(p);
pu16[0] = t ? math::clamp(static_cast<int>(mesh.t[t - 1].x * 65535.F), 0, 65535) : 0;
pu16[1] = t ? math::clamp(static_cast<int>(mesh.t[t - 1].y * 65535.F), 0, 65535) : 0;
p += 2 * sizeof(uint16_t);
const size_t n = vertices[k]->n;
auto packedNormal = reinterpret_cast<PackedNormal*>(p);
packedNormal->x = n ? math::clamp(static_cast<int>(mesh.n[n - 1].x * 511.F), -512, 511) : 0;
packedNormal->y = n ? math::clamp(static_cast<int>(mesh.n[n - 1].y * 511.F), -512, 511) : 0;
packedNormal->z = n ? math::clamp(static_cast<int>(mesh.n[n - 1].z * 511.F), -512, 511) : 0;
p += sizeof(PackedNormal);
}
}
break;
case gl::VBOType::Pos3_F32_UV_U16_Normal_U10_Color_U8:
for (size_t i = range.getMin(); i <= range.getMax(); ++i)
{
const geom::Vertex3* vertices[] =
{
&mesh.triangles[i].v[0],
&mesh.triangles[i].v[1],
&mesh.triangles[i].v[2]
};
for (size_t k = 0; k < 3; ++k)
{
const size_t v = vertices[k]->v;
float* pf = reinterpret_cast<float*>(p);
pf[0] = v ? mesh.v[v - 1].x : 0.F;
pf[1] = v ? mesh.v[v - 1].y : 0.F;
pf[2] = v ? mesh.v[v - 1].z : 0.F;
p += 3 * sizeof(float);
const size_t t = vertices[k]->t;
uint16_t* pu16 = reinterpret_cast<uint16_t*>(p);
pu16[0] = t ? math::clamp(static_cast<int>(mesh.t[t - 1].x * 65535.F), 0, 65535) : 0;
pu16[1] = t ? math::clamp(static_cast<int>(mesh.t[t - 1].y * 65535.F), 0, 65535) : 0;
p += 2 * sizeof(uint16_t);
const size_t n = vertices[k]->n;
auto packedNormal = reinterpret_cast<PackedNormal*>(p);
packedNormal->x = n ? math::clamp(static_cast<int>(mesh.n[n - 1].x * 511.F), -512, 511) : 0;
packedNormal->y = n ? math::clamp(static_cast<int>(mesh.n[n - 1].y * 511.F), -512, 511) : 0;
packedNormal->z = n ? math::clamp(static_cast<int>(mesh.n[n - 1].z * 511.F), -512, 511) : 0;
p += sizeof(PackedNormal);
auto packedColor = reinterpret_cast<PackedColor*>(p);
packedColor->r = v ? math::clamp(static_cast<int>(mesh.c[v - 1].x * 255.F), 0, 255) : 0;
packedColor->g = v ? math::clamp(static_cast<int>(mesh.c[v - 1].y * 255.F), 0, 255) : 0;
packedColor->b = v ? math::clamp(static_cast<int>(mesh.c[v - 1].z * 255.F), 0, 255) : 0;
packedColor->a = 255;
p += sizeof(PackedColor);
}
}
break;
case gl::VBOType::Pos3_F32_UV_F32_Normal_F32:
for (size_t i = range.getMin(); i <= range.getMax(); ++i)
{
const geom::Vertex3* vertices[] =
{
&mesh.triangles[i].v[0],
&mesh.triangles[i].v[1],
&mesh.triangles[i].v[2]
};
for (size_t k = 0; k < 3; ++k)
{
const size_t v = vertices[k]->v;
float* pf = reinterpret_cast<float*>(p);
pf[0] = v ? mesh.v[v - 1].x : 0.F;
pf[1] = v ? mesh.v[v - 1].y : 0.F;
pf[2] = v ? mesh.v[v - 1].z : 0.F;
p += 3 * sizeof(float);
const size_t t = vertices[k]->t;
pf = reinterpret_cast<float*>(p);
pf[0] = t ? mesh.t[t - 1].x : 0.F;
pf[1] = t ? mesh.t[t - 1].y : 0.F;
p += 2 * sizeof(float);
const size_t n = vertices[k]->n;
pf = reinterpret_cast<float*>(p);
pf[0] = n ? mesh.n[n - 1].x : 0.F;
pf[1] = n ? mesh.n[n - 1].y : 0.F;
pf[2] = n ? mesh.n[n - 1].z : 0.F;
p += 3 * sizeof(float);
}
}
break;
case gl::VBOType::Pos3_F32_UV_F32_Normal_F32_Color_F32:
for (size_t i = range.getMin(); i <= range.getMax(); ++i)
{
const geom::Vertex3* vertices[] =
{
&mesh.triangles[i].v[0],
&mesh.triangles[i].v[1],
&mesh.triangles[i].v[2]
};
for (size_t k = 0; k < 3; ++k)
{
const size_t v = vertices[k]->v;
float* pf = reinterpret_cast<float*>(p);
pf[0] = v ? mesh.v[v - 1].x : 0.F;
pf[1] = v ? mesh.v[v - 1].y : 0.F;
pf[2] = v ? mesh.v[v - 1].z : 0.F;
p += 3 * sizeof(float);
const size_t t = vertices[k]->t;
pf = reinterpret_cast<float*>(p);
pf[0] = t ? mesh.t[t - 1].x : 0.F;
pf[1] = t ? mesh.t[t - 1].y : 0.F;
p += 2 * sizeof(float);
const size_t n = vertices[k]->n;
pf = reinterpret_cast<float*>(p);
pf[0] = n ? mesh.n[n - 1].x : 0.F;
pf[1] = n ? mesh.n[n - 1].y : 0.F;
pf[2] = n ? mesh.n[n - 1].z : 0.F;
p += 3 * sizeof(float);
pf = reinterpret_cast<float*>(p);
pf[0] = v ? mesh.c[v - 1].x : 1.F;
pf[1] = v ? mesh.c[v - 1].y : 1.F;
pf[2] = v ? mesh.c[v - 1].z : 1.F;
p += 3 * sizeof(float);
}
}
break;
default: break;
}
return out;
}
void VBO::_init(std::size_t size, VBOType type)
{
_size = size;
_type = type;
glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizei>(_size * getByteCount(type)), NULL, GL_DYNAMIC_DRAW);
}
VBO::VBO()
{}
VBO::~VBO()
{
if (_vbo)
{
glDeleteBuffers(1, &_vbo);
_vbo = 0;
}
}
std::shared_ptr<VBO> VBO::create(std::size_t size, VBOType type)
{
auto out = std::shared_ptr<VBO>(new VBO);
out->_init(size, type);
return out;
}
size_t VBO::getSize() const
{
return _size;
}
VBOType VBO::getType() const
{
return _type;
}
GLuint VBO::getID() const
{
return _vbo;
}
GLuint VAO::getID() const
{
return _vao;
}
void VBO::copy(const std::vector<uint8_t>& data)
{
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, static_cast<GLsizei>(data.size()), (void*)data.data());
}
void VBO::copy(const std::vector<uint8_t>& data, std::size_t offset)
{
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferSubData(GL_ARRAY_BUFFER, offset, static_cast<GLsizei>(data.size()), (void*)data.data());
}
void VBO::copy(const std::vector<uint8_t>& data, std::size_t offset, std::size_t size)
{
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferSubData(GL_ARRAY_BUFFER, offset, static_cast<GLsizei>(size), (void*)data.data());
}
void VAO::_init(VBOType type, GLuint vbo)
{
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
const std::size_t byteCount = getByteCount(type);
switch (type)
{
case VBOType::Pos2_F32_UV_U16:
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_UNSIGNED_SHORT, GL_TRUE, static_cast<GLsizei>(byteCount), (GLvoid*)8);
glEnableVertexAttribArray(1);
break;
case VBOType::Pos3_F32:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)0);
glEnableVertexAttribArray(0);
break;
case VBOType::Pos3_F32_UV_U16:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_UNSIGNED_SHORT, GL_TRUE, static_cast<GLsizei>(byteCount), (GLvoid*)12);
glEnableVertexAttribArray(1);
break;
case VBOType::Pos3_F32_UV_F32_Normal_F32:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)12);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)20);
glEnableVertexAttribArray(2);
break;
case VBOType::Pos3_F32_UV_F32_Normal_F32_Color_F32:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)12);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)20);
glEnableVertexAttribArray(2);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)32);
glEnableVertexAttribArray(3);
break;
case VBOType::Pos3_F32_Color_U8:
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, static_cast<GLsizei>(byteCount), (GLvoid*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, static_cast<GLsizei>(byteCount), (GLvoid*)12);
glEnableVertexAttribArray(1);
break;
default: break;
}
}
VAO::VAO()
{}
VAO::~VAO()
{
if (_vao)
{
glDeleteVertexArrays(1, &_vao);
_vao = 0;
}
}
std::shared_ptr<VAO> VAO::create(VBOType type, GLuint vbo)
{
auto out = std::shared_ptr<VAO>(new VAO);
out->_init(type, vbo);
return out;
}
void VAO::bind()
{
glBindVertexArray(_vao);
}
void VAO::draw(GLenum mode, std::size_t offset, std::size_t size)
{
glDrawArrays(mode, static_cast<GLsizei>(offset), static_cast<GLsizei>(size));
}
}
}
| 42.119481 | 118 | 0.435126 | [
"mesh",
"vector"
] |
5c99ccf7cd05a93555101f78c6b560f25f2d827b | 2,231 | cpp | C++ | test/tests/frame_test.cpp | pkuehne/fortress | 1fac97edcb47b4dd6bf65f553585c22d0cd2e4de | [
"MIT"
] | null | null | null | test/tests/frame_test.cpp | pkuehne/fortress | 1fac97edcb47b4dd6bf65f553585c22d0cd2e4de | [
"MIT"
] | 118 | 2015-08-03T08:06:53.000Z | 2022-01-13T17:26:00.000Z | test/tests/frame_test.cpp | pkuehne/fortress | 1fac97edcb47b4dd6bf65f553585c22d0cd2e4de | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "../../src/windows/frame.h"
#include "../mocks/widget_mock.h"
using namespace ::testing;
TEST(Frame, realignCalledForChildren) {
unsigned int x = 5;
unsigned int y = 7;
unsigned int width = 100;
unsigned int height = 200;
Frame frame;
WidgetMock mock;
frame.addChild(&mock);
frame.setWidth(width);
frame.setHeight(height);
EXPECT_CALL(mock, realign(Eq(x), Eq(y), Eq(width), Eq(height)));
frame.realign(x, y, width, height);
}
TEST(Frame, realignAccountsForBorderWidth) {
unsigned int x = 5;
unsigned int y = 7;
unsigned int width = 100;
unsigned int height = 200;
Frame frame;
WidgetMock mock;
frame.setBorder();
frame.addChild(&mock);
frame.setWidth(width);
frame.setHeight(height);
EXPECT_CALL(mock,
realign(Eq(x + 1), Eq(y + 1), Eq(width - 2), Eq(height - 2)));
frame.realign(x, y, width, height);
}
TEST(Frame, realignAccountsForMargin) {
unsigned int x = 5;
unsigned int y = 7;
unsigned int width = 100;
unsigned int height = 200;
Frame frame;
WidgetMock mock;
frame.setMargin();
frame.addChild(&mock);
frame.setWidth(width);
frame.setHeight(height);
EXPECT_CALL(mock,
realign(Eq(x + 1), Eq(y + 1), Eq(width - 2), Eq(height - 2)));
frame.realign(x, y, width, height);
}
TEST(Frame, renderPassedDownToChildren) {
Frame frame;
WidgetMock mock;
frame.addChild(&mock);
EXPECT_CALL(mock, render());
frame.render();
}
TEST(Frame, keyPressPassedDownToChildren) {
Frame frame;
WidgetMock mock;
frame.addChild(&mock);
unsigned char key = '@';
EXPECT_CALL(mock, keyPress(Eq(key)));
frame.keyPress(key);
}
TEST(Frame, MergeBordersIgnoresOffsetsForOtherFrames) {
Frame frame;
Frame subFrame;
frame.setBorder();
frame.setMargin();
frame.setMergeBorders();
frame.addChild(&subFrame);
unsigned int x = 5;
unsigned int y = 7;
unsigned int width = 100;
unsigned int height = 200;
frame.realign(x, y, width, height);
EXPECT_EQ(subFrame.getXPos(), frame.getXPos());
EXPECT_EQ(subFrame.getYPos(), frame.getYPos());
} | 21.247619 | 78 | 0.632004 | [
"render"
] |
5c9a08276c848273a45266ae99da64ac93f2fb88 | 3,592 | cpp | C++ | src/pre-commit-hook/main.cpp | HuuugeGames/Lucy | 020b8e6d3ba4605bfc65a29c5072c9643ebd8c43 | [
"Apache-2.0"
] | null | null | null | src/pre-commit-hook/main.cpp | HuuugeGames/Lucy | 020b8e6d3ba4605bfc65a29c5072c9643ebd8c43 | [
"Apache-2.0"
] | null | null | null | src/pre-commit-hook/main.cpp | HuuugeGames/Lucy | 020b8e6d3ba4605bfc65a29c5072c9643ebd8c43 | [
"Apache-2.0"
] | null | null | null | #include <sys/select.h>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string_view>
#include <unistd.h>
#include <vector>
#include "Config.hpp"
#include "Git.hpp"
#include "Job.hpp"
std::vector <std::string> collectFilenames(git_diff *diff)
{
std::vector <std::string> result;
auto fileCallback = [](const git_diff_delta *delta, float, void *payload) -> int
{
if (delta->status != GIT_DELTA_ADDED && delta->status != GIT_DELTA_MODIFIED)
return 0;
std::string_view filename{delta->new_file.path};
const char extension[] = ".lua";
if (filename.size() < sizeof(extension) || strcmp(extension, &filename[filename.size() - sizeof(extension) + 1]) != 0)
return 0;
auto fileList = reinterpret_cast<std::vector <std::string> *>(payload);
fileList->emplace_back(filename);
return 0;
};
git_diff_foreach(diff, fileCallback, nullptr, nullptr, nullptr, &result);
return result;
}
int processFiles(const Config &cfg, std::vector <std::string> &files, git_repository *repo)
{
assert(cfg.maxParallelJobs != 0);
enum { OK = 0, LucyCheck = 1, LucyFail = 2, Internal = 4 }; //TODO
auto repoIndex = git::execute("index", &git_repository_index, repo);
int errCode = 0;
unsigned int runningJobs = 0;
std::vector <Job> jobs{cfg.maxParallelJobs};
while (runningJobs != 0 || !files.empty()) {
while (!files.empty() && runningJobs < cfg.maxParallelJobs) {
size_t i = 0;
while (jobs[i].state() != Job::State::Init)
++i;
if (!jobs[i].start(cfg, std::move(files.back()), repo, repoIndex.get()))
return Internal;
files.pop_back();
++runningJobs;
}
fd_set readFds, writeFds;
int maxFd = 0;
FD_ZERO(&readFds);
FD_ZERO(&writeFds);
for (const auto &j : jobs) {
if (j.state() == Job::State::Working) {
FD_SET(j.readFd(), &readFds);
maxFd = std::max(maxFd, j.readFd());
if (j.shouldWrite()) {
FD_SET(j.writeFd(), &writeFds);
maxFd = std::max(maxFd, j.writeFd());
}
}
}
if (select(maxFd + 1, &readFds, &writeFds, nullptr, nullptr) == -1) {
perror("select");
return Internal;
}
for (auto &j : jobs) {
if (j.state() != Job::State::Working)
continue;
if (FD_ISSET(j.readFd(), &readFds)) {
j.read();
if (j.state() == Job::State::Finished) {
printf("[Checking file: %s]\n", j.filename().c_str());
if (!j.output().empty()) {
errCode |= LucyCheck;
printf("%s\n", j.output().c_str());
}
const int status = j.exitStatus();
if (WIFEXITED(status)) {
const int exitStatus = WEXITSTATUS(status);
if (exitStatus != 0) {
errCode |= LucyCheck;
printf("Job exited with code %d\n", exitStatus);
}
}
if (WIFSIGNALED(status)) {
errCode |= LucyFail;
printf("Job killed with signal %d\n", WTERMSIG(status));
}
j.reset();
--runningJobs;
continue;
}
}
if (j.shouldWrite() && FD_ISSET(j.writeFd(), &writeFds))
j.write();
}
}
return errCode;
}
int main(int argc, char **argv)
{
git_libgit2_init();
atexit([]{git_libgit2_shutdown();});
auto repo = git::execute("open repo", &git_repository_open, ".");
auto head = git::getTree(repo, "HEAD^{tree}");
git_diff_options diffOpts = GIT_DIFF_OPTIONS_INIT;
auto diff = git::execute("diff", &git_diff_tree_to_index, repo.get(), head.get(), nullptr, &diffOpts);
auto files = collectFilenames(diff.get());
auto index = git::execute("index", &git_repository_index, repo.get());
Config cfg;
if (!cfg.parse(argc, argv))
return 1;
return processFiles(cfg, files, repo.get());
}
| 25.295775 | 120 | 0.629733 | [
"vector"
] |
5c9bb5cf02a9737697dccfe7e7672941cdc2cdea | 16,144 | cpp | C++ | src/run_recover.cpp | rwtourdot/mlinker | 406c18a4727a16739d6300f08e218aec4779be97 | [
"MIT"
] | 1 | 2021-08-24T15:35:40.000Z | 2021-08-24T15:35:40.000Z | src/run_recover.cpp | rwtourdot/mlinker | 406c18a4727a16739d6300f08e218aec4779be97 | [
"MIT"
] | 1 | 2021-08-10T02:58:45.000Z | 2021-08-10T20:23:19.000Z | src/run_recover.cpp | rwtourdot/mlinker | 406c18a4727a16739d6300f08e218aec4779be97 | [
"MIT"
] | 2 | 2021-03-18T16:03:56.000Z | 2021-03-18T16:05:41.000Z | #include "run_recover.h"
/////////////// namespaces ///////////////////
namespace opt {
static std::string chr_choice = "chr20";
static std::string input_scaffold_file = "./output/hap_full_scaffold_oct7_K562_chr20.dat";
static std::string input_graph_file = "./output/graph_variant_oct3_K562_bam1_tenx_chr20.dat";
static std::string id_string = "default";
static std::string technology = "tenx";
};
/////////////// structures ///////////////////
static const char* shortopts = "ho:i:g:c:n:e:";
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "scaf-file", no_argument, NULL, 'i' },
{ "graph-file", no_argument, NULL, 'g' },
{ "chr-choice", no_argument, NULL, 'c' },
{ "tech", no_argument, NULL, 'e' },
{ "id_string", no_argument, NULL, 'n' }
};
///////////////////////////////////////////////////////////////////////////////////////////////////////
static const char *RECOVER_USAGE_MESSAGE =
"Usage: mlinker recover [OPTION] -i /output/hap_full_scaffold_*chr4.dat -g /output/graph_variant_*chr4.dat -c chr4 \n\n"
"\n"
"********* this command is set up for hg38 *********"
"\n"
" Options\n"
" -i, input scaffold path \n"
" -g, input graph file \n"
" -c, chromosome name ( chr4 ) or contig name depending on bam \n"
" -e, technology ( tenx, hic, nanopore ) \n"
" -n, id string for output files \n"
"\n";
///////////////////////////////////////////////////////////////////////////////////////////////////////
static void parse_recover_options( int argc, char** argv ) {
bool die = false; //bool vcf_load = false; //bool cov_load = false; //if(argc <= 2) { die = true; }
if (argc < 2) {
std::cerr << "\n" << RECOVER_USAGE_MESSAGE;
exit(1);
}
if (string(argv[1]) == "help" || string(argv[1]) == "--help") {
std::cerr << "\n" << RECOVER_USAGE_MESSAGE;
exit(1);
}
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case 'h': die = true; break;
case 'i': arg >> opt::input_scaffold_file; break;
case 'g': arg >> opt::input_graph_file; break;
case 'c': arg >> opt::chr_choice; break;
case 'e': arg >> opt::technology; break;
case 'n': arg >> opt::id_string; break;
}
}
if (die) {
std::cerr << "\n" << RECOVER_USAGE_MESSAGE;
exit(1);
}
cout << endl;
cout << "############### running recover ############### " << endl;
cout << "== chromosome === " << opt::chr_choice << endl;
cout << "== input scaf file === " << opt::input_scaffold_file << endl;
cout << "== input graph file === " << opt::input_graph_file << endl;
cout << "== id string === " << opt::id_string << endl;
cout << "== technology === " << opt::technology << endl;
cout << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx " << endl;
cout << endl;
};
void recover_links( std::string chr_choice, coord_dictionary& pdict, variant_graph& vgraph, std::unordered_map<std::string,read_tree>& rgraph, std::string technology, coord_dictionary& rdict, std::string scaffoldsolutionFile, std::map<int,recovered_node>& recovered_map ) {
std::map<int,std::string> ref_position_map;
std::map<int,std::string> alt_position_map;
std::unordered_map<int,int> scaffold_map;
for (auto& it : vgraph) {
int vpos = it.second.pos;
if (it.second.var) {
ref_position_map[vpos] = it.second.ref_base;
alt_position_map[vpos] = it.second.var_base;
}
ptrdiff_t i = get_index_var( pdict.double_positions, vpos );
int index = i;
if (index < pdict.double_positions.size() ) { scaffold_map[vpos] = index; }
else { scaffold_map[vpos] = -1; }
}
std::unordered_map<int,std::string> ab_hap = {{1,"A"},{-1,"B"}};
int max_delta_p;
if ( technology == "tenx" ) { max_delta_p = 100000; }
else if ( technology == "hic" ) { max_delta_p = 10000000; }
else if ( technology == "nanopore" ) { max_delta_p = 1000000; }
cout << "maximum delta pos: " << max_delta_p << endl;
//#############################################
//#############################################
for (auto& it : ref_position_map) {
int pos1 = it.first;
int hap1 = 0;
int ref_numA,ref_numB,alt_numA,alt_numB;
int ref_numA_hashcall,ref_numB_hashcall,alt_numA_hashcall,alt_numB_hashcall;
vector<std::string> ref_bx_listA,alt_bx_listA,ref_bx_listB,alt_bx_listB;
vector<int> upos_ref_listA,upos_alt_listA,upos_ref_listB,upos_alt_listB;
ref_numA = 0; ref_numB = 0; alt_numA = 0; alt_numB = 0;
ref_numA_hashcall = 0; ref_numB_hashcall = 0; alt_numA_hashcall = 0; alt_numB_hashcall = 0;
//////////////////////////////////////////////////////////
std::string ref_base = ref_position_map[pos1];
std::string alt_base = alt_position_map[pos1];
std::string ref_hash = std::to_string(pos1) + "_" + ref_base + "_" + ref_base; // pdict.ref_handle[i];
std::string alt_hash = std::to_string(pos1) + "_" + ref_base + "_" + alt_base;
//////////////////////////////////////////////////////////
int i = scaffold_map[pos1];
bool in_scaffold = false;
if (i >= 0 ) { hap1 = pdict.haplotype[i]; in_scaffold = true; }
for (int l=0; l < vgraph[ref_hash].connected_reads_long_form.size(); l++) {
std::string hash_tag = vgraph[ref_hash].connected_reads_long_form[l];
std::map<std::string,int> hash_hap_count; hash_hap_count["A"] = 0; hash_hap_count["B"] = 0;
for (int m=0; m < rgraph[vgraph[ref_hash].connected_reads_long_form[l]].connected_strings.size(); m++) {
std::string connected_het = rgraph[vgraph[ref_hash].connected_reads_long_form[l]].connected_strings[m];
//cout << l << "\t" << connected_het << "\t" << vgraph[ref_hash].connected_reads_long_form[l] << "\t" << endl;
if (connected_het != ref_hash) {
int j = scaffold_map[vgraph[connected_het].pos];
if (j >= 0) {
int pos2 = vgraph[connected_het].pos;
std::string temp_string = split_string_first(connected_het,"_",1);
std::string ref_base = split_string_first(temp_string,"_",0);
std::string cnx_base = split_string_first(temp_string,"_",1);
int is_variant = -1; if (ref_base != cnx_base) { is_variant = 1; }
int hap2 = pdict.haplotype[j];
int call_allele = hap2*is_variant;
int diffp = std::abs( pos1 - pos2 );
if ( diffp < max_delta_p ) {
if ( ab_hap[call_allele] == "A" ) { ref_numA += 1; upos_ref_listA.push_back(pos2); ref_bx_listA.push_back(hash_tag); hash_hap_count["A"] += 1;}
if ( ab_hap[call_allele] == "B" ) { ref_numB += 1; upos_ref_listB.push_back(pos2); ref_bx_listB.push_back(hash_tag); hash_hap_count["B"] += 1;}
}
}
}
}
cout << ref_hash << "\t" << hash_tag << "\t" << hash_hap_count["A"] << "\t" << hash_hap_count["B"] << endl;
if (hash_hap_count["A"] > hash_hap_count["B"]) { ref_numA_hashcall += 1; }
if (hash_hap_count["B"] > hash_hap_count["A"]) { ref_numB_hashcall += 1; }
}
for (int l=0; l < vgraph[alt_hash].connected_reads_long_form.size(); l++) {
std::string hash_tag = vgraph[alt_hash].connected_reads_long_form[l];
std::map<std::string,int> hash_hap_count; hash_hap_count["A"] = 0; hash_hap_count["B"] = 0;
for (int m=0; m < rgraph[vgraph[alt_hash].connected_reads_long_form[l]].connected_strings.size(); m++) {
std::string connected_het = rgraph[vgraph[alt_hash].connected_reads_long_form[l]].connected_strings[m];
//cout << l << "\t" << connected_het << "\t" << vgraph[alt_hash].connected_reads_long_form[l] << "\t" << endl;
if (connected_het != ref_hash) {
int j = scaffold_map[vgraph[connected_het].pos];
if (j >= 0) {
int pos2 = vgraph[connected_het].pos;
std::string temp_string = split_string_first(connected_het,"_",1);
std::string ref_base = split_string_first(temp_string,"_",0);
std::string cnx_base = split_string_first(temp_string,"_",1);
int is_variant = -1; if (ref_base != cnx_base) { is_variant = 1; }
int hap2 = pdict.haplotype[j];
int call_allele = hap2*is_variant;
int diffp = std::abs( pos1 - pos2 );
if ( diffp < max_delta_p ) {
if ( ab_hap[call_allele] == "A" ) { alt_numA += 1; upos_alt_listA.push_back(pos2); alt_bx_listA.push_back(hash_tag); hash_hap_count["A"] += 1;}
if ( ab_hap[call_allele] == "B" ) { alt_numB += 1; upos_alt_listB.push_back(pos2); alt_bx_listB.push_back(hash_tag); hash_hap_count["B"] += 1;}
}
}
}
}
cout << alt_hash << "\t" << hash_tag << "\t" << hash_hap_count["A"] << "\t" << hash_hap_count["B"] << endl;
if (hash_hap_count["A"] > hash_hap_count["B"]) { alt_numA_hashcall += 1; }
if (hash_hap_count["B"] > hash_hap_count["A"]) { alt_numB_hashcall += 1; }
}
std::set<int> set_upos_alt_listA(upos_alt_listA.begin(), upos_alt_listA.end());
std::set<int> set_upos_alt_listB(upos_alt_listB.begin(), upos_alt_listB.end());
std::set<int> set_upos_ref_listA(upos_ref_listA.begin(), upos_ref_listA.end());
std::set<int> set_upos_ref_listB(upos_ref_listB.begin(), upos_ref_listB.end());
std::set<std::string> set_ref_bx_listA(ref_bx_listA.begin(), ref_bx_listA.end());
std::set<std::string> set_ref_bx_listB(ref_bx_listB.begin(), ref_bx_listB.end());
std::set<std::string> set_alt_bx_listA(alt_bx_listA.begin(), alt_bx_listA.end());
std::set<std::string> set_alt_bx_listB(alt_bx_listB.begin(), alt_bx_listB.end());
//////////////////////////////////////////////////////////
recovered_node rnode;
rnode.pos = pos1;
rnode.hap = hap1;
rnode.ref_numA = ref_numA; rnode.ref_numB = ref_numB;
rnode.alt_numA = alt_numA; rnode.alt_numB = alt_numB;
rnode.ref_numA_hashcall = ref_numA_hashcall; rnode.ref_numB_hashcall = ref_numB_hashcall;
rnode.alt_numA_hashcall = alt_numA_hashcall; rnode.alt_numB_hashcall = alt_numB_hashcall;
rnode.upos_ref_numA = set_upos_ref_listA.size();
rnode.upos_ref_numB = set_upos_ref_listB.size();
rnode.upos_alt_numA = set_upos_alt_listA.size();
rnode.upos_alt_numB = set_upos_alt_listB.size();
rnode.bx_ref_numA = set_ref_bx_listA.size();
rnode.bx_ref_numB = set_ref_bx_listB.size();
rnode.bx_alt_numA = set_alt_bx_listA.size();
rnode.bx_alt_numB = set_alt_bx_listB.size();
recovered_map[pos1] = rnode;
//cout << pos1 << "\t" << hap1 << "\t" << ref_numA << "\t" << ref_numB << "\t" << alt_numA << "\t" << alt_numB << "\t" << upos_ref_numA << "\t" << upos_ref_numB << "\t" << upos_alt_numA << "\t" << upos_alt_numB << "\t" << bx_ref_numA << "\t" << bx_ref_numB << "\t" << bx_alt_numA << "\t" << bx_alt_numB << endl;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void run_recover( int argc, char** argv ) {
parse_recover_options(argc, argv);
std::string recoveredsolutionFile = "./output/hap_recovered_" + opt::id_string + "_" + opt::chr_choice + ".dat";
cout << "- output recovered file: " << recoveredsolutionFile << endl;
cout << endl;
// ############################### load hap solution and hic links ###########################
coord_dictionary pdict;
cout << "reading scaffold file: " << opt::input_scaffold_file << endl;
read_scaffold( opt::input_scaffold_file, pdict );
//#############################################
read_graph rgraph;
variant_graph vgraph;
cout << "reading graph file: " << opt::input_graph_file << endl;
read_variant_graph_file( opt::input_graph_file, opt::chr_choice, vgraph, rgraph );
//cout << "linking hashes" << endl;
//link_hashes( vgraph, rgraph );
//prune_graph( vgraph );
for ( auto& it : vgraph ) { it.second.unique_hash(); }
coord_dictionary rdict;
initialize_pdict( vgraph, rdict, false );
cout << "making recovered dict" << endl;
std::map<int,recovered_node> recovered_map;
recover_links( opt::chr_choice, pdict, vgraph, rgraph, opt::technology, rdict, recoveredsolutionFile, recovered_map);
//#############################################
write_recovered( recoveredsolutionFile, recovered_map );
return;
};
/*
for (auto it2 : vgraph[ref_hash].connections) { /////// reference base
ptrdiff_t j = get_index_var( pdict.double_positions, vgraph[it2.first].pos );
//cout << "ref: " << ref_hash << "\t" << pos1 << "\t" << hap1 << "\t" << it2.first << "\t" << it2.second << "\t" << vgraph[it2.first].pos << "\t" << j << endl;
if (j < pdict.double_positions.size() && i != j) {
//// bx_tag = it2.second
//// pos2 = other het
std::string temp_string = split_string_first(it2.first,"_",1);
std::string ref_base = split_string_first(temp_string,"_",0);
std::string cnx_base = split_string_first(temp_string,"_",1);
int is_variant = -1; if (ref_base != cnx_base) { is_variant = 1; }
int pos2 = pdict.double_positions[j];
int hap2 = pdict.haplotype[j];
int call_allele = hap2*is_variant;
int diffp = std::abs( pos1 - pos2 );
if ( diffp < max_delta_p ) {
if ( ab_hap[call_allele] == "A" ) { ref_numA += 1; upos_ref_listA.push_back(pos2); }
if ( ab_hap[call_allele] == "B" ) { ref_numB += 1; upos_ref_listB.push_back(pos2); }
}
//cout << pos2 << "\t" << hap2 << "\t" << is_variant << "\t" << call_allele << "\t" << ab_hap[call_allele] << endl;
}
}
for (auto it2 : vgraph[alt_hash].connections) { /////// alternate base
ptrdiff_t j = get_index_var( pdict.double_positions, vgraph[it2.first].pos );
//cout << "alt: " << alt_hash << "\t" << pos1 << "\t" << hap1 << "\t" << it2.first << "\t" << vgraph[it2.first].pos << "\t" << j << endl;
if (j < pdict.double_positions.size() && i != j) {
std::string temp_string = split_string_first(it2.first,"_",1);
std::string ref_base = split_string_first(temp_string,"_",0);
std::string cnx_base = split_string_first(temp_string,"_",1);
int is_variant = -1; if (ref_base != cnx_base) { is_variant = 1; }
int pos2 = pdict.double_positions[j];
int hap2 = pdict.haplotype[j];
int call_allele = hap2*is_variant;
int diffp = std::abs( pos1 - pos2 );
if ( diffp < max_delta_p ) {
if ( ab_hap[call_allele] == "A" ) {
alt_numA += 1;
upos_alt_listA.push_back(pos2);
}
if ( ab_hap[call_allele] == "B" ) {
alt_numB += 1;
upos_alt_listB.push_back(pos2);
}
}
//cout << pos2 << "\t" << hap2 << "\t" << is_variant << "\t" << call_allele << "\t" << ab_hap[call_allele] << endl;
}
} */
//for (int l = 0; l < rdict.num_paired; l++) {
// int position = rdict.double_positions[l];
// cout << l << "\t" << rdict.num_paired << "\t"<< position << endl;
// ref_position_map[position] = rdict.ref_handle[l];
// alt_position_map[position] = rdict.alt_handle[l];
//}
//for (auto& it : vgraph) {
// ref_position_map[it.second.pos] = it.second.ref_base;
// alt_position_map[it.second.pos] = it.second.var_base;
//}
//coord_dictionary pdict;
//
///////////// write haplotype output
//cout << " writing scaffold file: " << scaffoldsolutionFile << endl;
//write_scaffold( opt::chr_choice, scaffoldsolutionFile, bl_dict, pdict, centromere_pos );
//for (int i = 0; i < pdict.num_paired; i++) {
//int pos1 = pdict.double_positions[i];
//int hap1 = pdict.haplotype[i];
//int ref_hap = hap1;
//int alt_hap = hap1*-1;
//std::string ref_hash = pdict.ref_handle[i];
//std::string alt_hash = pdict.alt_handle[i];
| 51.909968 | 315 | 0.580216 | [
"vector"
] |
5c9f76832b03657a7fba430d5d92a4bcd5bf475d | 4,959 | cpp | C++ | src/Sphere.cpp | omi-lab/tp_math_utils | bbcdec7a680fb2fd029006ad456efb5e81d840c3 | [
"MIT"
] | null | null | null | src/Sphere.cpp | omi-lab/tp_math_utils | bbcdec7a680fb2fd029006ad456efb5e81d840c3 | [
"MIT"
] | null | null | null | src/Sphere.cpp | omi-lab/tp_math_utils | bbcdec7a680fb2fd029006ad456efb5e81d840c3 | [
"MIT"
] | 3 | 2018-08-30T10:01:10.000Z | 2020-10-07T10:56:26.000Z | #include "tp_math_utils/Sphere.h"
#include "glm/gtx/compatibility.hpp"
namespace tp_math_utils
{
//##################################################################################################
//Geometry3D Sphere::icosahedralClass1(float radius,
// size_t division,
// int triangleFan,
// int triangleStrip,
// int triangles)
//{
// std::vector<glm::vec3> verts;
// return indexAndScale(radius, triangleFan, triangleStrip, triangles, verts);
//}
//##################################################################################################
Geometry3D Sphere::octahedralClass1(float radius,
size_t division,
int triangleFan,
int triangleStrip,
int triangles)
{
std::vector<glm::vec3> verts;
divideClass1(division, { 0,-1, 0}, { 1, 0, 0}, { 0, 0, 1}, verts);
divideClass1(division, {-1, 0, 0}, { 0,-1, 0}, { 0, 0, 1}, verts);
divideClass1(division, { 0, 1, 0}, {-1, 0, 0}, { 0, 0, 1}, verts);
divideClass1(division, { 1, 0, 0}, { 0, 1, 0}, { 0, 0, 1}, verts);
divideClass1(division, { 1, 0, 0}, { 0,-1, 0}, { 0, 0,-1}, verts);
divideClass1(division, { 0,-1, 0}, {-1, 0, 0}, { 0, 0,-1}, verts);
divideClass1(division, {-1, 0, 0}, { 0, 1, 0}, { 0, 0,-1}, verts);
divideClass1(division, { 0, 1, 0}, { 1, 0, 0}, { 0, 0,-1}, verts);
return indexAndScale(radius, triangleFan, triangleStrip, triangles, verts);
}
//##################################################################################################
Geometry3D Sphere::tetrahedralClass1(float radius,
size_t division,
int triangleFan,
int triangleStrip,
int triangles)
{
std::vector<glm::vec3> verts;
divideClass1(division, {-1,-1,-1}, { 1,-1, 1}, {-1, 1, 1}, verts);
divideClass1(division, {-1,-1,-1}, { 1, 1,-1}, { 1,-1, 1}, verts);
divideClass1(division, {-1,-1,-1}, {-1, 1, 1}, { 1, 1,-1}, verts);
divideClass1(division, { 1,-1, 1}, { 1, 1,-1}, {-1, 1, 1}, verts);
return indexAndScale(radius, triangleFan, triangleStrip, triangles, verts);
}
//##################################################################################################
void Sphere::divideClass1(size_t division,
const glm::vec3& a,
const glm::vec3& b,
const glm::vec3& c,
std::vector<glm::vec3>& verts)
{
if(division==0)
return;
double stepI = 1.0 / double(division);
std::vector<glm::vec3> prev;
prev.push_back(a);
for(size_t i=0; i<division; i++)
{
glm::vec3 bb = glm::lerp(a, b, float(stepI*double(i+1)));
glm::vec3 cc = glm::lerp(a, c, float(stepI*double(i+1)));
double stepJ = 1.0 / double(i+1);
std::vector<glm::vec3> next;
next.reserve(i+2);
next.push_back(bb);
for(size_t j=0; j<i; j++)
next.push_back(glm::lerp(bb, cc, float(stepJ*double(j+1))));
next.push_back(cc);
for(size_t c=0; c<prev.size(); c++)
{
verts.push_back(prev.at(c));
verts.push_back(next.at(c));
verts.push_back(next.at(c+1));
}
for(size_t c=1; c<prev.size(); c++)
{
verts.push_back(prev.at(c-1));
verts.push_back(next.at(c));
verts.push_back(prev.at(c));
}
prev.swap(next);
}
}
//##################################################################################################
Geometry3D Sphere::indexAndScale(float radius,
int triangleFan,
int triangleStrip,
int triangles,
const std::vector<glm::vec3>& verts)
{
Geometry3D geometry;
geometry.triangleFan = triangleFan;
geometry.triangleStrip = triangleStrip;
geometry.triangles = triangles;
auto& indexes = geometry.indexes.emplace_back().indexes;
geometry.indexes.back().type = geometry.triangles;
float e=0.000001f;
for(const auto& vert : verts)
{
int index=-1;
for(size_t i=0; i<geometry.verts.size(); i++)
{
const auto& v = geometry.verts.at(i).vert;
if(std::fabs(v.x-vert.x)<e &&
std::fabs(v.y-vert.y)<e &&
std::fabs(v.z-vert.z)<e)
{
index = int(i);
break;
}
}
if(index==-1)
{
index = int(geometry.verts.size());
geometry.verts.emplace_back().vert = vert;
}
indexes.push_back(index);
}
for(auto& vert : geometry.verts)
{
vert.vert = glm::normalize(vert.vert);
vert.texture = {(vert.vert.x+1.0f)/2.0f, (-vert.vert.z+1.0f)/2.0f};
vert.vert *= radius;
}
return geometry;
}
}
| 30.99375 | 100 | 0.463803 | [
"geometry",
"vector"
] |
5ca0730f5961899ca300e6d439a9df86c97975ea | 3,804 | hpp | C++ | src/openEL_ActuatorM5StackGrayBMM150.hpp | openel/openel-arduino | 8d429cb8b6e0d3ba152655a67459bc0f5ab54186 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-11-19T08:53:36.000Z | 2021-11-19T08:53:36.000Z | src/openEL_ActuatorM5StackGrayBMM150.hpp | openel/openel-arduino | 8d429cb8b6e0d3ba152655a67459bc0f5ab54186 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/openEL_ActuatorM5StackGrayBMM150.hpp | openel/openel-arduino | 8d429cb8b6e0d3ba152655a67459bc0f5ab54186 | [
"MIT",
"BSD-3-Clause"
] | 2 | 2021-11-07T00:22:12.000Z | 2021-11-07T06:41:45.000Z | /*
* MIT License
*
* Copyright (c) 2017 M5Stack
* Copyright (c) 2021 JASA(Japan Embedded Systems Technology Association)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef OPENEL_ACTUATOR_M5STACK_GRAY_BMM150_HPP
#define OPENEL_ACTUATOR_M5STACK_GRAY_BMM150_HPP
#include <M5Stack.h>
#include "Actuator.hpp"
#define MOTOR_ADDRESS 0x3A
#define MOTOR_SPEED_L 0x00
#define MOTOR_SPEED_R 0x02
#define MOTOR_ENCODER_L 0x10
#define MOTOR_ENCODER_R 0x14
#define MOTOR_LENGTH_SPEED (2)
#define MOTOR_LENGTH_ENCODER (4)
enum Instance {
MOTOR_LEFT = 1,
MOTOR_RIGHT,
InstanceNum
};
class ActuatorM5StackGrayBMM150 : public Actuator
{
private:
static std::string strDevName;
static std::vector<std::string> strFncLst;
static void I2C_Read_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, uint8_t *read_Buffer);
static void I2C_Read_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, int8_t *read_Buffer);
static void I2C_Write_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, uint8_t *write_Buffer);
static void I2C_Write_NBytes(uint8_t driver_Addr, uint8_t start_Addr, uint8_t number_Bytes, int8_t *write_Buffer);
static void getEncoder(int32_t* wheel, uint8_t sw);
static void setEncoder(int32_t wheel, uint8_t sw);
static void getSpeed(int16_t* sp, uint8_t sw);
static void setSpeed(int16_t sp, uint8_t sw);
public:
static Property ActuatorM5StackGrayBMM150_property;
static ReturnCode fncInit(HALComponent *pHALComponent);
static ReturnCode fncReInit(HALComponent *pHALComponent);
static ReturnCode fncFinalize(HALComponent *pHALComponent);
static ReturnCode fncAddObserver(HALComponent *pHALComponent, HALObserver **halObserver);
static ReturnCode fncRemoveObserver(HALComponent *pHALComponent, HALObserver **halObserver);
static ReturnCode fncGetProperty(HALComponent *pHALComponent, Property **property);
static ReturnCode fncGetTime(HALComponent *pHALComponent, unsigned int **timeValue);
static ReturnCode fncGetValLst(HALComponent *pHALComponent, float **valueList, int **num);
static ReturnCode fncGetTimedValLst(HALComponent *pHALComponent, float **valueList, unsigned int **time, int **num);
static ReturnCode fncSetValue(HALComponent *pHALComponent, int request, float value);
static ReturnCode fncGetValue(HALComponent *pHALComponent, int request, float **value);
static ReturnCode fncNop(HALComponent *pHALComponent, HAL_ARGUMENT_T *pCmd);
static ReturnCode fncDeviceVendorSpec(HALComponent* pHALComponent, HAL_ARGUMENT_T *pCmd, HAL_ARGUMENT_DEVICE_T *pCmdDev);
};
extern HAL_FNCTBL_T HalActuatorM5StackGrayBMM150Tbl;
#endif // OPENEL_ACTUATOR_M5STTACK_GRAY_BMM150_HPP
| 45.285714 | 125 | 0.784963 | [
"vector"
] |
5cafe87d4520b49d71a0308f24301f7193d844c2 | 1,596 | cpp | C++ | hphp/runtime/test/object.cpp | OrochiProject/hhvm-verifier | 4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2016-09-14T15:47:16.000Z | 2016-09-14T15:47:16.000Z | hphp/runtime/test/object.cpp | OrochiProject/hhvm-verifier | 4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/test/object.cpp | OrochiProject/hhvm-verifier | 4bba454dce32d5bceb12d4ca8c9f1fa5df2024c5 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include <gtest/gtest.h>
#include "hphp/runtime/base/comparisons.h"
#include "hphp/runtime/base/type-object.h"
#include "hphp/runtime/ext/string/ext_string.h"
namespace HPHP {
TEST(Object, Serialization) {
String s = "O:1:\"B\":1:{s:3:\"obj\";O:1:\"A\":1:{s:1:\"a\";i:10;}}";
Variant v = unserialize_from_string(s);
EXPECT_TRUE(v.isObject());
auto o = v.toObject();
EXPECT_TRUE(
!o->getClassName().asString().compare("__PHP_Incomplete_Class")
);
auto os = HHVM_FN(serialize)(o);
EXPECT_TRUE(
!os.compare( "O:1:\"B\":1:{s:3:\"obj\";O:1:\"A\":1:{s:1:\"a\";i:10;}}")
);
}
}
| 39.9 | 75 | 0.469298 | [
"object"
] |
5cb18c3407f24e165ff38e4e7ebbc8091a8ff339 | 3,663 | cpp | C++ | mps_voxels/src/mps_voxels/logging/DataLog.cpp | UM-ARM-Lab/multihypothesis_segmentation_tracking | 801d460afbf028100374c880bc684187ec8b909f | [
"MIT"
] | 3 | 2020-10-31T21:42:36.000Z | 2021-12-16T12:56:02.000Z | mps_voxels/src/mps_voxels/logging/DataLog.cpp | UM-ARM-Lab/multihypothesis_segmentation_tracking | 801d460afbf028100374c880bc684187ec8b909f | [
"MIT"
] | 1 | 2020-11-11T03:46:08.000Z | 2020-11-11T03:46:08.000Z | mps_voxels/src/mps_voxels/logging/DataLog.cpp | UM-ARM-Lab/multihypothesis_segmentation_tracking | 801d460afbf028100374c880bc684187ec8b909f | [
"MIT"
] | 1 | 2022-03-02T12:32:21.000Z | 2022-03-02T12:32:21.000Z | /*
* Copyright (c) 2020 Andrew Price
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "mps_voxels/logging/DataLog.h"
#include <ros/console.h>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace mps
{
std::unique_ptr<DataLog> DataLog::instance;
DataLog::DataLog(const std::string& filename, const ChannelSet& channels, const rosbag::bagmode::BagMode mode)
{
auto path = (filename.empty() ? getDefaultPath() : filename);
if (!fs::exists(path) && mode == rosbag::BagMode::Read)
{
throw std::runtime_error("Attempting to read from nonexistant file '" + path + "'.");
}
auto dir = fs::path(path).parent_path();
if (!fs::exists(dir))
{
fs::create_directory(dir);
}
bag = std::make_unique<rosbag::Bag>(path, mode);
activeChannels = channels;
if (mode == rosbag::BagMode::Read)
{
ROS_INFO_STREAM("Reading from '" << bag->getFileName() << "'");
}
else
{
ROS_INFO_STREAM("Logging to '" << bag->getFileName() << "'");
}
}
DataLog::~DataLog()
{
bag->close();
}
std::string DataLog::getDefaultPath() const
{
fs::path temp_dir = fs::temp_directory_path();
fs::path temp_file = temp_dir / fs::path("log.bag");
return temp_file.string();
}
ros::Time DataLog::getTime() const
{
if (ros::Time::isValid())
{
return ros::Time::now();
}
else
{
std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
std::time_t tt = std::chrono::system_clock::to_time_t(tp);
return ros::Time(tt);
}
}
template <>
void DataLog::log<const std::string&>(const std::string& channel, const std::string& msg)
{
if (activeChannels.find(channel) == activeChannels.end()) { return; }
std_msgs::String s;
s.data = msg;
log(channel, s);
}
template <>
std::string DataLog::load<std::string>(const std::string& channel)
{
std_msgs::String s = load<std_msgs::String>(channel);
return s.data;
}
template <>
void DataLog::log<const std::vector<char>>(const std::string& channel, const std::vector<char>& msg)
{
if (activeChannels.find(channel) == activeChannels.end()) { return; }
std_msgs::ByteMultiArray bytes;
std::copy(msg.begin(), msg.end(), std::back_inserter(bytes.data));
log(channel, bytes);
}
}
| 30.525 | 110 | 0.715261 | [
"vector"
] |
5cb7670efbf9c2525e5a8badbfef314abbb71128 | 10,870 | hpp | C++ | assembled_chunk_msgpack.hpp | CHIMEFRB/ch_frb_io | 1c283cda329c16cd04cf79d9d520a2076f748c9d | [
"MIT"
] | null | null | null | assembled_chunk_msgpack.hpp | CHIMEFRB/ch_frb_io | 1c283cda329c16cd04cf79d9d520a2076f748c9d | [
"MIT"
] | 17 | 2016-06-15T22:55:57.000Z | 2020-09-25T18:15:40.000Z | assembled_chunk_msgpack.hpp | CHIMEFRB/ch_frb_io | 1c283cda329c16cd04cf79d9d520a2076f748c9d | [
"MIT"
] | 3 | 2017-01-12T11:42:19.000Z | 2019-01-14T23:54:44.000Z | #ifndef _ASSEMBLED_CHUNK_MSGPACK_HPP
#define _ASSEMBLED_CHUNK_MSGPACK_HPP
#include <vector>
#include <iostream>
#include <msgpack.hpp>
extern "C" {
// UGH: c99
#define __STDC_VERSION__ 199901L
#include <bitshuffle.h>
}
#include <ch_frb_io.hpp>
/** Code for packing objects into msgpack mesages, and vice versa. **/
enum compression_type {
comp_none = 0,
comp_bitshuffle = 1
};
// Our own function for packing an assembled_chunk into a msgpack stream,
// including an optional buffer for compression.
template <typename Stream>
void pack_assembled_chunk(msgpack::packer<Stream>& o,
std::shared_ptr<ch_frb_io::assembled_chunk> const& ch,
bool compress=false,
uint8_t* buffer=NULL) {
// pack member variables as an array.
//std::cout << "Pack shared_ptr<assembled-chunk> into msgpack object..." << std::endl;
uint8_t version = 2;
// We are going to pack N items as a msgpack array (with mixed types)
o.pack_array(21);
// Item 0: header string
o.pack("assembled_chunk in msgpack format");
// Item 1: version number
o.pack(version);
uint8_t compression = (uint8_t)comp_none;
int data_size = ch->ndata;
// Create a shared pointer to the block of data to be written
// (which defaults to this assembled_chunk's data, which is not to be deleted)
std::shared_ptr<uint8_t> chdata(std::shared_ptr<uint8_t>(), ch->data);
std::shared_ptr<uint8_t> data = chdata;
if (compress) {
compression = (uint8_t)comp_bitshuffle;
if (buffer) {
// We can use this buffer for compression
data = std::shared_ptr<uint8_t>(std::shared_ptr<uint8_t>(), buffer);
} else {
// Try to allocate a temp buffer for the compressed data.
// How big can the compressed data become?
size_t maxsize = ch->max_compressed_size();
std::cout << "bitshuffle: uncompressed size " << ch->ndata << ", max compressed size " << maxsize << std::endl;
data = std::shared_ptr<uint8_t>((uint8_t*)malloc(maxsize));
// unlikely...
if (!data) {
std::cout << "Failed to allocate a buffer to compress an assembled_chunk; writing uncompressed" << std::endl;
compression = (uint8_t)comp_none;
data = chdata;
compress = false;
}
}
}
if (compress) {
// Try compressing. If the compressed size is not smaller than the original, write uncompressed instead.
int64_t n = bshuf_compress_lz4(ch->data, data.get(), ch->ndata, 1, 0);
if ((n < 0) || (n >= ch->ndata)) {
if (n < 0)
std::cout << "bitshuffle compression failed; writing uncompressed" << std::endl;
else
std::cout << "bitshuffle compression did not actually compress the data (" + std::to_string(n) + " vs orig " + std::to_string(ch->ndata) + "); writing uncompressed" << std::endl;
data = chdata;
compression = (uint8_t)comp_none;
compress = false;
} else {
data_size = n;
std::cout << "Bitshuffle compressed to " << n << std::endl;
}
}
// Item[2]
o.pack(compression);
// Item[3]
o.pack(data_size);
// Item[4]...
o.pack(ch->beam_id);
o.pack(ch->nupfreq);
o.pack(ch->nt_per_packet);
o.pack(ch->fpga_counts_per_sample);
o.pack(ch->nt_coarse);
o.pack(ch->nscales);
o.pack(ch->ndata);
o.pack(ch->fpga_begin);
o.pack(ch->fpga_end - ch->fpga_begin);
o.pack(ch->binning);
// PACK FLOATS AS BINARY
int nscalebytes = ch->nscales * sizeof(float);
// Item[14]
o.pack_bin(nscalebytes);
o.pack_bin_body(reinterpret_cast<const char*>(ch->scales),
nscalebytes);
// Item[15]
o.pack_bin(nscalebytes);
o.pack_bin_body(reinterpret_cast<const char*>(ch->offsets),
nscalebytes);
// Item[16]
o.pack_bin(data_size);
o.pack_bin_body(reinterpret_cast<const char*>(data.get()), data_size);
// Item[17]
o.pack(ch->frame0_nano);
// Item[18]
o.pack(ch->nrfifreq);
o.pack(ch->has_rfi_mask.load());
if (ch->rfi_mask) {
// Item[20]
o.pack_bin(ch->nrfimaskbytes);
o.pack_bin_body(reinterpret_cast<const char*>(ch->rfi_mask), ch->nrfimaskbytes);
} else {
// Item[20]
o.pack_bin(0);
}
}
namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
namespace adaptor {
// Unpack a msgpack object into an assembled_chunk.
template<>
struct convert<std::shared_ptr<ch_frb_io::assembled_chunk> > {
msgpack::object const& operator()(msgpack::object const& o,
std::shared_ptr<ch_frb_io::assembled_chunk>& ch) const {
if (o.type != msgpack::type::ARRAY) throw msgpack::type_error();
//std::cout << "convert msgpack object to shared_ptr<assembled_chunk>..." << std::endl;
// Make sure array is big enough to check header, version
if (o.via.array.size < 2)
throw msgpack::type_error();
msgpack::object* arr = o.via.array.ptr;
std::string header = arr[0].as<std::string>();
uint8_t version = arr[1].as<uint8_t>();
if (version == 1) {
if (o.via.array.size != 17)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack version 1: expected 17 items, got " + std::to_string(o.via.array.size));
} else if (version == 2) {
if (o.via.array.size != 21)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack version 2: expected 21 items, got " + std::to_string(o.via.array.size));
} else {
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack: expected version = 1 or 2, got " + std::to_string(version));
}
enum compression_type comp = (enum compression_type)arr[2].as<uint8_t>();
if (!((comp == comp_none) || (comp == comp_bitshuffle)))
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack compression " + std::to_string(comp) + ", expected 0 or 1");
int compressed_size = arr[3].as<int>();
int beam_id = arr[4].as<int>();
int nupfreq = arr[5].as<int>();
int nt_per_packet = arr[6].as<int>();
int fpga_counts_per_sample = arr[7].as<int>();
int nt_coarse = arr[8].as<int>();
int nscales = arr[9].as<int>();
int ndata = arr[10].as<int>();
uint64_t fpga0 = arr[11].as<uint64_t>();
uint64_t fpgaN = arr[12].as<uint64_t>();
int binning = arr[13].as<int>();
int iarr = 14;
uint64_t isample = fpga0 / (uint64_t)fpga_counts_per_sample;
uint64_t ichunk = isample / ch_frb_io::constants::nt_per_assembled_chunk;
uint64_t frame0_nano = 0;
if (version == 2)
frame0_nano = arr[17].as<uint64_t>();
ch_frb_io::assembled_chunk::initializer ini_params;
ini_params.beam_id = beam_id;
ini_params.nupfreq = nupfreq;
ini_params.nt_per_packet = nt_per_packet;
ini_params.fpga_counts_per_sample = fpga_counts_per_sample;
ini_params.binning = binning;
ini_params.ichunk = ichunk;
ini_params.frame0_nano = frame0_nano;
if (version == 2)
ini_params.nrfifreq = arr[18].as<int>();
ch = ch_frb_io::assembled_chunk::make(ini_params);
if (ch->nt_coarse != nt_coarse)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack nt_coarse mismatch");
if (ch->nscales != nscales)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack nscales mismatch");
if (ch->ndata != ndata)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack nscales mismatch");
if (ch->fpga_begin != fpga0)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack fpga_begin mismatch");
if (ch->fpga_end != fpga0 + fpgaN)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack fpga_end mismatch");
if (arr[iarr + 0].type != msgpack::type::BIN) throw msgpack::type_error();
if (arr[iarr + 1].type != msgpack::type::BIN) throw msgpack::type_error();
if (arr[iarr + 2].type != msgpack::type::BIN) throw msgpack::type_error();
uint nsdata = nscales * sizeof(float);
if (arr[iarr + 0].via.bin.size != nsdata) throw msgpack::type_error();
if (arr[iarr + 1].via.bin.size != nsdata) throw msgpack::type_error();
memcpy(ch->scales, arr[iarr + 0].via.bin.ptr, nsdata);
memcpy(ch->offsets, arr[iarr + 1].via.bin.ptr, nsdata);
if (comp == comp_none) {
if (arr[iarr + 2].via.bin.size != (uint)ndata) throw msgpack::type_error();
memcpy(ch->data, arr[iarr + 2].via.bin.ptr, ndata);
} else if (comp == comp_bitshuffle) {
if (arr[iarr + 2].via.bin.size != (uint)compressed_size) throw msgpack::type_error();
//std::cout << "Bitshuffle: decompressing " << compressed_size << " to " << ch->ndata << std::endl;
int64_t n = bshuf_decompress_lz4(reinterpret_cast<const void*>(arr[iarr + 2].via.bin.ptr), ch->data, ch->ndata, 1, 0);
if (n != compressed_size)
throw std::runtime_error("ch_frb_io: assembled_chunk msgpack bitshuffle decompression failure, code " + std::to_string(n));
}
if (version == 2) {
ch->has_rfi_mask = arr[19].as<bool>();
if (ch->has_rfi_mask) {
uint nb = ch->nrfimaskbytes;
if (arr[20].via.bin.size != (uint)nb)
throw msgpack::type_error();
memcpy(ch->rfi_mask, arr[20].via.bin.ptr, nb);
}
}
return o;
}
};
// Pack an assembled_chunk object into a msgpack stream.
template<>
struct pack<std::shared_ptr<ch_frb_io::assembled_chunk> > {
template <typename Stream>
packer<Stream>& operator()(msgpack::packer<Stream>& o, std::shared_ptr<ch_frb_io::assembled_chunk> const& ch) const {
pack_assembled_chunk(o, ch);
return o;
}
};
/* Apparently not needed yet?
template <>
struct object_with_zone<std::shared_ptr<ch_frb_io::assembled_chunk> > {
void operator()(msgpack::object::with_zone& o, std::shared_ptr<ch_frb_io::assembled_chunk> const& v) const {
o.type = type::ARRAY;
std::cout << "Convert shared_ptr<assembled_chunk> into msgpack object_with_zone" << std::endl;
...
*/
} // namespace adaptor
} // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS)
} // namespace msgpack
#endif // _ASSEMBLED_CHUNK_MSGPACK_HPP
| 41.018868 | 194 | 0.603128 | [
"object",
"vector"
] |
5cbefb26f8b66a27db226ae9762f64c117f9290b | 389,751 | cxx | C++ | dev/ese/src/ese/space.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | 1 | 2021-02-02T07:04:07.000Z | 2021-02-02T07:04:07.000Z | dev/ese/src/ese/space.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | dev/ese/src/ese/space.cxx | augustoproiete-forks/microsoft--Extensible-Storage-Engine | a38945d2147167e3fa749594f54dae6c7307b8da | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "std.hxx"
#include "_space.hxx"
#ifdef PERFMON_SUPPORT
PERFInstanceLiveTotal<> cSPPagesTrimmed;
LONG LSPPagesTrimmedCEFLPv( LONG iInstance, VOID *pvBuf )
{
cSPPagesTrimmed.PassTo( iInstance, pvBuf );
return 0;
}
PERFInstanceLiveTotal<> cSPPagesNotTrimmedUnalignedPage;
LONG LSPPagesNotTrimmedUnalignedPageCEFLPv( LONG iInstance, VOID *pvBuf )
{
cSPPagesNotTrimmedUnalignedPage.PassTo( iInstance, pvBuf );
return 0;
}
PERFInstanceLiveTotal<> cSPDeletedTrees;
LONG LSPDeletedTreesCEFLPv( LONG iInstance, VOID *pvBuf )
{
cSPDeletedTrees.PassTo( iInstance, pvBuf );
return 0;
}
PERFInstanceLiveTotal<> cSPDeletedTreeFreedPages;
LONG LSPDeletedTreeFreedPagesCEFLPv( LONG iInstance, VOID *pvBuf )
{
cSPDeletedTreeFreedPages.PassTo( iInstance, pvBuf );
return 0;
}
PERFInstanceLiveTotal<> cSPDeletedTreeFreedExtents;
LONG LSPDeletedTreeFreedExtentsCEFLPv( LONG iInstance, VOID *pvBuf )
{
cSPDeletedTreeFreedExtents.PassTo( iInstance, pvBuf );
return 0;
}
#endif
#include "_bt.hxx"
const CHAR * SzNameOfTable( const FUCB * const pfucb )
{
if( pfucb->u.pfcb->FTypeTable() )
{
return pfucb->u.pfcb->Ptdb()->SzTableName();
}
else if( pfucb->u.pfcb->FTypeLV() )
{
return pfucb->u.pfcb->PfcbTable()->Ptdb()->SzTableName();
}
else if( pfucb->u.pfcb->FTypeSecondaryIndex() )
{
return pfucb->u.pfcb->PfcbTable()->Ptdb()->SzTableName();
}
return "";
}
const CHAR * SzSpaceTreeType( const FUCB * const pfucb )
{
if ( pfucb->fAvailExt )
{
return " AE";
}
else if ( pfucb->fOwnExt )
{
return " OE";
}
return " !!";
}
#ifdef DEBUG
#endif
class CSPExtentInfo;
LOCAL ERR ErrSPIAddFreedExtent( FUCB *pfucb, FUCB *pfucbAE, const PGNO pgnoLast, const CPG cpgSize );
LOCAL ERR ErrSPISeekRootAE(
__in FUCB* const pfucbAE,
__in const PGNO pgno,
__in const SpacePool sppAvailPool,
__out CSPExtentInfo* const pspeiAE );
LOCAL ERR ErrSPIGetSparseInfoRange(
_In_ FMP* const pfmp,
_In_ const PGNO pgnoStart,
_In_ const PGNO pgnoEnd,
_Out_ CPG* pcpgSparse );
LOCAL ERR FSPIParentIsFs( FUCB * const pfucb );
LOCAL ERR ErrSPIGetFsSe(
FUCB * const pfucb,
FUCB * const pfucbAE,
const CPG cpgReq,
const CPG cpgMin,
const ULONG fSPFlags,
const BOOL fExact = fFalse,
const BOOL fPermitAsyncExtension = fTrue,
const BOOL fMayViolateMaxSize = fFalse );
LOCAL ERR ErrSPIGetSe(
FUCB * const pfucb,
FUCB * const pfucbAE,
const CPG cpgReq,
const CPG cpgMin,
const ULONG fSPFlags,
const SpacePool sppPool,
const BOOL fMayViolateMaxSize = fFalse );
LOCAL ERR ErrSPIWasAlloc( FUCB *pfucb, PGNO pgnoFirst, CPG cpgSize );
LOCAL ERR ErrSPIValidFDP( PIB *ppib, IFMP ifmp, PGNO pgnoFDP );
LOCAL ERR ErrSPIReserveSPBufPages(
FUCB* const pfucb,
FUCB* const pfucbParent,
const CPG cpgAddlReserveOE = 0,
const CPG cpgAddlReserveAE = 0,
const PGNO pgnoReplace = pgnoNull );
LOCAL ERR ErrSPIAddToAvailExt(
__in FUCB * pfucbAE,
__in const PGNO pgnoAELast,
__in const CPG cpgAESize,
__in SpacePool sppPool );
LOCAL ERR ErrSPIUnshelvePagesInRange( FUCB* const pfucbRoot, const PGNO pgnoFirst, const PGNO pgnoLast );
POSTIMERTASK g_posttSPITrimDBITask = NULL;
CSemaphore g_semSPTrimDBScheduleCancel( CSyncBasicInfo( "g_semSPTrimDBScheduleCancel" ) );
LOCAL VOID SPITrimDBITask( VOID*, VOID* );
ERR ErrSPInit()
{
ERR err = JET_errSuccess;
Assert( g_posttSPITrimDBITask == NULL );
Call( ErrOSTimerTaskCreate( SPITrimDBITask, (void*)ErrSPInit, &g_posttSPITrimDBITask ) );
Assert( g_semSPTrimDBScheduleCancel.CAvail() == 0 );
g_semSPTrimDBScheduleCancel.Release();
HandleError:
return err;
}
VOID SPTerm()
{
if ( g_posttSPITrimDBITask )
{
OSTimerTaskCancelTask( g_posttSPITrimDBITask );
OSTimerTaskDelete( g_posttSPITrimDBITask );
g_posttSPITrimDBITask = NULL;
}
Assert( g_semSPTrimDBScheduleCancel.CAvail() <= 1 );
g_semSPTrimDBScheduleCancel.Acquire();
Assert( g_semSPTrimDBScheduleCancel.CAvail() == 0 );
}
INLINE VOID AssertSPIPfucbOnRoot( const FUCB * const pfucb )
{
#ifdef DEBUG
Assert( pfucb->pcsrRoot != pcsrNil );
Assert( pfucb->pcsrRoot->Pgno() == PgnoFDP( pfucb ) );
Assert( pfucb->pcsrRoot->Latch() == latchRIW
|| pfucb->pcsrRoot->Latch() == latchWrite );
Assert( !FFUCBSpace( pfucb ) );
#endif
}
INLINE VOID AssertSPIPfucbOnRootOrNull( const FUCB * const pfucb )
{
#ifdef DEBUG
if ( pfucb != pfucbNil )
{
AssertSPIPfucbOnRoot( pfucb );
}
#endif
}
INLINE VOID AssertSPIPfucbOnSpaceTreeRoot( FUCB *pfucb, CSR *pcsr )
{
#ifdef DEBUG
Assert( FFUCBSpace( pfucb ) );
Assert( pcsr->FLatched() );
Assert( pcsr->Pgno() == PgnoRoot( pfucb ) );
Assert( pcsr->Cpage().FRootPage() );
Assert( pcsr->Cpage().FSpaceTree() );
#endif
}
INLINE BOOL FSPValidPGNO( __in const PGNO pgno )
{
return pgnoNull < pgno && pgnoSysMax > pgno;
}
INLINE BOOL FSPValidAllocPGNO( __in const PGNO pgno )
{
return pgnoFDPMSO-1 < pgno && pgnoSysMax > pgno;
}
#ifdef DEBUG
PGNO g_pgnoAllocTrap = 0;
INLINE VOID SPCheckPgnoAllocTrap( __in const PGNO pgnoAlloc, __in const CPG cpgAlloc )
{
if ( g_pgnoAllocTrap == pgnoAlloc ||
( g_pgnoAllocTrap > pgnoAlloc && g_pgnoAllocTrap <= pgnoAlloc + cpgAlloc -1 ) )
{
AssertSz( fFalse, "Pgno Alloc Trap" );
}
}
#else
INLINE VOID SPCheckPgnoAllocTrap( __in const PGNO pgnoAlloc, __in const CPG cpgAlloc )
{
;
}
#endif
#ifdef DEBUG
const PGNO pgnoBadNews = 0xFFFFFFFF;
const PGNO cpgBadNews = 0xFFFFFFFF;
#endif
#include <pshpack1.h>
PERSISTED
class SPEXTKEY {
private:
union {
BYTE mbe_pgnoLast[sizeof(PGNO)];
struct
{
BYTE bExtFlags;
BYTE mbe_pgnoLastAfterFlags[sizeof(PGNO)];
};
};
BOOL _FNewSpaceKey() const
{
return fSPAvailExtReservedPool == ( bExtFlags & fSPAvailExtReservedPool );
}
ULONG _Cb( ) const
{
if ( _FNewSpaceKey() )
{
C_ASSERT( 0x5 == sizeof(SPEXTKEY) );
return sizeof(SPEXTKEY);
}
else
{
C_ASSERT( 0x4 == sizeof(PGNO) );
return sizeof(PGNO);
}
}
PGNO _PgnoLast( void ) const
{
#ifdef DEBUG
PGNO pgnoLast = pgnoBadNews;
#else
PGNO pgnoLast;
#endif
if ( _FNewSpaceKey() )
{
LongFromUnalignedKey( &pgnoLast, mbe_pgnoLastAfterFlags );
}
else
{
LongFromUnalignedKey( &pgnoLast, mbe_pgnoLast );
}
Assert( pgnoBadNews != pgnoLast );
return pgnoLast;
}
public:
#ifdef DEBUG
SPEXTKEY( ) { Invalidate(); }
~SPEXTKEY( ) { Invalidate(); }
VOID Invalidate() { memset( this, 0xFF, sizeof(*this) ); }
#else
SPEXTKEY( ) { }
~SPEXTKEY( ) { }
#endif
public:
enum E_SP_EXTENT_TYPE
{
fSPExtentTypeUnknown = 0x0,
fSPExtentTypeOE,
fSPExtentTypeAE,
};
enum { fSPAvailExtReservedPool = 0x80 };
enum { fSPReservedZero = 0x40 };
enum { fSPReservedBitsMask = 0x38 };
enum { fSPPoolMask = 0x07 };
static_assert( ( 0xFF == ( (BYTE)fSPAvailExtReservedPool |
(BYTE)fSPReservedZero |
(BYTE)fSPReservedBitsMask |
(BYTE)fSPPoolMask ) ), "All bits are used." );
static_assert( ( ( 0 == ( (BYTE)fSPAvailExtReservedPool & (BYTE)fSPReservedZero ) ) &&
( 0 == ( (BYTE)fSPAvailExtReservedPool & (BYTE)fSPReservedBitsMask ) ) &&
( 0 == ( (BYTE)fSPAvailExtReservedPool & (BYTE)fSPPoolMask ) ) &&
( 0 == ( (BYTE)fSPReservedZero & (BYTE)fSPReservedBitsMask ) ) &&
( 0 == ( (BYTE)fSPReservedZero & (BYTE)fSPPoolMask ) ) &&
( 0 == ( (BYTE)fSPReservedBitsMask & (BYTE)fSPPoolMask ) ) ) , "All bits are used only once." );
static_assert( ( (BYTE)spp::MaxPool == ( (BYTE)fSPPoolMask & (BYTE)spp::MaxPool ) ),
"We are using enough bits to safely mask all spp:: values." );
VOID Make(
__in const E_SP_EXTENT_TYPE eExtType,
__in const PGNO pgnoLast,
__in const SpacePool sppAvailPool )
{
Assert( FSPIValidExplicitSpacePool( sppAvailPool ) );
if ( eExtType == fSPExtentTypeOE )
{
Assert( spp::AvailExtLegacyGeneralPool == sppAvailPool );
UnalignedKeyFromLong( mbe_pgnoLast, pgnoLast );
}
else if ( eExtType == fSPExtentTypeAE )
{
if ( spp::AvailExtLegacyGeneralPool != sppAvailPool )
{
bExtFlags = ( ( BYTE ) fSPAvailExtReservedPool | ( BYTE )sppAvailPool );
UnalignedKeyFromLong( mbe_pgnoLastAfterFlags, pgnoLast );
Assert( _FNewSpaceKey() );
}
else
{
UnalignedKeyFromLong( mbe_pgnoLast, pgnoLast );
}
}
else
{
AssertSz( fFalse, "Unknown Ext type" );
}
}
ULONG Cb( ) const { ASSERT_VALID( this ); return _Cb(); }
const VOID * Pv( ) const
{
ASSERT_VALID( this );
Assert( (BYTE*)this == mbe_pgnoLast );
C_ASSERT( OffsetOf( SPEXTKEY, mbe_pgnoLast ) == OffsetOf( SPEXTKEY, bExtFlags ) );
Assert( OffsetOf( SPEXTKEY, mbe_pgnoLast ) == OffsetOf( SPEXTKEY, bExtFlags ) );
C_ASSERT( OffsetOf( SPEXTKEY, mbe_pgnoLast ) != OffsetOf( SPEXTKEY, mbe_pgnoLastAfterFlags ) );
Assert( OffsetOf( SPEXTKEY, mbe_pgnoLast ) != OffsetOf( SPEXTKEY, mbe_pgnoLastAfterFlags ) );
return reinterpret_cast<const VOID *>(mbe_pgnoLast);
}
PGNO PgnoLast() const { ASSERT_VALID( this ); Assert( pgnoNull != _PgnoLast() ); return _PgnoLast(); }
BOOL FNewAvailFormat() const { ASSERT_VALID( this ); return _FNewSpaceKey(); }
SpacePool SppPool() const
{
SpacePool spp;
ASSERT_VALID( this );
if( _FNewSpaceKey() )
{
spp = (SpacePool) (bExtFlags & fSPPoolMask);
Assert( FSPIValidExplicitSpacePool( spp ) );
Assert( spp != spp::AvailExtLegacyGeneralPool );
}
else
{
spp = spp::AvailExtLegacyGeneralPool;
}
return spp;
}
public:
enum E_VALIDATE_TYPE
{
fValidateData = 0x01,
fValidateSearch = 0x02
};
INLINE BOOL FValid( __in const E_SP_EXTENT_TYPE eExtType, __in const E_VALIDATE_TYPE fValidateType ) const
{
PGNO pgnoLast = _PgnoLast();
Assert( pgnoBadNews != pgnoLast );
if ( pgnoSysMax < pgnoLast )
{
return fFalse;
}
if ( fValidateData == fValidateType )
{
if ( eExtType == fSPExtentTypeOE &&
!FSPValidPGNO( pgnoLast ) )
{
return fFalse;
}
if ( eExtType == fSPExtentTypeAE &&
!FSPValidAllocPGNO( pgnoLast ) )
{
return fFalse;
}
}
return fTrue;
}
INLINE BOOL FValid( __in const E_SP_EXTENT_TYPE eExtType, __in const ULONG cb ) const
{
return Cb() == cb && FValid( eExtType, fValidateData );
}
private:
INLINE BOOL FValid( ) const
{
return FValid( fSPExtentTypeOE, fValidateData ) ||
FValid( fSPExtentTypeAE, fValidateData ) ||
FValid( fSPExtentTypeOE, fValidateSearch ) ||
FValid( fSPExtentTypeAE, fValidateSearch );
}
public:
#ifdef DEBUG
VOID AssertValid() const
{
AssertSz( FValid( ), "Invalid Space Extent Key" );
}
#endif
};
C_ASSERT( 0x5 == sizeof(SPEXTKEY ) );
PERSISTED
class SPEXTDATA {
private:
UnalignedLittleEndian< CPG > le_cpgExtent;
public:
VOID Invalidate( )
{
#ifdef DEBUG
le_cpgExtent = pgnoBadNews;
#endif
}
SPEXTDATA( )
{
#ifdef DEBUG
Invalidate();
#endif
}
~SPEXTDATA( )
{
#ifdef DEBUG
Invalidate();
#endif
}
public:
SPEXTDATA( __in const CPG cpgExtent )
{
Set( cpgExtent );
Assert( FValid( ) );
}
VOID Set( __in const CPG cpgExtent )
{
le_cpgExtent = cpgExtent;
Assert( FValid( ) );
}
CPG CpgExtent() const { return le_cpgExtent; }
ULONG Cb() const { C_ASSERT( 4 == sizeof(SPEXTDATA) ); return sizeof(SPEXTDATA); }
const VOID* Pv() const { return reinterpret_cast<const VOID*>(&le_cpgExtent); }
public:
BOOL FValid( ) const
{
return PGNO(le_cpgExtent) < pgnoSysMax;
}
BOOL FValid( ULONG cb ) const
{
return cb == Cb() && FValid( );
}
};
C_ASSERT( 0x4 == sizeof(SPEXTDATA ) );
#include <poppack.h>
class CSPExtentInfo {
private:
SPEXTKEY::E_SP_EXTENT_TYPE m_eSpExtType:8;
FLAG32 m_fFromTempDB:1;
PGNO m_pgnoLast;
CPG m_cpgExtent;
SpacePool m_sppPool;
FLAG32 m_fNewAvailFormat:1;
FLAG32 m_fCorruptData:1;
PGNO _PgnoFirst() const { return m_pgnoLast - m_cpgExtent + 1; }
BOOL _FOwnedExt() const { return m_eSpExtType == SPEXTKEY::fSPExtentTypeOE; }
BOOL _FAvailExt() const { return m_eSpExtType == SPEXTKEY::fSPExtentTypeAE; }
VOID _Set( __in const SPEXTKEY::E_SP_EXTENT_TYPE eSpExtType, __in const KEYDATAFLAGS& kdfCurr )
{
m_fCorruptData = fFalse;
m_eSpExtType = eSpExtType;
if ( SPEXTKEY::fSPExtentTypeUnknown == eSpExtType )
{
if( kdfCurr.key.Cb() == 0x4 )
{
m_eSpExtType = SPEXTKEY::fSPExtentTypeOE;
}
else if ( kdfCurr.key.Cb() == 0x5 )
{
m_eSpExtType = SPEXTKEY::fSPExtentTypeAE;
}
}
if ( kdfCurr.key.Cb() == 0x5 )
{
Assert( m_eSpExtType == SPEXTKEY::fSPExtentTypeAE );
}
BYTE rgExtKey[sizeof(SPEXTKEY)];
kdfCurr.key.CopyIntoBuffer( rgExtKey, sizeof( rgExtKey ) );
const SPEXTKEY * const pSPExtKey = reinterpret_cast<const SPEXTKEY *>( rgExtKey );
m_fCorruptData |= !pSPExtKey->FValid( m_eSpExtType, kdfCurr.key.Cb() );
Assert( !m_fCorruptData );
m_pgnoLast = pSPExtKey->PgnoLast();
m_sppPool = pSPExtKey->SppPool();
if ( pSPExtKey->FNewAvailFormat() )
{
Assert( m_eSpExtType == SPEXTKEY::fSPExtentTypeAE );
Assert( _FAvailExt() );
Assert( 0x5 == kdfCurr.key.Cb() );
m_fNewAvailFormat = fTrue;
}
else
{
Assert( 0x4 == kdfCurr.key.Cb() );
Assert( spp::AvailExtLegacyGeneralPool == m_sppPool );
m_fNewAvailFormat = fFalse;
}
const SPEXTDATA * const pSPExtData = reinterpret_cast<const SPEXTDATA *>( kdfCurr.data.Pv() );
m_fCorruptData |= !pSPExtData->FValid( kdfCurr.data.Cb() );
Assert( !m_fCorruptData );
m_cpgExtent = pSPExtData->CpgExtent();
Assert( m_cpgExtent >= 0 );
}
public:
#ifdef DEBUG
VOID Invalidate()
{
m_fCorruptData = fTrue;
m_eSpExtType = SPEXTKEY::fSPExtentTypeUnknown;
m_pgnoLast = pgnoBadNews;
m_cpgExtent = cpgBadNews;
}
VOID AssertValid() const
{
Assert( SPEXTKEY::fSPExtentTypeUnknown != m_eSpExtType &&
pgnoBadNews != m_pgnoLast &&
cpgBadNews != m_cpgExtent );
Assert( SPEXTKEY::fSPExtentTypeAE == m_eSpExtType ||
SPEXTKEY::fSPExtentTypeOE == m_eSpExtType );
Assert( m_fCorruptData || ErrCheckCorrupted( fTrue ) >= JET_errSuccess );
}
#endif
CSPExtentInfo( ) { Unset(); }
~CSPExtentInfo( ) { Unset(); }
CSPExtentInfo( const FUCB * pfucb )
{
Set( pfucb );
ASSERT_VALID( this );
Assert( cpgBadNews != PgnoLast() );
Assert( cpgBadNews != CpgExtent() );
}
CSPExtentInfo( const KEYDATAFLAGS * pkdf )
{
_Set( SPEXTKEY::fSPExtentTypeUnknown, *pkdf );
ASSERT_VALID( this );
Assert( cpgBadNews != PgnoLast() );
Assert( cpgBadNews != CpgExtent() );
}
VOID Set( __in const FUCB * pfucb )
{
m_fCorruptData = fFalse;
Assert( FFUCBSpace( pfucb ) );
Assert( Pcsr( pfucb )->FLatched() );
m_eSpExtType = pfucb->fAvailExt ? SPEXTKEY::fSPExtentTypeAE : SPEXTKEY::fSPExtentTypeOE;
m_fFromTempDB = FFMPIsTempDB( pfucb->ifmp );
_Set( m_eSpExtType, pfucb->kdfCurr );
}
VOID Unset( )
{
m_eSpExtType = SPEXTKEY::fSPExtentTypeUnknown;
#ifdef DEBUG
Invalidate();
#endif
}
BOOL FIsSet( ) const
{
return m_eSpExtType != SPEXTKEY::fSPExtentTypeUnknown;
}
BOOL FOwnedExt() const { ASSERT_VALID( this ); return _FOwnedExt(); }
BOOL FAvailExt() const { ASSERT_VALID( this ); return _FAvailExt(); }
BOOL FValidExtent( ) const { ASSERT_VALID( this ); return ErrCheckCorrupted( fFalse ) >= JET_errSuccess; }
PGNO PgnoLast() const { ASSERT_VALID( this ); Assert( FValidExtent( ) ); return m_pgnoLast; }
CPG CpgExtent() const { ASSERT_VALID( this ); Assert( FValidExtent( ) ); return m_cpgExtent; }
PGNO PgnoFirst() const { ASSERT_VALID( this ); Assert( FValidExtent( ) ); Assert( m_cpgExtent != 0 ); return _PgnoFirst(); }
BOOL FContains( __in const PGNO pgnoIn ) const
{
ASSERT_VALID( this );
#ifdef DEBUG
BOOL fInExtent = ( ( pgnoIn >= _PgnoFirst() ) && ( pgnoIn <= m_pgnoLast ) );
if ( 0x0 == m_cpgExtent )
{
Assert( !fInExtent );
}
else
{
Assert( FValidExtent( ) );
}
return fInExtent;
#else
return ( ( pgnoIn >= _PgnoFirst() ) && ( pgnoIn <= m_pgnoLast ) );
#endif
}
BOOL FNewAvailFormat() const { ASSERT_VALID( this ); Assert( FValidExtent( ) ); return m_fNewAvailFormat; }
CPG FEmptyExtent() const { ASSERT_VALID( this ); return 0x0 == m_cpgExtent; }
PGNO PgnoMarker() const { ASSERT_VALID( this ); return m_pgnoLast; }
SpacePool SppPool() const
{
ASSERT_VALID( this );
Assert ( m_fNewAvailFormat || m_sppPool == spp::AvailExtLegacyGeneralPool );
return m_sppPool;
}
enum FValidationStrength { fStrong = 0x0, fZeroLengthOK = 0x1, fZeroFirstPgnoOK = 0x2 };
INLINE static BOOL FValidExtent( __in const PGNO pgnoLast, __in const CPG cpg, __in const FValidationStrength fStrength = fStrong )
{
if( fStrength & fZeroLengthOK )
{
if( ( cpg < 0 ) ||
( !( ( pgnoLast - cpg ) <= pgnoLast ) ) ||
( (ULONG)cpg > pgnoLast ) ||
( ( (INT)pgnoLast - cpg ) <= ( fStrength & fZeroFirstPgnoOK ? -1 : 0 ) ) ||
( ( pgnoLast + 1 ) < (ULONG)cpg ) )
{
return fFalse;
}
Assert( ( pgnoLast - cpg + 1 ) <= pgnoLast );
}
else
{
if( ( cpg <= 0 ) ||
( !( ( pgnoLast - cpg ) < pgnoLast ) ) ||
( (ULONG)cpg > pgnoLast ) ||
( ( (INT)pgnoLast - cpg ) <= ( fStrength & fZeroFirstPgnoOK ? -1 : 0 ) ) ||
( ( pgnoLast + 1 ) < (ULONG)cpg ) )
{
return fFalse;
}
Assert( ( pgnoLast - cpg + 1 ) <= pgnoLast );
}
return fTrue;
}
ERR ErrCheckCorrupted( BOOL fSilentOperation = fFalse ) const
{
if( m_fCorruptData )
{
AssertSz( fSilentOperation, "Ext Node corrupted at TAG level" );
goto HandleError;
}
if ( m_fNewAvailFormat && _FOwnedExt() )
{
AssertSz( fSilentOperation, "OE does not currently use the new format" );
goto HandleError;
}
if ( ( spp::AvailExtLegacyGeneralPool != m_sppPool ) && _FOwnedExt() )
{
AssertSz( fSilentOperation, "OE does not currently support pools" );
goto HandleError;
}
if ( !FSPIValidExplicitSpacePool( m_sppPool ) )
{
AssertSz( fSilentOperation, "Invalid pool" );
goto HandleError;
}
if ( spp::ShelvedPool == m_sppPool && 1 != m_cpgExtent )
{
AssertSz( fSilentOperation, "Shelved pool must only contain single-page extents." );
goto HandleError;
}
if( spp::ContinuousPool != m_sppPool || 0 != m_cpgExtent )
{
if( !FValidExtent( m_pgnoLast,
m_cpgExtent,
FValidationStrength( ( _FAvailExt() ? fZeroLengthOK : fStrong ) |
( _FOwnedExt() ? fZeroFirstPgnoOK : fStrong ) ) ) )
{
AssertSz( fSilentOperation, "Extent invalid range, could cause math overflow" );
goto HandleError;
}
}
if( !FSPValidPGNO( _PgnoFirst() ) || !FSPValidPGNO( m_pgnoLast ) )
{
AssertSz( fSilentOperation, "Invalid pgno" );
goto HandleError;
}
Assert( m_cpgExtent < 128 * 1024 / g_cbPage * 1024 * 1024 );
return JET_errSuccess;
HandleError:
if ( _FOwnedExt() )
{
return ErrERRCheck( JET_errSPOwnExtCorrupted );
}
else if ( _FAvailExt() )
{
return ErrERRCheck( JET_errSPAvailExtCorrupted );
}
AssertSz( fFalse, "Unknown extent type." );
return ErrERRCheck( JET_errInternalError );
}
};
class CSPExtentKeyBM {
private:
BOOKMARK m_bm;
SPEXTKEY m_spextkey;
SPEXTKEY::E_SP_EXTENT_TYPE m_eSpExtType:8;
BYTE m_fBookmarkSet:1;
public:
CSPExtentKeyBM()
{
m_fBookmarkSet = fFalse;
#ifdef DEBUG
m_eSpExtType = SPEXTKEY::fSPExtentTypeUnknown;
m_spextkey.Invalidate();
m_bm.Invalidate();
#endif
}
CSPExtentKeyBM(
__in const SPEXTKEY::E_SP_EXTENT_TYPE eExtType,
__in const PGNO pgno,
__in const SpacePool sppAvailPool = spp::AvailExtLegacyGeneralPool
)
{
m_fBookmarkSet = fFalse;
SPExtentMakeKeyBM( eExtType, pgno, sppAvailPool );
Assert( m_spextkey.FValid( eExtType, SPEXTKEY::fValidateSearch ) );
Assert( m_spextkey.Pv() == m_bm.key.suffix.Pv() );
}
VOID SPExtentMakeKeyBM(
__in const SPEXTKEY::E_SP_EXTENT_TYPE eExtType,
__in const PGNO pgno,
__in const SpacePool sppAvailPool = spp::AvailExtLegacyGeneralPool
)
{
m_eSpExtType = eExtType;
if( m_eSpExtType == SPEXTKEY::fSPExtentTypeAE )
{
Assert( FSPIValidExplicitSpacePool( sppAvailPool ) );
}
else
{
Assert( SPEXTKEY::fSPExtentTypeOE == eExtType );
Assert( spp::AvailExtLegacyGeneralPool == sppAvailPool );
}
m_spextkey.Make( eExtType, pgno, sppAvailPool );
Assert( m_spextkey.FValid( eExtType, SPEXTKEY::fValidateSearch ) );
if ( !m_fBookmarkSet )
{
m_bm.key.prefix.Nullify();
m_bm.key.suffix.SetPv( (VOID *) m_spextkey.Pv() );
m_bm.key.suffix.SetCb( m_spextkey.Cb() );
m_bm.data.Nullify();
Assert( m_bm.key.suffix.Pv() == m_spextkey.Pv() );
m_fBookmarkSet = fTrue;
}
}
const BOOKMARK& GetBm( FUCB * pfucb ) const
{
Assert( FFUCBSpace( pfucb ) && FFUCBUnique( pfucb ) );
Assert( m_spextkey.FValid( pfucb->fAvailExt ? SPEXTKEY::fSPExtentTypeAE : SPEXTKEY::fSPExtentTypeOE, SPEXTKEY::fValidateSearch ) );
Assert( pgnoBadNews != m_spextkey.PgnoLast() );
return m_bm;
}
const BOOKMARK* Pbm( FUCB * pfucb ) const
{
Assert( FFUCBSpace( pfucb ) && FFUCBUnique( pfucb ) );
Assert( m_spextkey.FValid( pfucb->fAvailExt ? SPEXTKEY::fSPExtentTypeAE : SPEXTKEY::fSPExtentTypeOE, SPEXTKEY::fValidateSearch ) );
return &m_bm;
}
};
class CSPExtentNodeKDF {
private:
KEYDATAFLAGS m_kdf;
SPEXTDATA m_spextdata;
SPEXTKEY m_spextkey;
SPEXTKEY::E_SP_EXTENT_TYPE m_eSpExtType:8;
BYTE m_fShouldDeleteNode:1;
public:
#ifdef DEBUG
VOID AssertValid( ) const
{
Assert( pgnoBadNews != m_spextkey.PgnoLast() );
Assert( pgnoBadNews != m_spextdata.CpgExtent() );
}
#endif
VOID Invalidate( void )
{
#ifdef DEBUG
m_kdf.Nullify();
m_spextkey.Invalidate();
m_spextdata.Invalidate();
#endif
}
BOOL FValid( void ) const
{
Assert( pgnoBadNews != m_spextkey.PgnoLast() );
Assert( cpgBadNews != m_spextdata.CpgExtent() );
if( m_spextkey.PgnoLast() > pgnoSysMax ||
m_spextdata.CpgExtent() > pgnoSysMax ||
pgnoNull == m_spextkey.PgnoLast() ||
( m_spextkey.SppPool() != spp::ContinuousPool &&
0x0 == m_spextdata.CpgExtent() )
)
{
return fFalse;
}
return fTrue;
}
private:
CSPExtentNodeKDF( )
{
Invalidate();
}
public:
CSPExtentNodeKDF(
__in const SPEXTKEY::E_SP_EXTENT_TYPE eExtType,
__in const PGNO pgnoLast,
__in const CPG cpgExtent,
__in const SpacePool sppAvailPool = spp::AvailExtLegacyGeneralPool )
{
Invalidate();
m_eSpExtType = eExtType;
m_spextkey.Make( m_eSpExtType, pgnoLast, sppAvailPool );
m_spextdata.Set( cpgExtent );
m_kdf.key.prefix.Nullify();
m_kdf.key.suffix.SetCb( m_spextkey.Cb() );
m_kdf.key.suffix.SetPv( (VOID*)m_spextkey.Pv() );
m_kdf.data.SetCb( m_spextdata.Cb() );
m_kdf.data.SetPv( (VOID*)m_spextdata.Pv() );
m_kdf.fFlags = 0;
m_fShouldDeleteNode = fFalse;
ASSERT_VALID( this );
}
class CSPExtentInfo;
ERR ErrConsumeSpace( __in const PGNO pgnoConsume, __in const CPG cpgConsume = 1 )
{
ASSERT_VALID( this );
Assert( pgnoConsume == PgnoFirst() );
Assert( pgnoConsume <= PgnoLast() );
if ( cpgConsume < 0 )
{
AssertSz( fFalse, "Consume space has a negative cpgConsume." );
return ErrERRCheck( JET_errInternalError );
}
else if ( cpgConsume != 1 )
{
Assert( pgnoConsume + cpgConsume - 1 <= PgnoLast() );
}
m_spextdata.Set( CpgExtent() - cpgConsume );
Assert( m_spextkey.FValid( m_eSpExtType, SPEXTKEY::fValidateData ) );
if ( m_spextkey.SppPool() != spp::ContinuousPool &&
CpgExtent() == 0 )
{
m_fShouldDeleteNode = fTrue;
}
if ( !m_fShouldDeleteNode && !FValid( ) )
{
AssertSz( fFalse, "Consume space has corrupted data." );
return ErrERRCheck( JET_errInternalError );
}
ASSERT_VALID( this );
return JET_errSuccess;
}
ERR ErrUnconsumeSpace( __in const CPG cpgConsume )
{
ASSERT_VALID( this );
m_spextdata.Set( CpgExtent() + cpgConsume );
if ( !FValid( ) )
{
AssertSz( fFalse, "Unconsume space has corrupted data." );
return ErrERRCheck( JET_errInternalError );
}
ASSERT_VALID( this );
return JET_errSuccess;
}
BOOL FDelete( void ) const
{
ASSERT_VALID( this );
return m_fShouldDeleteNode;
}
PGNO PgnoLast( void ) const
{
ASSERT_VALID( this );
Assert( m_kdf.key.Cb() == sizeof(PGNO) || m_kdf.key.Cb() == sizeof(SPEXTKEY) );
return m_spextkey.PgnoLast();
}
PGNO PgnoFirst( void ) const
{
ASSERT_VALID( this );
return PgnoLast() - CpgExtent() + 1;
}
CPG CpgExtent( void ) const
{
ASSERT_VALID( this );
return m_spextdata.CpgExtent();
}
const KEYDATAFLAGS * Pkdf( void ) const
{
ASSERT_VALID( this );
return &m_kdf;
}
const KEYDATAFLAGS& Kdf( void ) const
{
ASSERT_VALID( this );
return m_kdf;
}
BOOKMARK GetBm( FUCB * pfucb ) const
{
BOOKMARK bm;
Assert( pgnoBadNews != m_spextkey.PgnoLast() );
Assert( FFUCBUnique( pfucb ) );
NDGetBookmarkFromKDF( pfucb, Kdf(), &bm );
ASSERT_VALID( this );
return bm;
}
const KEY& GetKey( ) const
{
ASSERT_VALID( this );
return Kdf().key;
}
DATA GetData( ) const
{
ASSERT_VALID( this );
Assert( !m_fShouldDeleteNode );
return Kdf().data;
}
};
ERR ErrSPIExtentLastPgno( __in const FUCB * pfucb, __out PGNO * ppgnoLast )
{
const CSPExtentInfo spext( pfucb );
CallS( spext.ErrCheckCorrupted() );
*ppgnoLast = spext.PgnoLast();
return JET_errSuccess;
}
ERR ErrSPIExtentFirstPgno( __in const FUCB * pfucb, __out PGNO * ppgnoFirst )
{
const CSPExtentInfo spext( pfucb );
CallS( spext.ErrCheckCorrupted() );
*ppgnoFirst = spext.PgnoFirst();
return JET_errSuccess;
}
ERR ErrSPIExtentCpg( __in const FUCB * pfucb, __out CPG * pcpgSize )
{
const CSPExtentInfo spext( pfucb );
CallS( spext.ErrCheckCorrupted() );
*pcpgSize = spext.CpgExtent();
return JET_errSuccess;
}
ERR ErrSPIGetExtentInfo( __in const FUCB * pfucb, __out PGNO * ppgnoLast, __out CPG * pcpgSize, __out SpacePool * psppPool )
{
const CSPExtentInfo spext( pfucb );
CallS( spext.ErrCheckCorrupted() );
*ppgnoLast = spext.PgnoLast();
*pcpgSize = spext.CpgExtent();
*psppPool = spext.SppPool();
return JET_errSuccess;
}
ERR ErrSPIGetExtentInfo( __in const KEYDATAFLAGS * pkdf, __out PGNO * ppgnoLast, __out CPG * pcpgSize, __out SpacePool * psppPool )
{
const CSPExtentInfo spext( pkdf );
CallS( spext.ErrCheckCorrupted() );
*ppgnoLast = spext.PgnoLast();
*pcpgSize = spext.CpgExtent();
*psppPool = spext.SppPool();
return JET_errSuccess;
}
ERR ErrSPREPAIRValidateSpaceNode(
__in const KEYDATAFLAGS * pkdf,
__out PGNO * ppgnoLast,
__out CPG * pcpgExtent,
__out PCWSTR * pwszPoolName )
{
SpacePool spp;
ERR err = ErrSPIREPAIRValidateSpaceNode(
pkdf,
ppgnoLast,
pcpgExtent,
&spp
);
if ( JET_errSuccess <= err )
{
*pwszPoolName = WszPoolName( spp );
}
return err;
}
ERR ErrSPIREPAIRValidateSpaceNode(
__in const KEYDATAFLAGS * pkdf,
__out PGNO * ppgnoLast,
__out CPG * pcpgExtent,
__out SpacePool * psppPool )
{
ERR err = JET_errSuccess;
const CSPExtentInfo spext( pkdf );
Assert( pkdf );
Assert( ppgnoLast );
Assert( pcpgExtent );
Call( spext.ErrCheckCorrupted() );
*ppgnoLast = spext.PgnoLast();
*pcpgExtent = spext.CpgExtent();
*psppPool = spext.SppPool();
HandleError:
return err;
}
INLINE BOOL FSPIIsSmall( const FCB * const pfcb )
{
#ifdef DEBUG
Assert( pfcb->FSpaceInitialized() );
if ( pfcb->PgnoOE() == pgnoNull )
{
Assert( pfcb->PgnoAE() == pgnoNull );
Assert( FSPValidAllocPGNO( pfcb->PgnoFDP() ) );
if ( !FFMPIsTempDB( pfcb->Ifmp() ) )
{
Assert( !FCATBaseSystemFDP( pfcb->PgnoFDP() ) );
}
}
else
{
Assert( pfcb->PgnoAE() != pgnoNull );
Assert( pfcb->PgnoOE() + 1 == pfcb->PgnoAE() );
}
#endif
return pfcb->PgnoOE() == pgnoNull;
}
LOCAL VOID SPIUpgradeToWriteLatch( FUCB *pfucb )
{
CSR *pcsrT;
if ( Pcsr( pfucb )->Latch() == latchNone )
{
Assert( pfucb->pcsrRoot->Pgno() == PgnoFDP( pfucb ) );
pcsrT = pfucb->pcsrRoot;
Assert( latchRIW == pcsrT->Latch() || latchWrite == pcsrT->Latch() );
}
else
{
Assert( Pcsr( pfucb ) == pfucb->pcsrRoot );
Assert( Pcsr(pfucb)->Pgno() == PgnoFDP( pfucb ) );
pcsrT = &pfucb->csr;
}
if ( pcsrT->Latch() != latchWrite )
{
Assert( pcsrT->Latch() == latchRIW );
pcsrT->UpgradeFromRIWLatch();
}
else
{
#ifdef DEBUG
LINE lineSpaceHeader;
NDGetPtrExternalHeader( pcsrT->Cpage(), &lineSpaceHeader, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == lineSpaceHeader.cb );
SPACE_HEADER * psph = (SPACE_HEADER*)lineSpaceHeader.pv;
Assert( psph->FSingleExtent() );
Assert( !psph->FMultipleExtent() );
Assert( pcsrT->Cpage().FRootPage() );
Assert( pcsrT->Cpage().FInvisibleSons() );
#endif
}
}
ERR ErrSPIOpenAvailExt( PIB *ppib, FCB *pfcb, FUCB **ppfucbAE )
{
ERR err;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->nParentObjectClass = pfcb->TCE( fTrue );
tcScope->SetDwEngineObjid( pfcb->ObjidFDP() );
tcScope->iorReason.SetIort( iortSpace );
CallR( ErrBTOpen( ppib, pfcb, ppfucbAE, fFalse ) );
FUCBSetAvailExt( *ppfucbAE );
FUCBSetIndex( *ppfucbAE );
Assert( pfcb->FSpaceInitialized() );
Assert( pfcb->PgnoAE() != pgnoNull );
return err;
}
ERR ErrSPIOpenOwnExt( PIB *ppib, FCB *pfcb, FUCB **ppfucbOE )
{
ERR err;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->nParentObjectClass = pfcb->TCE( fTrue );
tcScope->SetDwEngineObjid( pfcb->ObjidFDP() );
tcScope->iorReason.SetIort( iortSpace );
CallR( ErrBTOpen( ppib, pfcb, ppfucbOE, fFalse ) );
FUCBSetOwnExt( *ppfucbOE );
FUCBSetIndex( *ppfucbOE );
Assert( pfcb->FSpaceInitialized() );
Assert( !FSPIIsSmall( pfcb ) );
return err;
}
ERR ErrSPGetLastPgno( _Inout_ PIB * ppib, _In_ const IFMP ifmp, _Out_ PGNO * ppgno )
{
ERR err;
EXTENTINFO extinfo;
Call( ErrSPGetLastExtent( ppib, ifmp, &extinfo ) );
*ppgno = extinfo.PgnoLast();
HandleError:
return err;
}
ERR ErrSPGetLastExtent( _Inout_ PIB * ppib, _In_ const IFMP ifmp, _Out_ EXTENTINFO * pextinfo )
{
ERR err;
FUCB *pfucb = pfucbNil;
FUCB *pfucbOE = pfucbNil;
DIB dib;
CallR( ErrBTOpen( ppib, pgnoSystemRoot, ifmp, &pfucb, openNormal, fTrue ) );
Assert( pfucbNil != pfucb );
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortSpace );
if ( PinstFromPpib( ppib )->FRecovering() && !pfucb->u.pfcb->FSpaceInitialized() )
{
Call( ErrSPInitFCB( pfucb ) );
pfucb->u.pfcb->Lock();
pfucb->u.pfcb->ResetInitedForRecovery();
pfucb->u.pfcb->Unlock();
}
Assert( pfucb->u.pfcb->FSpaceInitialized() );
Call( ErrSPIOpenOwnExt( ppib, pfucb->u.pfcb, &pfucbOE ) );
dib.dirflag = fDIRNull;
dib.pos = posLast;
dib.pbm = NULL;
err = ErrBTDown( pfucbOE, &dib, latchReadTouch );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
FireWall( "GetDbLastExtNoOwned" );
Error( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
Call( err );
{
const CSPExtentInfo spLastOE( pfucbOE );
Assert( spLastOE.FIsSet() && ( spLastOE.CpgExtent() > 0 ) );
pextinfo->pgnoLastInExtent = spLastOE.PgnoLast();
pextinfo->cpgExtent = spLastOE.CpgExtent();
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "%hs: ifmp=%d now has pgnoLast=%lu, cpgExtent=%ld",
__FUNCTION__, ifmp, pextinfo->PgnoLast(), pextinfo->CpgExtent() ) );
}
HandleError:
if ( pfucbOE != pfucbNil )
{
BTClose( pfucbOE );
}
Assert ( pfucb != pfucbNil );
BTClose( pfucb );
return err;
}
C_ASSERT( sizeof(SPACE_HEADER) == 16 );
LOCAL VOID SPIInitFCB( FUCB *pfucb, const BOOL fDeferredInit )
{
CSR * pcsr = ( fDeferredInit ? pfucb->pcsrRoot : Pcsr( pfucb ) );
FCB * pfcb = pfucb->u.pfcb;
Assert( pcsr->FLatched() );
pfcb->Lock();
if ( !pfcb->FSpaceInitialized() )
{
NDGetExternalHeader ( pfucb, pcsr, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
const SPACE_HEADER * const psph = reinterpret_cast <const SPACE_HEADER * const> ( pfucb->kdfCurr.data.Pv() );
if ( psph->FSingleExtent() )
{
pfcb->SetPgnoOE( pgnoNull );
pfcb->SetPgnoAE( pgnoNull );
}
else
{
pfcb->SetPgnoOE( psph->PgnoOE() );
pfcb->SetPgnoAE( psph->PgnoAE() );
Assert( pfcb->PgnoAE() == pfcb->PgnoOE() + 1 );
}
if ( !fDeferredInit )
{
Assert( pfcb->FUnique() );
if ( psph->FNonUnique() )
pfcb->SetNonUnique();
}
pfcb->SetSpaceInitialized();
#ifdef DEBUG
if( psph->FSingleExtent() )
{
Assert( FSPIIsSmall( pfcb ) );
}
else
{
Assert( !FSPIIsSmall( pfcb ) );
}
#endif
}
pfcb->Unlock();
return;
}
ERR ErrSPInitFCB( _Inout_ FUCB * const pfucb )
{
ERR err;
FCB *pfcb = pfucb->u.pfcb;
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->iorReason.SetIort( iortSpace );
tcScope->SetDwEngineObjid( pfcb->ObjidFDP() );
Assert( !Pcsr( pfucb )->FLatched() );
Assert( !FFUCBSpace( pfucb ) );
err = ErrBTIGotoRoot( pfucb, latchReadTouch );
if ( err < 0 )
{
if ( g_fRepair )
{
pfcb->SetPgnoOE( pgnoNull );
pfcb->SetPgnoAE( pgnoNull );
Assert( objidNil == pfcb->ObjidFDP() );
err = JET_errSuccess;
}
}
else
{
Assert( objidNil == pfcb->ObjidFDP()
|| ( PinstFromIfmp( pfucb->ifmp )->FRecovering() && pfcb->ObjidFDP() == Pcsr( pfucb )->Cpage().ObjidFDP() ) );
pfcb->SetObjidFDP( Pcsr( pfucb )->Cpage().ObjidFDP() );
SPIInitFCB( pfucb, fFalse );
BTUp( pfucb );
}
return err;
}
ERR ErrSPDeferredInitFCB( _Inout_ FUCB * const pfucb )
{
ERR err;
FCB * pfcb = pfucb->u.pfcb;
FUCB * pfucbT = pfucbNil;
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortSpace );
Assert( !Pcsr( pfucb )->FLatched() );
Assert( !FFUCBSpace( pfucb ) );
CallR( ErrBTIOpenAndGotoRoot(
pfucb->ppib,
pfcb->PgnoFDP(),
pfucb->ifmp,
&pfucbT ) );
Assert( pfucbNil != pfucbT );
Assert( pfucbT->u.pfcb == pfcb );
Assert( pcsrNil != pfucbT->pcsrRoot );
if ( !pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucbT, fTrue );
}
pfucbT->pcsrRoot->ReleasePage();
pfucbT->pcsrRoot = pcsrNil;
Assert( pfucbNil != pfucbT );
BTClose( pfucbT );
return JET_errSuccess;
}
INLINE const SPACE_HEADER * PsphSPIRootPage( FUCB* pfucb )
{
const SPACE_HEADER *psph;
AssertSPIPfucbOnRoot( pfucb );
NDGetExternalHeader( pfucb, pfucb->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
psph = reinterpret_cast <const SPACE_HEADER *> ( pfucb->kdfCurr.data.Pv() );
return psph;
}
PGNO PgnoSPIParentFDP( FUCB *pfucb )
{
return PsphSPIRootPage( pfucb )->PgnoParent();
}
BOOL FSPIsRootSpaceTree( const FUCB * const pfucb )
{
return ( ObjidFDP( pfucb ) == objidSystemRoot && FFUCBSpace( pfucb ) );
}
INLINE SPLIT_BUFFER *PspbufSPISpaceTreeRootPage( FUCB *pfucb, CSR *pcsr )
{
SPLIT_BUFFER *pspbuf;
AssertSPIPfucbOnSpaceTreeRoot( pfucb, pcsr );
NDGetExternalHeader( pfucb, pcsr, noderfWhole );
Assert( sizeof( SPLIT_BUFFER ) == pfucb->kdfCurr.data.Cb() );
pspbuf = reinterpret_cast <SPLIT_BUFFER *> ( pfucb->kdfCurr.data.Pv() );
return pspbuf;
}
INLINE VOID SPITraceSplitBufferMsg( const FUCB * const pfucb, const CHAR * const szMsg )
{
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal, OSFormat(
"Database '%ws'[ifmp=0x%x]: %s SplitBuffer for a Btree (objidFDP %u, pgnoFDP %u).",
g_rgfmp[pfucb->ifmp].WszDatabaseName(),
pfucb->ifmp,
szMsg,
pfucb->u.pfcb->ObjidFDP(),
pfucb->u.pfcb->PgnoFDP() ) );
}
LOCAL ERR ErrSPIFixSpaceTreeRootPage( FUCB *pfucb, SPLIT_BUFFER **ppspbuf )
{
ERR err = JET_errSuccess;
const BOOL fAvailExt = FFUCBAvailExt( pfucb );
AssertTrack( fFalse, "UnexpectedSpBufFixup" );
AssertSPIPfucbOnSpaceTreeRoot( pfucb, Pcsr( pfucb ) );
Assert( latchRIW == Pcsr( pfucb )->Latch() );
#ifdef DEBUG
const BOOL fNotEnoughPageSpace = ( Pcsr( pfucb )->Cpage().CbPageFree() < ( g_cbPage * 3 / 4 ) );
#else
const BOOL fNotEnoughPageSpace = ( Pcsr( pfucb )->Cpage().CbPageFree() < sizeof(SPLIT_BUFFER) );
#endif
if ( fNotEnoughPageSpace )
{
if ( NULL == pfucb->u.pfcb->Psplitbuf( fAvailExt ) )
{
CallR( pfucb->u.pfcb->ErrEnableSplitbuf( fAvailExt ) );
SPITraceSplitBufferMsg( pfucb, "Allocated" );
}
*ppspbuf = pfucb->u.pfcb->Psplitbuf( fAvailExt );
Assert( NULL != *ppspbuf );
}
else
{
const BOOL fSplitbufDangling = ( NULL != pfucb->u.pfcb->Psplitbuf( fAvailExt ) );
SPLIT_BUFFER spbuf;
DATA data;
Assert( 0 == pfucb->kdfCurr.data.Cb() );
if ( fSplitbufDangling )
{
memcpy( &spbuf, pfucb->u.pfcb->Psplitbuf( fAvailExt ), sizeof(SPLIT_BUFFER) );
}
else
{
memset( &spbuf, 0, sizeof(SPLIT_BUFFER) );
}
data.SetPv( &spbuf );
data.SetCb( sizeof(spbuf) );
Pcsr( pfucb )->UpgradeFromRIWLatch();
err = ErrNDSetExternalHeader(
pfucb,
&data,
( pfucb->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfWhole );
Pcsr( pfucb )->Downgrade( latchRIW );
CallR( err );
if ( fSplitbufDangling )
{
pfucb->u.pfcb->DisableSplitbuf( fAvailExt );
SPITraceSplitBufferMsg( pfucb, "Persisted" );
}
NDGetExternalHeader( pfucb, Pcsr( pfucb ), noderfWhole );
*ppspbuf = reinterpret_cast <SPLIT_BUFFER *> ( pfucb->kdfCurr.data.Pv() );
}
return err;
}
INLINE ERR ErrSPIGetSPBuf( FUCB *pfucb, SPLIT_BUFFER **ppspbuf )
{
ERR err;
AssertSPIPfucbOnSpaceTreeRoot( pfucb, Pcsr( pfucb ) );
NDGetExternalHeader( pfucb, Pcsr( pfucb ), noderfWhole );
if ( sizeof( SPLIT_BUFFER ) != pfucb->kdfCurr.data.Cb() )
{
AssertTrack( fFalse, "PersistedSpBufMissing" );
err = ErrSPIFixSpaceTreeRootPage( pfucb, ppspbuf );
}
else
{
Assert( NULL == pfucb->u.pfcb->Psplitbuf( FFUCBAvailExt( pfucb ) ) );
*ppspbuf = reinterpret_cast <SPLIT_BUFFER *> ( pfucb->kdfCurr.data.Pv() );
err = JET_errSuccess;
}
return err;
}
ERR ErrSPIGetSPBufUnlatched( __inout FUCB * pfucbSpace, __out_bcount(sizeof(SPLIT_BUFFER)) SPLIT_BUFFER * pspbuf )
{
ERR err = JET_errSuccess;
LINE line;
Assert( pspbuf );
Assert( pfucbSpace );
Assert( !Pcsr( pfucbSpace )->FLatched() );
CallR( ErrBTIGotoRoot( pfucbSpace, latchReadNoTouch ) );
Assert( Pcsr( pfucbSpace )->FLatched() );
NDGetPtrExternalHeader( Pcsr( pfucbSpace )->Cpage(), &line, noderfWhole );
if (sizeof( SPLIT_BUFFER ) == line.cb)
{
UtilMemCpy( (void*)pspbuf, line.pv, sizeof( SPLIT_BUFFER ) );
}
else
{
memset( (void*)pspbuf, 0, sizeof(SPLIT_BUFFER) );
Assert( 0 == pspbuf->CpgBuffer1() );
Assert( 0 == pspbuf->CpgBuffer2() );
}
BTUp( pfucbSpace );
return err;
}
LOCAL ERR ErrSPISPBufContains(
_In_ PIB* const ppib,
_In_ FCB* const pfcbFDP,
_In_ const PGNO pgno,
_In_ const BOOL fOwnExt,
_Out_ BOOL* const pfContains )
{
ERR err = JET_errSuccess;
FUCB* pfucbSpace = pfucbNil;
SPLIT_BUFFER* pspbuf;
if ( fOwnExt )
{
Call( ErrSPIOpenOwnExt( ppib, pfcbFDP, &pfucbSpace ) );
}
else
{
Call( ErrSPIOpenAvailExt( ppib, pfcbFDP, &pfucbSpace ) );
}
Call( ErrBTIGotoRoot( pfucbSpace, latchRIW ) );
Call( ErrSPIGetSPBuf( pfucbSpace, &pspbuf ) );
*pfContains = ( ( pgno >= ( pspbuf->PgnoLastBuffer1() - pspbuf->CpgBuffer1() + 1 ) ) &&
( pgno <= pspbuf->PgnoLastBuffer1() ) ) ||
( ( pgno >= ( pspbuf->PgnoLastBuffer2() - pspbuf->CpgBuffer2() + 1 ) ) &&
( pgno <= pspbuf->PgnoLastBuffer2() ) );
HandleError:
if ( pfucbSpace != pfucbNil )
{
BTUp( pfucbSpace );
BTClose( pfucbSpace );
pfucbSpace = pfucbNil;
}
return err;
}
INLINE VOID SPIDirtyAndSetMaxDbtime( CSR *pcsr1, CSR *pcsr2, CSR *pcsr3 )
{
#ifdef DEBUG
Assert( pcsr1->Latch() == latchWrite );
Assert( pcsr2->Latch() == latchWrite );
Assert( pcsr3->Latch() == latchWrite );
const IFMP ifmp = pcsr1->Cpage().Ifmp();
Assert( pcsr2->Cpage().Ifmp() == ifmp );
Assert( pcsr3->Cpage().Ifmp() == ifmp );
const BOOL fRedoImplicitCreateDb = ( PinstFromIfmp( ifmp )->m_plog->FRecoveringMode() == fRecoveringRedo ) &&
g_rgfmp[ifmp].FCreatingDB() &&
!FFMPIsTempDB( ifmp );
const DBTIME dbtimeMaxBefore = max( max( pcsr1->Dbtime(), pcsr2->Dbtime() ), pcsr3->Dbtime() );
if ( fRedoImplicitCreateDb )
{
Expected( pcsr1->Dbtime() < dbtimeStart );
Expected( pcsr2->Dbtime() < dbtimeStart );
Expected( pcsr3->Dbtime() < dbtimeStart );
Expected( pcsr1->Dbtime() != pcsr2->Dbtime() );
Expected( pcsr2->Dbtime() != pcsr3->Dbtime() );
Expected( pcsr1->Dbtime() != pcsr3->Dbtime() );
Expected( dbtimeMaxBefore -
min( min( pcsr1->Dbtime(), pcsr2->Dbtime() ), pcsr3->Dbtime() )
== 2 );
}
else if ( !g_fRepair )
{
Expected( pcsr1->Dbtime() >= dbtimeStart );
Expected( pcsr2->Dbtime() >= dbtimeStart );
Expected( pcsr3->Dbtime() >= dbtimeStart );
}
#endif
pcsr1->Dirty();
pcsr2->Dirty();
pcsr3->Dirty();
const DBTIME dbtimeMax = max( max( pcsr1->Dbtime(), pcsr2->Dbtime() ), pcsr3->Dbtime() );
#ifdef DEBUG
if ( fRedoImplicitCreateDb )
{
Expected( dbtimeMax < dbtimeStart );
Expected( ( dbtimeMax - dbtimeMaxBefore ) == 3 );
Expected( pcsr1->Dbtime() != pcsr2->Dbtime() );
Expected( pcsr2->Dbtime() != pcsr3->Dbtime() );
Expected( pcsr1->Dbtime() != pcsr3->Dbtime() );
Expected( dbtimeMax -
min( min( pcsr1->Dbtime(), pcsr2->Dbtime() ), pcsr3->Dbtime() )
== 2 );
}
else if ( !g_fRepair )
{
Expected( dbtimeMax >= dbtimeStart );
}
#endif
pcsr1->SetDbtime( dbtimeMax );
pcsr2->SetDbtime( dbtimeMax );
pcsr3->SetDbtime( dbtimeMax );
}
INLINE VOID SPIInitSplitBuffer( FUCB *pfucb, CSR *pcsr )
{
DATA data;
SPLIT_BUFFER spbuf;
memset( &spbuf, 0, sizeof(SPLIT_BUFFER) );
Assert( FBTIUpdatablePage( *pcsr ) );
Assert( latchWrite == pcsr->Latch() );
Assert( pcsr->FDirty() );
Assert( pgnoNull != PgnoAE( pfucb ) || g_fRepair );
Assert( pgnoNull != PgnoOE( pfucb ) || g_fRepair );
Assert( ( FFUCBAvailExt( pfucb ) && pcsr->Pgno() == PgnoAE( pfucb ) )
|| ( FFUCBOwnExt( pfucb ) && pcsr->Pgno() == PgnoOE( pfucb ) )
|| g_fRepair );
data.SetPv( (VOID *)&spbuf );
data.SetCb( sizeof(spbuf) );
NDSetExternalHeader( pfucb, pcsr, noderfWhole, &data );
}
VOID SPICreateExtentTree( FUCB *pfucb, CSR *pcsr, PGNO pgnoLast, CPG cpgExtent, BOOL fAvail )
{
if ( !FBTIUpdatablePage( *pcsr ) )
{
return;
}
Assert( !FFUCBVersioned( pfucb ) );
Assert( !FFUCBSpace( pfucb ) );
Assert( pgnoNull != PgnoAE( pfucb ) || g_fRepair );
Assert( pgnoNull != PgnoOE( pfucb ) || g_fRepair );
Assert( latchWrite == pcsr->Latch() );
Assert( pcsr->FDirty() );
if ( fAvail )
{
FUCBSetAvailExt( pfucb );
}
else
{
FUCBSetOwnExt( pfucb );
}
Assert( pcsr->FDirty() );
SPIInitSplitBuffer( pfucb, pcsr );
Assert( 0 == pcsr->Cpage().Clines() );
pcsr->SetILine( 0 );
if ( cpgExtent != 0 )
{
const CSPExtentNodeKDF spextnode( fAvail ?
SPEXTKEY::fSPExtentTypeAE :
SPEXTKEY::fSPExtentTypeOE,
pgnoLast, cpgExtent );
NDInsert( pfucb, pcsr, spextnode.Pkdf() );
}
else
{
Assert( FFUCBAvailExt( pfucb ) );
}
if ( fAvail )
{
FUCBResetAvailExt( pfucb );
}
else
{
FUCBResetOwnExt( pfucb );
}
return;
}
VOID SPIInitPgnoFDP( FUCB *pfucb, CSR *pcsr, const SPACE_HEADER& sph )
{
if ( !FBTIUpdatablePage( *pcsr ) )
{
return;
}
Assert( latchWrite == pcsr->Latch() );
Assert( pcsr->FDirty() );
Assert( pcsr->Pgno() == PgnoFDP( pfucb ) || g_fRepair );
DATA data;
data.SetPv( (VOID *)&sph );
data.SetCb( sizeof(sph) );
NDSetExternalHeader( pfucb, pcsr, noderfSpaceHeader, &data );
}
ERR ErrSPIImproveLastAlloc( FUCB * pfucb, const SPACE_HEADER * const psph, CPG cpgLast )
{
ERR err = JET_errSuccess;
AssertSPIPfucbOnRoot( pfucb );
if ( psph->FSingleExtent() )
{
return JET_errSuccess;
}
Assert( psph->FMultipleExtent() );
SPACE_HEADER sphSet;
memcpy( &sphSet, psph, sizeof(sphSet) );
sphSet.SetCpgLast( cpgLast );
DATA data;
data.SetPv( &sphSet );
data.SetCb( sizeof(sphSet) );
if ( latchWrite != pfucb->pcsrRoot->Latch() )
{
Assert( pfucb->pcsrRoot->Latch() == latchRIW );
SPIUpgradeToWriteLatch( pfucb );
}
Assert( pfucb->pcsrRoot->Latch() == latchWrite );
CallR( ErrNDSetExternalHeader( pfucb, pfucb->pcsrRoot, &data,
( pfucb->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfSpaceHeader ) );
return err;
}
VOID SPIPerformCreateMultiple( FUCB *pfucb, CSR *pcsrFDP, CSR *pcsrOE, CSR *pcsrAE, PGNO pgnoPrimary, const SPACE_HEADER& sph )
{
const CPG cpgPrimary = sph.CpgPrimary();
const PGNO pgnoLast = pgnoPrimary;
Assert( g_fRepair || pgnoLast == PgnoFDP( pfucb ) + cpgPrimary - 1 );
Assert( FBTIUpdatablePage( *pcsrFDP ) );
Assert( FBTIUpdatablePage( *pcsrOE ) );
Assert( FBTIUpdatablePage( *pcsrAE ) );
SPIInitPgnoFDP( pfucb, pcsrFDP, sph );
SPICreateExtentTree( pfucb, pcsrOE, pgnoLast, cpgPrimary, fFalse );
SPICreateExtentTree( pfucb, pcsrAE, pgnoLast, cpgPrimary - 1 - 1 - 1, fTrue );
return;
}
ERR ErrSPCreateMultiple(
FUCB *pfucb,
const PGNO pgnoParent,
const PGNO pgnoFDP,
const OBJID objidFDP,
const PGNO pgnoOE,
const PGNO pgnoAE,
const PGNO pgnoPrimary,
const CPG cpgPrimary,
const BOOL fUnique,
const ULONG fPageFlags )
{
ERR err;
CSR csrOE;
CSR csrAE;
CSR csrFDP;
SPACE_HEADER sph;
LGPOS lgpos;
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortSpace );
Assert( objidFDP == ObjidFDP( pfucb ) || g_fRepair );
Assert( objidFDP != objidNil );
Assert( !( fPageFlags & CPAGE::fPageRoot ) );
Assert( !( fPageFlags & CPAGE::fPageLeaf ) );
Assert( !( fPageFlags & CPAGE::fPageParentOfLeaf ) );
Assert( !( fPageFlags & CPAGE::fPageEmpty ) );
Assert( !( fPageFlags & CPAGE::fPagePreInit ) );
Assert( !( fPageFlags & CPAGE::fPageSpaceTree) );
const BOOL fLogging = g_rgfmp[pfucb->ifmp].FLogOn();
Call( csrOE.ErrGetNewPreInitPage( pfucb->ppib,
pfucb->ifmp,
pgnoOE,
objidFDP,
fLogging ) );
csrOE.ConsumePreInitPage( ( fPageFlags | CPAGE::fPageRoot | CPAGE::fPageLeaf | CPAGE::fPageSpaceTree ) & ~CPAGE::fPageRepair );
Assert( csrOE.Latch() == latchWrite );
Call( csrAE.ErrGetNewPreInitPage( pfucb->ppib,
pfucb->ifmp,
pgnoAE,
objidFDP,
fLogging ) );
csrAE.ConsumePreInitPage( ( fPageFlags | CPAGE::fPageRoot | CPAGE::fPageLeaf | CPAGE::fPageSpaceTree ) & ~CPAGE::fPageRepair );
Assert( csrAE.Latch() == latchWrite );
Call( csrFDP.ErrGetNewPreInitPage( pfucb->ppib,
pfucb->ifmp,
pgnoFDP,
objidFDP,
fLogging ) );
csrFDP.ConsumePreInitPage( fPageFlags | CPAGE::fPageRoot | CPAGE::fPageLeaf );
Assert( csrFDP.Latch() == latchWrite );
SPIDirtyAndSetMaxDbtime( &csrFDP, &csrOE, &csrAE );
sph.SetCpgPrimary( cpgPrimary );
sph.SetPgnoParent( pgnoParent );
Assert( sph.FSingleExtent() );
Assert( sph.FUnique() );
sph.SetMultipleExtent();
if ( !fUnique )
{
sph.SetNonUnique();
}
sph.SetPgnoOE( pgnoOE );
Assert( ( PinstFromPfucb( pfucb )->m_plog->FRecoveringMode() != fRecoveringRedo ) ||
( !g_rgfmp[pfucb->ifmp].FLogOn() && g_rgfmp[pfucb->ifmp].FCreatingDB() ) );
Call( ErrLGCreateMultipleExtentFDP( pfucb, &csrFDP, &sph, fPageFlags, &lgpos ) );
csrFDP.Cpage().SetLgposModify( lgpos );
csrOE.Cpage().SetLgposModify( lgpos );
csrAE.Cpage().SetLgposModify( lgpos );
csrFDP.FinalizePreInitPage();
csrOE.FinalizePreInitPage();
csrAE.FinalizePreInitPage();
SPIPerformCreateMultiple( pfucb, &csrFDP, &csrOE, &csrAE, pgnoPrimary, sph );
HandleError:
csrAE.ReleasePage();
csrOE.ReleasePage();
csrFDP.ReleasePage();
return err;
}
INLINE ERR ErrSPICreateMultiple(
FUCB *pfucb,
const PGNO pgnoParent,
const PGNO pgnoFDP,
const OBJID objidFDP,
const CPG cpgPrimary,
const ULONG fPageFlags,
const BOOL fUnique )
{
return ErrSPCreateMultiple(
pfucb,
pgnoParent,
pgnoFDP,
objidFDP,
pgnoFDP + 1,
pgnoFDP + 2,
pgnoFDP + cpgPrimary - 1,
cpgPrimary,
fUnique,
fPageFlags );
}
ERR ErrSPICreateSingle(
FUCB *pfucb,
CSR *pcsr,
const PGNO pgnoParent,
const PGNO pgnoFDP,
const OBJID objidFDP,
CPG cpgPrimary,
const BOOL fUnique,
const ULONG fPageFlags,
const DBTIME dbtime )
{
ERR err;
SPACE_HEADER sph;
const BOOL fRedo = ( PinstFromPfucb( pfucb )->m_plog->FRecoveringMode() == fRecoveringRedo );
Assert( ( !fRedo && ( dbtime == dbtimeNil ) ) ||
( fRedo && ( dbtime != dbtimeNil ) ) ||
( fRedo && ( dbtime == dbtimeNil ) && g_rgfmp[pfucb->ifmp].FCreatingDB() && !g_rgfmp[pfucb->ifmp].FLogOn() ) );
sph.SetPgnoParent( pgnoParent );
sph.SetCpgPrimary( cpgPrimary );
Assert( sph.FSingleExtent() );
Assert( sph.FUnique() );
Assert( !( fPageFlags & CPAGE::fPageRoot ) );
Assert( !( fPageFlags & CPAGE::fPageLeaf ) );
Assert( !( fPageFlags & CPAGE::fPageParentOfLeaf ) );
Assert( !( fPageFlags & CPAGE::fPageEmpty ) );
Assert( !( fPageFlags & CPAGE::fPagePreInit ) );
Assert( !( fPageFlags & CPAGE::fPageSpaceTree) );
if ( !fUnique )
sph.SetNonUnique();
Assert( cpgPrimary > 0 );
if ( cpgPrimary > cpgSmallSpaceAvailMost )
{
sph.SetRgbitAvail( 0xffffffff );
}
else
{
sph.SetRgbitAvail( 0 );
while ( --cpgPrimary > 0 )
{
sph.SetRgbitAvail( ( sph.RgbitAvail() << 1 ) + 1 );
}
}
Assert( objidFDP == ObjidFDP( pfucb ) );
Assert( objidFDP != 0 );
const ULONG fInitPageFlags = fPageFlags | CPAGE::fPageRoot | CPAGE::fPageLeaf;
if ( !fRedo || ( dbtime == dbtimeNil ) )
{
Call( pcsr->ErrGetNewPreInitPage(
pfucb->ppib,
pfucb->ifmp,
pgnoFDP,
objidFDP,
!fRedo && g_rgfmp[pfucb->ifmp].FLogOn() ) );
pcsr->ConsumePreInitPage( fInitPageFlags );
if ( !fRedo )
{
LGPOS lgpos;
Call( ErrLGCreateSingleExtentFDP( pfucb, pcsr, &sph, fPageFlags, &lgpos ) );
pcsr->Cpage().SetLgposModify( lgpos );
}
}
else
{
Call( pcsr->ErrGetNewPreInitPageForRedo(
pfucb->ppib,
pfucb->ifmp,
pgnoFDP,
objidFDP,
dbtime ) );
pcsr->ConsumePreInitPage( fInitPageFlags );
}
Assert( pcsr->FDirty() );
SPIInitPgnoFDP( pfucb, pcsr, sph );
pcsr->FinalizePreInitPage();
BTUp( pfucb );
HandleError:
return err;
}
ERR ErrSPCreate(
PIB *ppib,
const IFMP ifmp,
const PGNO pgnoParent,
const PGNO pgnoFDP,
const CPG cpgPrimary,
const ULONG fSPFlags,
const ULONG fPageFlags,
OBJID *pobjidFDP )
{
ERR err;
FUCB *pfucb = pfucbNil;
const BOOL fUnique = !( fSPFlags & fSPNonUnique );
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortSpace );
Assert( NULL != pobjidFDP );
Assert( !( fPageFlags & CPAGE::fPageRoot ) );
Assert( !( fPageFlags & CPAGE::fPageLeaf ) );
Assert( !( fPageFlags & CPAGE::fPageParentOfLeaf ) );
Assert( !( fPageFlags & CPAGE::fPageEmpty ) );
Assert( !( fPageFlags & CPAGE::fPageSpaceTree ) );
if ( pgnoFDP == pgnoSystemRoot &&
pgnoParent == pgnoNull &&
g_rgfmp[ifmp].FLogOn() &&
!PinstFromIfmp( ifmp )->m_plog->FRecovering() )
{
#ifdef DEBUG
QWORD cbSize = 0;
if ( g_rgfmp[ifmp].Pfapi()->ErrSize( &cbSize, IFileAPI::filesizeLogical ) >= JET_errSuccess )
{
Assert( ( cbSize / g_cbPage - cpgDBReserved ) == cpgPrimary );
}
#endif
Assert( cpgPrimary >= CpgDBDatabaseMinMin() ||
FFMPIsTempDB( ifmp ) );
LGPOS lgposExtend;
Call( ErrLGExtendDatabase( PinstFromIfmp( ifmp )->m_plog, ifmp, cpgPrimary, &lgposExtend ) );
Call( ErrIOResizeUpdateDbHdrCount( ifmp, fTrue ) );
if ( ( g_rgfmp[ ifmp ].ErrDBFormatFeatureEnabled( JET_efvLgposLastResize ) == JET_errSuccess ) )
{
Expected( fFalse );
Call( ErrIOResizeUpdateDbHdrLgposLast( ifmp, lgposExtend ) );
}
}
CallR( ErrBTOpen( ppib, pgnoFDP, ifmp, &pfucb, openNew ) );
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
FCB *pfcb = pfucb->u.pfcb;
Assert( pfcbNil != pfcb );
if ( pgnoSystemRoot == pgnoFDP )
{
Assert( pfcb->FInitialized() );
Assert( pfcb->FTypeDatabase() );
}
else
{
Assert( !pfcb->FInitialized() );
Assert( pfcb->FTypeNull() );
}
Assert( pfcb->FUnique() );
if ( !fUnique )
{
pfcb->Lock();
pfcb->SetNonUnique();
pfcb->Unlock();
}
if ( g_fRepair && pgnoSystemRoot == pgnoFDP )
{
*pobjidFDP = objidSystemRoot;
}
else
{
Call( g_rgfmp[ pfucb->ifmp ].ErrObjidLastIncrementAndGet( pobjidFDP ) );
}
Assert( pgnoSystemRoot != pgnoFDP || objidSystemRoot == *pobjidFDP );
Assert( objidNil == pfcb->ObjidFDP() || g_fRepair );
pfcb->SetObjidFDP( *pobjidFDP );
tcScope->SetDwEngineObjid( *pobjidFDP );
Assert( !pfcb->FSpaceInitialized() || g_fRepair );
pfcb->Lock();
pfcb->SetSpaceInitialized();
pfcb->Unlock();
if ( fSPFlags & fSPMultipleExtent )
{
Assert( PgnoFDP( pfucb ) == pgnoFDP );
pfcb->SetPgnoOE( pgnoFDP + 1 );
pfcb->SetPgnoAE( pgnoFDP + 2 );
err = ErrSPICreateMultiple(
pfucb,
pgnoParent,
pgnoFDP,
*pobjidFDP,
cpgPrimary,
fPageFlags,
fUnique );
}
else
{
Assert( PgnoFDP( pfucb ) == pgnoFDP );
pfcb->SetPgnoOE( pgnoNull );
pfcb->SetPgnoAE( pgnoNull );
err = ErrSPICreateSingle(
pfucb,
Pcsr( pfucb ),
pgnoParent,
pgnoFDP,
*pobjidFDP,
cpgPrimary,
fUnique,
fPageFlags,
dbtimeNil );
}
Assert( !FFUCBSpace( pfucb ) );
Assert( !FFUCBVersioned( pfucb ) );
HandleError:
Assert( ( pfucb != pfucbNil ) || ( err < JET_errSuccess ) );
if ( pfucb != pfucbNil )
{
BTClose( pfucb );
}
return err;
}
VOID SPIConvertCalcExtents(
const SPACE_HEADER& sph,
const PGNO pgnoFDP,
EXTENTINFO *rgext,
INT *pcext )
{
PGNO pgno;
UINT rgbit = 0x80000000;
INT iextMac = 0;
if ( sph.CpgPrimary() - 1 > cpgSmallSpaceAvailMost )
{
pgno = pgnoFDP + sph.CpgPrimary() - 1;
rgext[iextMac].pgnoLastInExtent = pgno;
rgext[iextMac].cpgExtent = sph.CpgPrimary() - cpgSmallSpaceAvailMost - 1;
Assert( rgext[iextMac].FValid() );
pgno -= rgext[iextMac].CpgExtent();
iextMac++;
Assert( pgnoFDP + cpgSmallSpaceAvailMost == pgno );
Assert( 0x80000000 == rgbit );
}
else
{
pgno = pgnoFDP + cpgSmallSpaceAvailMost;
while ( 0 != rgbit && 0 == iextMac )
{
Assert( pgno > pgnoFDP );
if ( rgbit & sph.RgbitAvail() )
{
Assert( pgno <= pgnoFDP + sph.CpgPrimary() - 1 );
rgext[iextMac].pgnoLastInExtent = pgno;
rgext[iextMac].cpgExtent = 1;
Assert( rgext[iextMac].FValid() );
iextMac++;
}
pgno--;
rgbit >>= 1;
}
}
Assert( ( 0 == iextMac && 0 == rgbit )
|| 1 == iextMac );
for ( ; rgbit != 0; pgno--, rgbit >>= 1 )
{
Assert( pgno > pgnoFDP );
if ( rgbit & sph.RgbitAvail() )
{
const INT iextPrev = iextMac - 1;
Assert( rgext[iextPrev].CpgExtent() > 0 );
Assert( (ULONG)rgext[iextPrev].CpgExtent() <= rgext[iextPrev].PgnoLast() );
Assert( rgext[iextPrev].PgnoLast() <= pgnoFDP + sph.CpgPrimary() - 1 );
const PGNO pgnoFirst = rgext[iextPrev].PgnoLast() - rgext[iextPrev].CpgExtent() + 1;
Assert( pgnoFirst > pgnoFDP );
if ( pgnoFirst - 1 == pgno )
{
Assert( pgnoFirst - 1 > pgnoFDP );
rgext[iextPrev].cpgExtent++;
Assert( rgext[iextPrev].FValid() );
}
else
{
rgext[iextMac].pgnoLastInExtent = pgno;
rgext[iextMac].cpgExtent = 1;
Assert( rgext[iextMac].FValid() );
iextMac++;
}
}
}
*pcext = iextMac;
}
LOCAL VOID SPIConvertUpdateOE( FUCB *pfucb, CSR *pcsrOE, const SPACE_HEADER& sph, PGNO pgnoSecondaryFirst, CPG cpgSecondary )
{
if ( !FBTIUpdatablePage( *pcsrOE ) )
{
Assert( PinstFromIfmp( pfucb->ifmp )->FRecovering() );
return;
}
Assert( pcsrOE->Latch() == latchWrite );
Assert( !FFUCBOwnExt( pfucb ) );
FUCBSetOwnExt( pfucb );
SPIInitSplitBuffer( pfucb, pcsrOE );
Assert( 0 == pcsrOE->Cpage().Clines() );
Assert( cpgSecondary != 0 );
pcsrOE->SetILine( 0 );
const CSPExtentNodeKDF spextSecondary( SPEXTKEY::fSPExtentTypeOE, pgnoSecondaryFirst + cpgSecondary - 1, cpgSecondary );
NDInsert( pfucb, pcsrOE, spextSecondary.Pkdf() );
const CSPExtentNodeKDF spextPrimary( SPEXTKEY::fSPExtentTypeOE, PgnoFDP( pfucb ) + sph.CpgPrimary() - 1, sph.CpgPrimary() );
const BOOKMARK bm = spextPrimary.GetBm( pfucb );
const ERR err = ErrNDSeek( pfucb, pcsrOE, bm );
AssertRTL( wrnNDFoundLess == err || wrnNDFoundGreater == err );
if ( wrnNDFoundLess == err )
{
Assert( pcsrOE->Cpage().Clines() - 1 == pcsrOE->ILine() );
pcsrOE->IncrementILine();
}
NDInsert( pfucb, pcsrOE, spextPrimary.Pkdf() );
FUCBResetOwnExt( pfucb );
}
LOCAL VOID SPIConvertUpdateAE(
FUCB *pfucb,
CSR *pcsrAE,
EXTENTINFO *rgext,
INT iextMac,
PGNO pgnoSecondaryFirst,
CPG cpgSecondary )
{
if ( !FBTIUpdatablePage( *pcsrAE ) )
{
Assert( PinstFromIfmp( pfucb->ifmp )->FRecovering() );
return;
}
Assert( iextMac >= 0 );
if ( iextMac < 0 )
{
return;
}
Assert( pcsrAE->Latch() == latchWrite );
Assert( !FFUCBAvailExt( pfucb ) );
FUCBSetAvailExt( pfucb );
SPIInitSplitBuffer( pfucb, pcsrAE );
Assert( cpgSecondary >= 2 );
Assert( 0 == pcsrAE->Cpage().Clines() );
pcsrAE->SetILine( 0 );
CPG cpgExtent = cpgSecondary - 1 - 1;
PGNO pgnoLast = pgnoSecondaryFirst + cpgSecondary - 1;
if ( cpgExtent != 0 )
{
const CSPExtentNodeKDF spavailextSecondary( SPEXTKEY::fSPExtentTypeAE, pgnoLast, cpgExtent );
NDInsert( pfucb, pcsrAE, spavailextSecondary.Pkdf() );
}
Assert( latchWrite == pcsrAE->Latch() );
for ( INT iext = iextMac - 1; iext >= 0; iext-- )
{
Assert( rgext[iext].CpgExtent() > 0 );
#ifdef DEBUG
if ( iext > 0 )
{
Assert( rgext[iext].PgnoLast() < rgext[iext-1].PgnoLast() );
}
#endif
AssertTrack( rgext[iext].FValid(), "SPConvertInvalidExtInfo" );
const CSPExtentNodeKDF spavailextCurr( SPEXTKEY::fSPExtentTypeAE, rgext[iext].PgnoLast(), rgext[iext].CpgExtent() );
if ( 0 < pcsrAE->Cpage().Clines() )
{
const BOOKMARK bm = spavailextCurr.GetBm( pfucb );
ERR err;
err = ErrNDSeek( pfucb, pcsrAE, bm );
AssertRTL( wrnNDFoundLess == err || wrnNDFoundGreater == err );
if ( wrnNDFoundLess == err )
pcsrAE->IncrementILine();
}
NDInsert( pfucb, pcsrAE, spavailextCurr.Pkdf() );
}
FUCBResetAvailExt( pfucb );
Assert( pcsrAE->Latch() == latchWrite );
}
INLINE VOID SPIConvertUpdateFDP( FUCB *pfucb, CSR *pcsrRoot, SPACE_HEADER *psph )
{
if ( FBTIUpdatablePage( *pcsrRoot ) )
{
DATA data;
Assert( latchWrite == pcsrRoot->Latch() );
Assert( pcsrRoot->FDirty() );
data.SetPv( psph );
data.SetCb( sizeof( *psph ) );
NDSetExternalHeader( pfucb, pcsrRoot, noderfSpaceHeader, &data );
}
else
{
Assert( PinstFromIfmp( pfucb->ifmp )->FRecovering() );
}
}
VOID SPIPerformConvert( FUCB *pfucb,
CSR *pcsrRoot,
CSR *pcsrAE,
CSR *pcsrOE,
SPACE_HEADER *psph,
PGNO pgnoSecondaryFirst,
CPG cpgSecondary,
EXTENTINFO *rgext,
INT iextMac )
{
SPIConvertUpdateOE( pfucb, pcsrOE, *psph, pgnoSecondaryFirst, cpgSecondary );
SPIConvertUpdateAE( pfucb, pcsrAE, rgext, iextMac, pgnoSecondaryFirst, cpgSecondary );
SPIConvertUpdateFDP( pfucb, pcsrRoot, psph );
}
VOID SPIConvertGetExtentinfo( FUCB *pfucb,
CSR *pcsrRoot,
SPACE_HEADER *psph,
EXTENTINFO *rgext,
INT *piextMac )
{
NDGetExternalHeader( pfucb, pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
UtilMemCpy( psph, pfucb->kdfCurr.data.Pv(), sizeof(SPACE_HEADER) );
SPIConvertCalcExtents( *psph, PgnoFDP( pfucb ), rgext, piextMac );
}
LOCAL ERR ErrSPIConvertToMultipleExtent( FUCB *pfucb, CPG cpgReq, CPG cpgMin, BOOL fUseSpaceHints = fTrue )
{
ERR err;
SPACE_HEADER sph;
PGNO pgnoSecondaryFirst = pgnoNull;
INT iextMac = 0;
UINT rgbitAvail;
FUCB *pfucbT;
CSR csrOE;
CSR csrAE;
CSR *pcsrRoot = pfucb->pcsrRoot;
DBTIME dbtimeBefore = dbtimeNil;
ULONG fFlagsBefore = 0;
LGPOS lgpos = lgposMin;
EXTENTINFO rgextT[(cpgSmallSpaceAvailMost+1)/2 + 1];
Assert( NULL != pcsrRoot );
Assert( latchRIW == pcsrRoot->Latch() );
AssertSPIPfucbOnRoot( pfucb );
Assert( !FFUCBSpace( pfucb ) );
Assert( ObjidFDP( pfucb ) != objidNil );
Assert( pfucb->u.pfcb->FSpaceInitialized() );
const ULONG fPageFlags = pcsrRoot->Cpage().FFlags()
& ~CPAGE::fPageRepair
& ~CPAGE::fPageRoot
& ~CPAGE::fPageLeaf
& ~CPAGE::fPageParentOfLeaf;
SPIConvertGetExtentinfo( pfucb, pcsrRoot, &sph, rgextT, &iextMac );
Assert( sph.FSingleExtent() );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal,
OSFormat( "ConvertSMALLToMultiExt(%d.%d)-> ", pfucb->u.pfcb->PgnoFDP(), sph.CpgPrimary() ) );
rgbitAvail = sph.RgbitAvail();
CallR( ErrBTOpen( pfucb->ppib, pfucb->u.pfcb, &pfucbT, fFalse ) );
cpgMin += cpgMultipleExtentConvert;
cpgReq = max( cpgMin, cpgReq );
if ( fUseSpaceHints )
{
CPG cpgNext = CpgSPIGetNextAlloc( pfucb->u.pfcb->Pfcbspacehints(), sph.CpgPrimary() );
cpgReq = max( cpgNext, cpgReq );
}
Assert( sph.PgnoParent() != pgnoNull );
Call( ErrSPGetExt( pfucbT, sph.PgnoParent(), &cpgReq, cpgMin, &pgnoSecondaryFirst ) );
Assert( cpgReq >= cpgMin );
Assert( pgnoSecondaryFirst != pgnoNull );
Assert( pgnoSecondaryFirst != pgnoNull );
sph.SetMultipleExtent();
sph.SetPgnoOE( pgnoSecondaryFirst );
Assert( !FFUCBVersioned( pfucbT ) );
Assert( !FFUCBSpace( pfucbT ) );
const BOOL fLogging = !pfucb->u.pfcb->FDontLogSpaceOps() && g_rgfmp[pfucb->ifmp].FLogOn();
Call( csrOE.ErrGetNewPreInitPage( pfucbT->ppib,
pfucbT->ifmp,
sph.PgnoOE(),
ObjidFDP( pfucbT ),
fLogging ) );
csrOE.ConsumePreInitPage( fPageFlags | CPAGE::fPageRoot | CPAGE::fPageLeaf | CPAGE::fPageSpaceTree );
Assert( latchWrite == csrOE.Latch() );
Call( csrAE.ErrGetNewPreInitPage( pfucbT->ppib,
pfucbT->ifmp,
sph.PgnoAE(),
ObjidFDP( pfucbT ),
fLogging ) );
csrAE.ConsumePreInitPage( fPageFlags | CPAGE::fPageRoot | CPAGE::fPageLeaf | CPAGE::fPageSpaceTree );
Assert( latchWrite == csrAE.Latch() );
SPIUpgradeToWriteLatch( pfucb );
dbtimeBefore = pfucb->pcsrRoot->Dbtime();
fFlagsBefore = pfucb->pcsrRoot->Cpage().FFlags();
Assert ( dbtimeNil != dbtimeBefore );
SPIDirtyAndSetMaxDbtime( pfucb->pcsrRoot, &csrOE, &csrAE );
if ( pfucb->pcsrRoot->Dbtime() > dbtimeBefore )
{
if ( !fLogging )
{
Assert( 0 == CmpLgpos( lgpos, lgposMin ) );
err = JET_errSuccess;
}
else
{
err = ErrLGConvertFDP(
pfucb,
pcsrRoot,
&sph,
pgnoSecondaryFirst,
cpgReq,
dbtimeBefore,
rgbitAvail,
fPageFlags,
&lgpos );
}
}
else
{
FireWall( "ConvertToMultiExtDbTimeTooLow" );
OSUHAEmitFailureTag( PinstFromPfucb( pfucb ), HaDbFailureTagCorruption, L"b4c2850e-04f0-4476-b967-2420fdcb6663" );
err = ErrERRCheck( JET_errDbTimeCorrupted );
}
if ( err < JET_errSuccess )
{
pfucb->pcsrRoot->RevertDbtime( dbtimeBefore, fFlagsBefore );
}
Call ( err );
pfucb->u.pfcb->SetPgnoOE( sph.PgnoOE() );
pfucb->u.pfcb->SetPgnoAE( sph.PgnoAE() );
Assert( pgnoNull != PgnoAE( pfucb ) );
Assert( pgnoNull != PgnoOE( pfucb ) );
pcsrRoot->Cpage().SetLgposModify( lgpos );
csrOE.Cpage().SetLgposModify( lgpos );
csrAE.Cpage().SetLgposModify( lgpos );
SPIPerformConvert(
pfucbT,
pcsrRoot,
&csrAE,
&csrOE,
&sph,
pgnoSecondaryFirst,
cpgReq,
rgextT,
iextMac );
csrOE.FinalizePreInitPage();
csrAE.FinalizePreInitPage();
AssertSPIPfucbOnRoot( pfucb );
Assert( pfucb->pcsrRoot->Latch() == latchWrite );
HandleError:
Assert( err != JET_errKeyDuplicate );
csrAE.ReleasePage();
csrOE.ReleasePage();
Assert( pfucbT != pfucbNil );
BTClose( pfucbT );
return err;
}
ERR ErrSPBurstSpaceTrees( FUCB *pfucb )
{
ERR err = JET_errSuccess;
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
Call( ErrSPIConvertToMultipleExtent(
pfucb,
0,
0,
fFalse ) );
HandleError:
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
return err;
}
INLINE BOOL FSPIAllocateAllAvail(
const CSPExtentInfo * pcspaei,
const CPG cpgReq,
const LONG lPageFragment,
const PGNO pgnoFDP,
const CPG cpgDb,
const BOOL fSPFlags )
{
BOOL fAllocateAllAvail = fTrue;
if ( pcspaei->CpgExtent() > cpgReq )
{
if ( BoolSetFlag( fSPFlags, fSPExactExtent ) )
{
fAllocateAllAvail = fFalse;
}
else if ( pgnoSystemRoot == pgnoFDP )
{
if ( BoolSetFlag( fSPFlags, fSPNewFDP ) && cpgDb < cpgSmallDbSpaceSize && pcspaei->PgnoFirst() < pgnoSmallDbSpaceStart )
{
fAllocateAllAvail = fFalse;
}
if ( pcspaei->CpgExtent() >= cpgReq + cpgSmallGrow )
{
fAllocateAllAvail = fFalse;
}
}
else if ( cpgReq < lPageFragment || pcspaei->CpgExtent() >= cpgReq + lPageFragment )
{
fAllocateAllAvail = fFalse;
}
}
return fAllocateAllAvail;
}
LOCAL INLINE ERR ErrSPIFindExt(
__inout FUCB * pfucb,
__in const PGNO pgno,
__in const SpacePool sppAvailPool,
__in const SPEXTKEY::E_SP_EXTENT_TYPE eExtType,
__out CSPExtentInfo * pspei )
{
Assert( ( eExtType == SPEXTKEY::fSPExtentTypeOE ) || ( eExtType == SPEXTKEY::fSPExtentTypeAE ) );
ERR err;
DIB dib;
OnDebug( const BOOL fOwnExt = eExtType == SPEXTKEY::fSPExtentTypeOE );
Assert( fOwnExt ? pfucb->fOwnExt : pfucb->fAvailExt );
Assert( ( sppAvailPool == spp::AvailExtLegacyGeneralPool ) || !fOwnExt );
CSPExtentKeyBM spextkeyFind( eExtType, pgno, sppAvailPool );
dib.pos = posDown;
dib.pbm = spextkeyFind.Pbm( pfucb ) ;
dib.dirflag = fDIRFavourNext;
Call( ErrBTDown( pfucb, &dib, latchReadTouch ) );
if ( wrnNDFoundLess == err )
{
Assert( Pcsr( pfucb )->Cpage().Clines() - 1 ==
Pcsr( pfucb )->ILine() );
Call( ErrBTNext( pfucb, fDIRNull ) );
}
pspei->Set( pfucb );
ASSERT_VALID( pspei );
Call( pspei->ErrCheckCorrupted() );
if ( pspei->SppPool() != sppAvailPool )
{
Error( ErrERRCheck( JET_errRecordNotFound ) );
}
err = JET_errSuccess;
HandleError:
if ( err < JET_errSuccess )
{
pspei->Unset();
}
return err;
}
LOCAL ERR ErrSPIFindExtOE(
__inout FUCB * pfucbOE,
__in const PGNO pgnoFirst,
__out CSPExtentInfo * pcspoext
)
{
return ErrSPIFindExt( pfucbOE, pgnoFirst, spp::AvailExtLegacyGeneralPool, SPEXTKEY::fSPExtentTypeOE, pcspoext );
}
LOCAL ERR ErrSPIFindExtAE(
__inout FUCB * pfucbAE,
__in const PGNO pgnoFirst,
__in const SpacePool sppAvailPool,
__out CSPExtentInfo * pcspaext
)
{
Expected( ( sppAvailPool != spp::ShelvedPool ) || ( pfucbAE->u.pfcb->PgnoFDP() == pgnoSystemRoot ) );
return ErrSPIFindExt( pfucbAE, pgnoFirst, sppAvailPool, SPEXTKEY::fSPExtentTypeAE, pcspaext );
}
LOCAL INLINE ERR ErrSPIFindExtOE(
__inout PIB * ppib,
__in FCB * pfcb,
__in const PGNO pgnoFirst,
__out CSPExtentInfo * pcspoext )
{
ERR err = JET_errSuccess;
FUCB *pfucbOE;
CallR( ErrSPIOpenOwnExt( ppib, pfcb, &pfucbOE ) );
Assert( pfcb == pfucbOE->u.pfcb );
Call( ErrSPIFindExtOE( pfucbOE, pgnoFirst, pcspoext ) );
ASSERT_VALID( pcspoext );
HandleError:
BTClose( pfucbOE );
return err;
}
LOCAL INLINE ERR ErrSPIFindExtAE(
__inout PIB * ppib,
__in FCB * pfcb,
__in const PGNO pgnoFirst,
__in const SpacePool sppAvailPool,
__out CSPExtentInfo * pcspaext )
{
ERR err = JET_errSuccess;
FUCB *pfucbAE;
CallR( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbAE ) );
Assert( pfcb == pfucbAE->u.pfcb );
Call( ErrSPIFindExtAE( pfucbAE, pgnoFirst, sppAvailPool, pcspaext ) );
ASSERT_VALID( pcspaext );
HandleError:
BTClose( pfucbAE );
return err;
}
template< class T >
inline SpaceCategoryFlags& operator|=( SpaceCategoryFlags& spcatf, const T& t )
{
spcatf = SpaceCategoryFlags( spcatf | (SpaceCategoryFlags)t );
return spcatf;
}
BOOL FSPSpaceCatStrictlyLeaf( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfStrictlyLeaf ) != 0;
}
BOOL FSPSpaceCatStrictlyInternal( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfStrictlyInternal ) != 0;
}
BOOL FSPSpaceCatRoot( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfRoot ) != 0;
}
BOOL FSPSpaceCatSplitBuffer( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfSplitBuffer ) != 0;
}
BOOL FSPSpaceCatSmallSpace( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfSmallSpace ) != 0;
}
BOOL FSPSpaceCatSpaceOE( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfSpaceOE ) != 0;
}
BOOL FSPSpaceCatSpaceAE( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfSpaceAE ) != 0;
}
BOOL FSPSpaceCatAnySpaceTree( const SpaceCategoryFlags spcatf )
{
return FSPSpaceCatSpaceOE( spcatf ) || FSPSpaceCatSpaceAE( spcatf );
}
BOOL FSPSpaceCatAvailable( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfAvailable ) != 0;
}
BOOL FSPSpaceCatIndeterminate( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfIndeterminate ) != 0;
}
BOOL FSPSpaceCatInconsistent( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfInconsistent ) != 0;
}
BOOL FSPSpaceCatLeaked( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfLeaked ) != 0;
}
BOOL FSPSpaceCatNotOwned( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfNotOwned ) != 0;
}
BOOL FSPSpaceCatNotOwnedEof( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfNotOwnedEof ) != 0;
}
BOOL FSPSpaceCatUnknown( const SpaceCategoryFlags spcatf )
{
return ( spcatf & spcatfUnknown ) != 0;
}
BOOL FSPValidSpaceCategoryFlags( const SpaceCategoryFlags spcatf )
{
if ( spcatf == spcatfNone )
{
return fFalse;
}
if ( FSPSpaceCatUnknown( spcatf ) && ( spcatf != spcatfUnknown ) )
{
return fFalse;
}
if ( FSPSpaceCatIndeterminate( spcatf ) && ( spcatf != spcatfIndeterminate ) )
{
return fFalse;
}
if ( FSPSpaceCatInconsistent( spcatf ) && ( spcatf != spcatfInconsistent ) )
{
return fFalse;
}
if ( FSPSpaceCatLeaked( spcatf ) && ( spcatf != spcatfLeaked ) )
{
return fFalse;
}
if ( FSPSpaceCatNotOwned( spcatf ) && ( spcatf != spcatfNotOwned ) )
{
return fFalse;
}
if ( FSPSpaceCatNotOwnedEof( spcatf ) && ( spcatf != spcatfNotOwnedEof ) )
{
return fFalse;
}
if ( FSPSpaceCatAvailable( spcatf ) &&
( FSPSpaceCatStrictlyLeaf( spcatf ) || FSPSpaceCatStrictlyInternal( spcatf ) || FSPSpaceCatRoot( spcatf ) ) )
{
return fFalse;
}
if ( FSPSpaceCatSpaceOE( spcatf ) && FSPSpaceCatSpaceAE( spcatf ) )
{
return fFalse;
}
if ( FSPSpaceCatSplitBuffer( spcatf ) &&
( !FSPSpaceCatAnySpaceTree( spcatf ) || !FSPSpaceCatAvailable( spcatf ) ) )
{
return fFalse;
}
if ( FSPSpaceCatAvailable( spcatf ) && !FSPSpaceCatSplitBuffer( spcatf ) && FSPSpaceCatAnySpaceTree( spcatf ) )
{
return fFalse;
}
if ( FSPSpaceCatAvailable( spcatf ) &&
!FSPSpaceCatSplitBuffer( spcatf ) &&
!FSPSpaceCatAnySpaceTree( spcatf ) &&
!FSPSpaceCatSmallSpace( spcatf ) &&
( spcatf != spcatfAvailable ) )
{
return fFalse;
}
if ( FSPSpaceCatRoot( spcatf ) && ( FSPSpaceCatStrictlyLeaf( spcatf ) || FSPSpaceCatStrictlyInternal( spcatf ) ) )
{
return fFalse;
}
if ( FSPSpaceCatStrictlyLeaf( spcatf ) && ( FSPSpaceCatRoot( spcatf ) || FSPSpaceCatStrictlyInternal( spcatf ) ) )
{
return fFalse;
}
if ( FSPSpaceCatStrictlyInternal( spcatf ) && ( FSPSpaceCatRoot( spcatf ) || FSPSpaceCatStrictlyLeaf( spcatf ) ) )
{
return fFalse;
}
if ( FSPSpaceCatSmallSpace( spcatf ) && FSPSpaceCatAnySpaceTree( spcatf ) )
{
return fFalse;
}
return fTrue;
}
VOID SPFreeSpaceCatCtx( _Inout_ SpaceCatCtx** const ppSpCatCtx )
{
Assert( ppSpCatCtx != NULL );
SpaceCatCtx* const pSpCatCtx = *ppSpCatCtx;
if ( pSpCatCtx == NULL )
{
return;
}
if ( pSpCatCtx->pfucbSpace != pfucbNil )
{
BTUp( pSpCatCtx->pfucbSpace );
BTClose( pSpCatCtx->pfucbSpace );
pSpCatCtx->pfucbSpace = pfucbNil;
}
Assert( ( pSpCatCtx->pfucb != pfucbNil ) || ( pSpCatCtx->pfucbParent == pfucbNil ) );
CATFreeCursorsFromObjid( pSpCatCtx->pfucb, pSpCatCtx->pfucbParent );
pSpCatCtx->pfucbParent = pfucbNil;
pSpCatCtx->pfucb = pfucbNil;
if ( pSpCatCtx->pbm != NULL )
{
delete pSpCatCtx->pbm;
pSpCatCtx->pbm = NULL;
}
delete pSpCatCtx;
*ppSpCatCtx = NULL;
}
ERR ErrSPIGetObjidFromPage(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_Out_ OBJID* const pobjid )
{
CPAGE cpage;
ERR err = cpage.ErrGetReadPage( ppib, ifmp, pgno, bflfUninitPageOk );
if ( err < JET_errSuccess )
{
*pobjid = objidNil;
}
else
{
*pobjid = cpage.ObjidFDP();
}
Call( err );
cpage.ReleaseReadLatch();
HandleError:
return err;
}
ERR ErrSPIGetSpaceCategoryObject(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_In_ const OBJID objid,
_In_ const OBJID objidParent,
_In_ const SYSOBJ sysobj,
_Out_ SpaceCategoryFlags* const pspcatf,
_Out_ BOOL* const pfOwned,
_Out_ SpaceCatCtx** const ppSpCatCtx )
{
ERR err = JET_errSuccess;
BOOL fOwned = fFalse;
PGNO pgnoFDPParent = pgnoNull;
PGNO pgnoFDP = pgnoNull;
FUCB* pfucbParent = pfucbNil;
FUCB* pfucb = pfucbNil;
FUCB* pfucbSpace = pfucbNil;
FCB* pfcb = pfcbNil;
SpaceCategoryFlags spcatf = spcatfNone;
CPAGE cpage;
BOOL fPageLatched = fFalse;
KEYDATAFLAGS kdf;
SpaceCatCtx* pSpCatCtx = NULL;
BOOKMARK_COPY* pbm = NULL;
Assert( objid != objidNil );
Assert( objid != objidParent );
Assert( ( sysobj == sysobjNil ) || ( sysobj == sysobjTable ) || ( sysobj == sysobjIndex ) || ( sysobj == sysobjLongValue ) );
Assert( ( objidParent != objidNil ) != ( objid == objidSystemRoot ) );
Assert( ( sysobj != sysobjNil ) != ( objid == objidSystemRoot ) );
Assert( ( sysobj == sysobjTable ) == ( objidParent == objidSystemRoot ) );
Assert( pspcatf != NULL );
Assert( pfOwned != NULL );
Assert( ppSpCatCtx != NULL );
*pspcatf = spcatfUnknown;
*pfOwned = fFalse;
*ppSpCatCtx = NULL;
Alloc( pSpCatCtx = new SpaceCatCtx );
Alloc( pbm = new BOOKMARK_COPY );
Call( ErrCATGetCursorsFromObjid(
ppib,
ifmp,
objid,
objidParent,
sysobj,
&pgnoFDP,
&pgnoFDPParent,
&pfucb,
&pfucbParent ) );
pfcb = pfucb->u.pfcb;
#ifdef DEBUG
if ( pfucbParent != pfucbNil )
{
Assert( objid != objidSystemRoot );
FCB* const pfcbParent = pfucbParent->u.pfcb;
Assert( pfcbParent != pfcbNil );
Assert( pfcbParent->FInitialized() );
Assert( PgnoFDP( pfucbParent ) == pgnoFDPParent );
}
else
{
Assert( objid == objidSystemRoot );
}
#endif
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
if ( FSPIIsSmall( pfcb ) )
{
Expected( objid != objidSystemRoot );
const SPACE_HEADER* const psph = PsphSPIRootPage( pfucb );
Assert( psph->FSingleExtent() );
const PGNO pgnoFirst = PgnoFDP( pfucb );
const PGNO pgnoLast = pgnoFirst + psph->CpgPrimary() - 1;
if ( ( pgno < pgnoFirst ) || ( pgno > pgnoLast ) )
{
spcatf = spcatfUnknown;
goto HandleError;
}
fOwned = fTrue;
spcatf |= spcatfSmallSpace;
C_ASSERT( cpgSmallSpaceAvailMost <= ( 8 * sizeof( psph->RgbitAvail() ) ) );
if (
( pgno > pgnoFirst ) &&
(
( ( pgno - pgnoFirst ) > cpgSmallSpaceAvailMost ) ||
( psph->RgbitAvail() & ( (UINT)0x1 << ( pgno - pgnoFirst - 1 ) ) )
)
)
{
spcatf |= spcatfAvailable;
goto HandleError;
}
if ( pgno == pgnoFDP )
{
spcatf |= spcatfRoot;
}
}
else
{
CSPExtentInfo speiOE;
err = ErrSPIFindExtOE( ppib, pfcb, pgno, &speiOE );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
err = JET_errSuccess;
}
Call( err );
if ( !speiOE.FIsSet() || !speiOE.FContains( pgno ) )
{
if ( objid == objidSystemRoot )
{
if ( speiOE.FIsSet() && !speiOE.FContains( pgno ) )
{
spcatf = spcatfNotOwned;
}
else
{
Assert( !speiOE.FIsSet() );
QWORD cbSize = 0;
Call( g_rgfmp[ ifmp ].Pfapi()->ErrSize( &cbSize, IFileAPI::filesizeLogical ) );
const PGNO pgnoBeyondEOF = PgnoOfOffset( cbSize );
if ( pgno >= pgnoBeyondEOF )
{
Error( ErrERRCheck( JET_errFileIOBeyondEOF ) );
}
else
{
spcatf = spcatfNotOwnedEof;
}
}
goto HandleError;
}
else
{
Assert( spcatf == spcatfNone );
}
}
else
{
fOwned = fTrue;
}
for ( SpacePool sppAvailPool = spp::MinPool;
sppAvailPool < spp::MaxPool;
sppAvailPool++ )
{
if ( sppAvailPool == spp::ShelvedPool )
{
continue;
}
CSPExtentInfo speiAE;
err = ErrSPIFindExtAE( ppib, pfcb, pgno, sppAvailPool, &speiAE );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
err = JET_errSuccess;
}
Call( err );
if ( speiAE.FIsSet() && speiAE.FContains( pgno ) )
{
if ( fOwned )
{
spcatf |= spcatfAvailable;
}
else
{
AssertTrack( fFalse, "SpaceCatAvailNotOwned" );
spcatf = spcatfInconsistent;
}
goto HandleError;
}
}
if ( ( pgno == pgnoFDP ) || ( pgno == pfcb->PgnoOE() ) || ( pgno == pfcb->PgnoAE() ) )
{
spcatf |= spcatfRoot;
spcatf |= ( pgno == pfcb->PgnoOE() ) ? spcatfSpaceOE :
( ( pgno == pfcb->PgnoAE() ) ? spcatfSpaceAE : spcatfNone );
}
}
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
Assert( ( fOwned && !FSPSpaceCatAvailable( spcatf ) ) ||
( !fOwned && !FSPIIsSmall( pfcb ) && ( objid != objidSystemRoot ) && ( spcatf == spcatfNone ) ) );
Assert( !FSPSpaceCatSplitBuffer( spcatf ) );
if ( !FSPSpaceCatRoot( spcatf ) && !FSPSpaceCatSmallSpace( spcatf ) )
{
BOOL fSPBufAEContains = fFalse;
BOOL fSPBufOEContains = fFalse;
Call( ErrSPISPBufContains( ppib, pfcb, pgno, fFalse, &fSPBufAEContains ) );
if ( !fSPBufAEContains )
{
Call( ErrSPISPBufContains( ppib, pfcb, pgno, fTrue, &fSPBufOEContains ) );
}
if ( fSPBufAEContains || fSPBufOEContains )
{
Assert( !( fSPBufAEContains && fSPBufOEContains ) );
spcatf |= ( spcatfSplitBuffer | spcatfAvailable | ( fSPBufAEContains ? spcatfSpaceAE : spcatfSpaceOE ) );
goto HandleError;
}
}
Assert( !FSPSpaceCatStrictlyInternal( spcatf ) && !FSPSpaceCatStrictlyLeaf( spcatf ) );
err = cpage.ErrGetReadPage( ppib, ifmp, pgno, BFLatchFlags( bflfNoTouch | bflfUninitPageOk ) );
if ( err < JET_errSuccess )
{
if ( err == JET_errPageNotInitialized )
{
err = JET_errSuccess;
if ( FSPSpaceCatRoot( spcatf ) )
{
AssertTrack( false, "SpaceCatBlankRoot" );
spcatf = spcatfInconsistent;
}
else
{
spcatf = spcatfUnknown;
}
goto HandleError;
}
else
{
Error( err );
}
}
fPageLatched = fTrue;
Assert( cpage.FPageIsInitialized() );
if ( cpage.ObjidFDP() != objid )
{
spcatf = spcatfUnknown;
goto HandleError;
}
if ( FSPSpaceCatRoot( spcatf ) && !cpage.FRootPage() )
{
AssertTrack( false, "SpaceCatIncRootFlag" );
spcatf = spcatfInconsistent;
goto HandleError;
}
if ( FSPSpaceCatAnySpaceTree( spcatf ) && !cpage.FSpaceTree() )
{
AssertTrack( false, "SpaceCatIncSpaceFlag" );
spcatf = spcatfInconsistent;
goto HandleError;
}
if ( cpage.FPreInitPage() && ( cpage.FRootPage() || cpage.FLeafPage() ) )
{
AssertTrack( false, "SpaceCatIncPreInitFlag" );
spcatf = spcatfInconsistent;
goto HandleError;
}
if ( FSPSpaceCatRoot( spcatf ) )
{
goto HandleError;
}
if ( cpage.FEmptyPage() || cpage.FPreInitPage() || ( cpage.Clines() <= 0 ) )
{
spcatf = spcatfUnknown;
goto HandleError;
}
#ifdef DEBUG
const INT iline = ( ( cpage.Clines() - 1 ) * ( rand() % 5 ) ) / 4;
#else
const INT iline = 0;
#endif
Assert( ( iline >= 0 ) && ( iline < cpage.Clines() ) );
NDIGetKeydataflags( cpage, iline, &kdf );
const BOOL fLeafPage = cpage.FLeafPage();
const BOOL fSpacePage = cpage.FSpaceTree();
const BOOL fNonUniqueKeys = cpage.FNonUniqueKeys() && !fSpacePage;
if ( fLeafPage && fNonUniqueKeys )
{
if ( kdf.key.FNull() || kdf.data.FNull() )
{
AssertTrack( false, "SpaceCatIncKdfNonUnique" );
spcatf = spcatfInconsistent;
goto HandleError;
}
Call( pbm->ErrCopyKeyData( kdf.key, kdf.data ) );
}
else
{
if ( fLeafPage && kdf.key.FNull() )
{
AssertTrack( false, "SpaceCatIncKdfUniqueLeaf" );
spcatf = spcatfInconsistent;
goto HandleError;
}
else if ( !fLeafPage && kdf.data.FNull() )
{
AssertTrack( false, "SpaceCatIncKdfUniqueInternal" );
spcatf = spcatfInconsistent;
goto HandleError;
}
Call( pbm->ErrCopyKey( kdf.key ) );
}
cpage.ReleaseReadLatch();
fPageLatched = fFalse;
if ( !fSpacePage )
{
if ( !fNonUniqueKeys != !!FFUCBUnique( pfucb ) )
{
AssertTrack( false, "SpaceCatIncUniqueFdp" );
spcatf = spcatfInconsistent;
goto HandleError;
}
err = ErrBTContainsPage( pfucb, *pbm, pgno, fLeafPage );
if ( err >= JET_errSuccess )
{
spcatf |= ( fLeafPage ? spcatfStrictlyLeaf : spcatfStrictlyInternal );
goto HandleError;
}
else if ( err == JET_errRecordNotFound )
{
err = JET_errSuccess;
}
Call( err );
}
else
{
Assert( pfucbSpace == pfucbNil );
Call( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbSpace ) );
if ( !fNonUniqueKeys != !!FFUCBUnique( pfucbSpace ) )
{
AssertTrack( false, "SpaceCatIncUniqueAe" );
spcatf = spcatfInconsistent;
goto HandleError;
}
err = ErrBTContainsPage( pfucbSpace, *pbm, pgno, fLeafPage );
if ( err >= JET_errSuccess )
{
spcatf |= ( spcatfSpaceAE | ( fLeafPage ? spcatfStrictlyLeaf : spcatfStrictlyInternal ) );
goto HandleError;
}
else if ( err == JET_errRecordNotFound )
{
err = JET_errSuccess;
}
Call( err );
BTUp( pfucbSpace );
BTClose( pfucbSpace );
pfucbSpace = pfucbNil;
Assert( pfucbSpace == pfucbNil );
Call( ErrSPIOpenOwnExt( ppib, pfcb, &pfucbSpace ) );
if ( !fNonUniqueKeys != !!FFUCBUnique( pfucbSpace ) )
{
AssertTrack( false, "SpaceCatIncUniqueOe" );
spcatf = spcatfInconsistent;
goto HandleError;
}
err = ErrBTContainsPage( pfucbSpace, *pbm, pgno, fLeafPage );
if ( err >= JET_errSuccess )
{
spcatf |= ( spcatfSpaceOE | ( fLeafPage ? spcatfStrictlyLeaf : spcatfStrictlyInternal ) );
goto HandleError;
}
else if ( err == JET_errRecordNotFound )
{
err = JET_errSuccess;
}
Call( err );
BTUp( pfucbSpace );
BTClose( pfucbSpace );
pfucbSpace = pfucbNil;
}
spcatf = spcatfUnknown;
HandleError:
if ( fPageLatched )
{
cpage.ReleaseReadLatch();
fPageLatched = fFalse;
}
if ( pfucbSpace != pfucbNil )
{
BTUp( pfucbSpace );
}
if ( pfucb != pfucbNil )
{
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
}
if ( pfucbParent != pfucbNil )
{
BTUp( pfucbParent );
}
if ( ( err >= JET_errSuccess ) &&
FSPSpaceCatAnySpaceTree( spcatf ) &&
( pfucbSpace == pfucbNil ) )
{
if ( FSPSpaceCatSpaceOE( spcatf ) )
{
err = ErrSPIOpenOwnExt( ppib, pfcb, &pfucbSpace );
}
else
{
Assert( FSPSpaceCatSpaceAE( spcatf ) );
err = ErrSPIOpenAvailExt( ppib, pfcb, &pfucbSpace );
}
}
if ( ( err >= JET_errSuccess ) &&
!FSPSpaceCatAnySpaceTree( spcatf ) &&
( pfucbSpace != pfucbNil ))
{
BTClose( pfucbSpace );
pfucbSpace = NULL;
}
if ( ( err >= JET_errSuccess ) &&
!FSPSpaceCatStrictlyInternal( spcatf ) &&
!FSPSpaceCatStrictlyLeaf( spcatf ) &&
( pbm != NULL ) )
{
delete pbm;
pbm = NULL;
}
if ( pSpCatCtx != NULL )
{
pSpCatCtx->pfucbParent = pfucbParent;
pSpCatCtx->pfucb = pfucb;
pSpCatCtx->pfucbSpace = pfucbSpace;
pSpCatCtx->pbm = pbm;
}
else
{
Assert( pfucbParent == pfucbNil );
Assert( pfucb == pfucbNil );
Assert( pfucbSpace == pfucbNil );
Assert( pbm == NULL );
}
if ( err >= JET_errSuccess )
{
*pspcatf = spcatf;
*pfOwned = fOwned;
}
else
{
*pspcatf = spcatfUnknown;
*pfOwned = fFalse;
SPFreeSpaceCatCtx( &pSpCatCtx );
}
*ppSpCatCtx = pSpCatCtx;
return err;
}
ERR ErrSPIGetSpaceCategoryObjectAndChildren(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_In_ const OBJID objid,
_In_ const OBJID objidChildExclude,
_Out_ OBJID* const pobjid,
_Out_ SpaceCategoryFlags* const pspcatf,
_Out_ SpaceCatCtx** const ppSpCatCtx )
{
ERR err = JET_errSuccess;
FUCB* pfucbCatalog = pfucbNil;
OBJID objidChild = objidNil;
SYSOBJ sysobjChild = sysobjNil;
SpaceCatCtx* pSpCatCtxParent = NULL;
BOOL fParentOwned = fFalse;
Call( ErrSPIGetSpaceCategoryObject( ppib, ifmp, pgno, objid, objidSystemRoot, sysobjTable, pspcatf, &fParentOwned, ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( *pspcatf ) )
{
*pobjid = objid;
goto HandleError;
}
if ( !fParentOwned )
{
*pobjid = objidNil;
goto HandleError;
}
pSpCatCtxParent = *ppSpCatCtx;
*ppSpCatCtx = NULL;
for ( err = ErrCATGetNextNonRootObject( ppib, ifmp, objid, &pfucbCatalog, &objidChild, &sysobjChild );
( err >= JET_errSuccess ) && ( objidChild != objidNil );
err = ErrCATGetNextNonRootObject( ppib, ifmp, objid, &pfucbCatalog, &objidChild, &sysobjChild ) )
{
if ( objidChild == objidChildExclude )
{
continue;
}
BOOL fChildOwned = fFalse;
Call( ErrSPIGetSpaceCategoryObject( ppib, ifmp, pgno, objidChild, objid, sysobjChild, pspcatf, &fChildOwned, ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( *pspcatf ) )
{
*pobjid = objidChild;
goto HandleError;
}
if ( fChildOwned )
{
*pobjid = objidChild;
*pspcatf = spcatfLeaked;
goto HandleError;
}
SPFreeSpaceCatCtx( ppSpCatCtx );
}
Call( err );
*pobjid = objid;
*pspcatf = spcatfLeaked;
*ppSpCatCtx = pSpCatCtxParent;
pSpCatCtxParent = NULL;
HandleError:
if ( pfucbCatalog != pfucbNil )
{
CallS( ErrCATClose( ppib, pfucbCatalog ) );
pfucbCatalog = pfucbNil;
}
SPFreeSpaceCatCtx( &pSpCatCtxParent );
if ( err < JET_errSuccess )
{
SPFreeSpaceCatCtx( ppSpCatCtx );
}
return err;
}
ERR ErrSPIGetSpaceCategoryNoHint(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_In_ const OBJID objidExclude,
_Out_ OBJID* const pobjid,
_Out_ SpaceCategoryFlags* const pspcatf,
_Out_ SpaceCatCtx** const ppSpCatCtx )
{
ERR err = JET_errSuccess;
FUCB* pfucbCatalog = pfucbNil;
OBJID objid = objidNil;
for ( err = ErrCATGetNextRootObject( ppib, ifmp, &pfucbCatalog, &objid );
( err >= JET_errSuccess ) && ( objid != objidNil );
err = ErrCATGetNextRootObject( ppib, ifmp, &pfucbCatalog, &objid ) )
{
if ( objid == objidExclude )
{
continue;
}
Call( ErrSPIGetSpaceCategoryObjectAndChildren( ppib, ifmp, pgno, objid, objidNil, pobjid, pspcatf, ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( *pspcatf ) )
{
goto HandleError;
}
SPFreeSpaceCatCtx( ppSpCatCtx );
}
Call( err );
HandleError:
if ( pfucbCatalog != pfucbNil )
{
CallS( ErrCATClose( ppib, pfucbCatalog ) );
pfucbCatalog = pfucbNil;
}
if ( err < JET_errSuccess )
{
SPFreeSpaceCatCtx( ppSpCatCtx );
}
return err;
}
ERR ErrSPGetSpaceCategory(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_In_ const OBJID objidHint,
_In_ const BOOL fRunFullSpaceCat,
_Out_ OBJID* const pobjid,
_Out_ SpaceCategoryFlags* const pspcatf,
_Out_ SpaceCatCtx** const ppSpCatCtx )
{
Assert( pobjid != NULL );
Assert( pspcatf != NULL );
Assert( ppSpCatCtx != NULL );
ERR err = JET_errSuccess;
OBJID objid = objidNil;
SpaceCategoryFlags spcatf = spcatfUnknown;
OBJID objidHintParent = objidNil;
OBJID objidHintPage = objidNil;
OBJID objidHintPageParent = objidNil;
OBJID objidHintExclude = objidNil;
BOOL fSearchedRoot = fFalse;
BOOL fOwned = fFalse;
SpaceCatCtx* pSpCatCtxRoot = NULL;
if ( ( objidHint != objidNil ) &&
( objidHint != objidSystemRoot ) )
{
SYSOBJ sysobjHint = sysobjNil;
Call( ErrCATGetObjidMetadata( ppib, ifmp, objidHint, &objidHintParent, &sysobjHint ) );
if ( sysobjHint != sysobjNil )
{
Assert( objidHintParent != objidNil );
if ( objidHint != objidHintParent )
{
Call( ErrSPIGetSpaceCategoryObject( ppib,
ifmp,
pgno,
objidHint,
objidHintParent,
sysobjHint,
&spcatf,
&fOwned,
ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( spcatf ) )
{
objid = objidHint;
goto HandleError;
}
if ( fOwned )
{
objid = objidHint;
spcatf = spcatfLeaked;
goto HandleError;
}
SPFreeSpaceCatCtx( ppSpCatCtx );
}
}
else
{
objidHintParent = objidNil;
err = JET_errSuccess;
}
}
Assert( FSPSpaceCatUnknown( spcatf ) );
if ( ( objidHintParent != objidNil ) &&
( objidHintParent != objidSystemRoot ) )
{
Call( ErrSPIGetSpaceCategoryObjectAndChildren( ppib,
ifmp,
pgno,
objidHintParent,
( objidHint != objidHintParent ) ? objidHint : objidNil,
&objid,
&spcatf,
ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( spcatf ) )
{
goto HandleError;
}
SPFreeSpaceCatCtx( ppSpCatCtx );
objidHintExclude = objidHintParent;
}
Assert( FSPSpaceCatUnknown( spcatf ) );
if ( objidHint == objidSystemRoot )
{
Call( ErrSPIGetSpaceCategoryObject( ppib, ifmp, pgno, objidSystemRoot, objidNil, sysobjNil, &spcatf, &fOwned, ppSpCatCtx ) );
fSearchedRoot = fTrue;
if ( !FSPSpaceCatUnknown( spcatf ) )
{
Assert( !FSPSpaceCatRoot( spcatf ) ||
( pgno == pgnoSystemRoot ) ||
( FSPSpaceCatSpaceOE( spcatf ) && ( pgno == ( pgnoSystemRoot + 1 ) ) ) ||
( FSPSpaceCatSpaceAE( spcatf ) && ( pgno == ( pgnoSystemRoot + 2 ) ) ) );
objid = objidSystemRoot;
goto HandleError;
}
Assert( pSpCatCtxRoot == NULL );
pSpCatCtxRoot = *ppSpCatCtx;
*ppSpCatCtx = NULL;
}
Assert( FSPSpaceCatUnknown( spcatf ) );
err = ErrSPIGetObjidFromPage( ppib, ifmp, pgno, &objidHintPage );
if ( err >= JET_errSuccess )
{
if ( ( objidHintPage != objidNil ) &&
( objidHintPage != objidSystemRoot ) &&
( objidHintPage != objidHint ) &&
( objidHintPage != objidHintParent ) )
{
SYSOBJ sysobjHint = sysobjNil;
Call( ErrCATGetObjidMetadata( ppib, ifmp, objidHintPage, &objidHintPageParent, &sysobjHint ) );
if ( sysobjHint != sysobjNil )
{
Assert( objidHintPageParent != objidNil );
if ( objidHintPage != objidHintPageParent )
{
Call( ErrSPIGetSpaceCategoryObject( ppib,
ifmp,
pgno,
objidHintPage,
objidHintPageParent,
sysobjHint,
&spcatf,
&fOwned,
ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( spcatf ) )
{
objid = objidHintPage;
goto HandleError;
}
if ( fOwned )
{
objid = objidHintPage;
spcatf = spcatfLeaked;
goto HandleError;
}
SPFreeSpaceCatCtx( ppSpCatCtx );
}
}
else
{
objidHintPageParent = objidNil;
err = JET_errSuccess;
}
if ( ( objidHintPageParent != objidNil ) &&
( objidHintPageParent != objidSystemRoot ) &&
( objidHintPageParent != objidHint ) &&
( objidHintPageParent != objidHintParent ) )
{
Call( ErrSPIGetSpaceCategoryObjectAndChildren( ppib,
ifmp,
pgno,
objidHintPageParent,
( objidHintPage != objidHintPageParent ) ? objidHintPage : objidNil,
&objid,
&spcatf,
ppSpCatCtx ) );
if ( !FSPSpaceCatUnknown( spcatf ) )
{
goto HandleError;
}
SPFreeSpaceCatCtx( ppSpCatCtx );
objidHintExclude = objidHintPageParent;
}
}
}
else if ( err == JET_errPageNotInitialized )
{
objidHintPage = objidNil;
err = JET_errSuccess;
}
else
{
Assert( err < JET_errSuccess );
Error( err );
}
Assert( FSPSpaceCatUnknown( spcatf ) );
if ( !fSearchedRoot )
{
Call( ErrSPIGetSpaceCategoryObject( ppib, ifmp, pgno, objidSystemRoot, objidNil, sysobjNil, &spcatf, &fOwned, ppSpCatCtx ) );
fSearchedRoot = fTrue;
if ( !FSPSpaceCatUnknown( spcatf ) )
{
objid = objidSystemRoot;
goto HandleError;
}
Assert( pSpCatCtxRoot == NULL );
pSpCatCtxRoot = *ppSpCatCtx;
*ppSpCatCtx = NULL;
}
Assert( FSPSpaceCatUnknown( spcatf ) );
Assert( fSearchedRoot );
if ( fRunFullSpaceCat )
{
Call( ErrSPIGetSpaceCategoryNoHint( ppib, ifmp, pgno, objidHintExclude, &objid, &spcatf, ppSpCatCtx ) );
Assert( !FSPSpaceCatIndeterminate( spcatf ) );
if ( FSPSpaceCatUnknown( spcatf ) )
{
objid = objidSystemRoot;
spcatf = spcatfLeaked;
Assert( pSpCatCtxRoot != NULL );
*ppSpCatCtx = pSpCatCtxRoot;
pSpCatCtxRoot = NULL;
}
}
else
{
spcatf = spcatfIndeterminate;
}
Assert( FSPValidSpaceCategoryFlags( spcatf ) );
Assert( !FSPSpaceCatUnknown( spcatf ) );
HandleError:
SPFreeSpaceCatCtx( &pSpCatCtxRoot );
if ( err >= JET_errSuccess )
{
#ifdef DEBUG
Assert( !FSPSpaceCatIndeterminate( spcatf ) || !fRunFullSpaceCat );
Assert( ( objid != objidNil ) || FSPSpaceCatIndeterminate( spcatf ) );
Assert( pgno != pgnoNull );
if ( pgno <= ( pgnoSystemRoot + 2 ) )
{
Assert( objid == objidSystemRoot );
Assert( ( pgno != pgnoSystemRoot ) ||
( FSPSpaceCatRoot( spcatf ) && !FSPSpaceCatAnySpaceTree( spcatf ) ) );
Assert( ( pgno != ( pgnoSystemRoot + 1 ) ) ||
( FSPSpaceCatRoot( spcatf ) && FSPSpaceCatSpaceOE( spcatf ) ) );
Assert( ( pgno != ( pgnoSystemRoot + 2 ) ) ||
( FSPSpaceCatRoot( spcatf ) && FSPSpaceCatSpaceAE( spcatf ) ) );
}
if ( objid == objidSystemRoot )
{
Assert( FSPSpaceCatAnySpaceTree( spcatf ) ||
( !FSPSpaceCatStrictlyLeaf( spcatf ) && !FSPSpaceCatStrictlyInternal( spcatf ) ) );
}
if ( pgno == pgnoFDPMSO )
{
Assert( objid == objidFDPMSO );
Assert( FSPSpaceCatRoot( spcatf ) && !FSPSpaceCatAnySpaceTree( spcatf ) );
}
if ( pgno == pgnoFDPMSOShadow )
{
Assert( objid == objidFDPMSOShadow );
Assert( FSPSpaceCatRoot( spcatf ) && !FSPSpaceCatAnySpaceTree( spcatf ) );
}
if ( pgno == pgnoFDPMSO_NameIndex )
{
Assert( FSPSpaceCatRoot( spcatf ) && !FSPSpaceCatAnySpaceTree( spcatf ) );
}
if ( pgno == pgnoFDPMSO_RootObjectIndex )
{
Assert( FSPSpaceCatRoot( spcatf ) && !FSPSpaceCatAnySpaceTree( spcatf ) );
}
const SpaceCatCtx* const pSpCatCtx = *ppSpCatCtx;
if ( pSpCatCtx != NULL )
{
Assert( !FSPSpaceCatIndeterminate( spcatf ) );
Assert( pSpCatCtx->pfucb != pfucbNil );
Assert( pSpCatCtx->pfucb->u.pfcb->PgnoFDP() != pgnoNull );
if ( pSpCatCtx->pfucbParent != pfucbNil )
{
Assert( objid != objidSystemRoot );
Assert( pSpCatCtx->pfucbParent->u.pfcb != pSpCatCtx->pfucb->u.pfcb );
if ( pSpCatCtx->pfucbSpace != pfucbNil )
{
Assert( pSpCatCtx->pfucbParent->u.pfcb != pSpCatCtx->pfucbSpace->u.pfcb );
}
if ( pSpCatCtx->pfucbParent->u.pfcb->PgnoFDP() != pgnoSystemRoot )
{
Assert( ( pSpCatCtx->pfucb == pSpCatCtx->pfucbParent->pfucbCurIndex ) ||
( pSpCatCtx->pfucb == pSpCatCtx->pfucbParent->pfucbLV ) );
}
}
else
{
Assert( objid == objidSystemRoot );
Assert( pSpCatCtx->pfucb->u.pfcb->PgnoFDP() == pgnoSystemRoot );
}
if ( pSpCatCtx->pfucbSpace != pfucbNil )
{
Assert( FSPSpaceCatAnySpaceTree( spcatf ) );
Assert( ( FSPSpaceCatSpaceOE( spcatf ) && FFUCBOwnExt( pSpCatCtx->pfucbSpace ) ) ||
( FSPSpaceCatSpaceAE( spcatf ) && FFUCBAvailExt( pSpCatCtx->pfucbSpace ) ) );
Assert( pSpCatCtx->pfucbSpace != pSpCatCtx->pfucb );
Assert( pSpCatCtx->pfucbSpace->u.pfcb == pSpCatCtx->pfucb->u.pfcb );
if ( FSPSpaceCatRoot( spcatf ) )
{
Assert( ( FSPSpaceCatSpaceOE( spcatf ) && ( pSpCatCtx->pfucb->u.pfcb->PgnoOE() == pgno ) ) ||
( FSPSpaceCatSpaceAE( spcatf ) && ( pSpCatCtx->pfucb->u.pfcb->PgnoAE() == pgno ) ) );
}
}
else
{
Assert( !FSPSpaceCatAnySpaceTree( spcatf ) );
if ( FSPSpaceCatRoot( spcatf ) )
{
Assert( pSpCatCtx->pfucb->u.pfcb->PgnoFDP() == pgno );
}
}
Assert( !FSPSpaceCatStrictlyInternal( spcatf ) && !FSPSpaceCatStrictlyLeaf( spcatf ) || ( pSpCatCtx->pbm != NULL ) );
}
else
{
Assert( FSPSpaceCatIndeterminate( spcatf ) );
}
#endif
if ( ( !FSPValidSpaceCategoryFlags( spcatf ) ||
FSPSpaceCatUnknown( spcatf ) ||
FSPSpaceCatInconsistent( spcatf ) ) )
{
FireWall( OSFormat( "InconsistentCategoryFlags:0x%I32x", spcatf ) );
}
*pobjid = objid;
*pspcatf = spcatf;
err = JET_errSuccess;
}
else
{
SPFreeSpaceCatCtx( ppSpCatCtx );
*pobjid = objidNil;
*pspcatf = spcatfUnknown;
}
return err;
}
ERR ErrSPGetSpaceCategory(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_In_ const OBJID objidHint,
_In_ const BOOL fRunFullSpaceCat,
_Out_ OBJID* const pobjid,
_Out_ SpaceCategoryFlags* const pspcatf )
{
SpaceCatCtx* pSpCatCtx = NULL;
const ERR err = ErrSPGetSpaceCategory( ppib, ifmp, pgno, objidHint, fRunFullSpaceCat, pobjid, pspcatf, &pSpCatCtx );
SPFreeSpaceCatCtx( &pSpCatCtx );
return err;
}
ERR ErrSPGetSpaceCategoryRange(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgnoFirst,
_In_ const PGNO pgnoLast,
_In_ const BOOL fRunFullSpaceCat,
_In_ const JET_SPCATCALLBACK pfnCallback,
_In_opt_ VOID* const pvContext )
{
ERR err = JET_errSuccess;
BOOL fMSysObjidsReady = fFalse;
if ( ( pgnoFirst < 1 ) || ( pgnoLast > pgnoSysMax ) || ( pgnoFirst > pgnoLast ) || ( pfnCallback == NULL ) )
{
Error( ErrERRCheck( JET_errInvalidParameter ) );
}
Call( ErrCATCheckMSObjidsReady( ppib, ifmp, &fMSysObjidsReady ) );
if ( !fMSysObjidsReady )
{
Error( ErrERRCheck( JET_errObjectNotFound ) );
}
const CPG cpgPrereadMax = LFunctionalMax( 1, (CPG)( UlParam( JET_paramMaxCoalesceReadSize ) / g_cbPage ) );
PGNO pgnoPrereadWaypoint = pgnoFirst, pgnoPrereadNext = pgnoFirst;
OBJID objidHint = objidNil;
for ( PGNO pgnoCurrent = pgnoFirst; pgnoCurrent <= pgnoLast; pgnoCurrent++ )
{
if ( ( pgnoCurrent >= pgnoPrereadWaypoint ) && ( pgnoPrereadNext <= pgnoLast ) )
{
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortDbShrink );
const CPG cpgPrereadCurrent = LFunctionalMin( cpgPrereadMax, (CPG)( pgnoLast - pgnoPrereadNext + 1 ) );
Assert( cpgPrereadCurrent >= 1 );
BFPrereadPageRange( ifmp, pgnoPrereadNext, cpgPrereadCurrent, bfprfDefault, ppib->BfpriPriority( ifmp ), *tcScope );
pgnoPrereadNext += cpgPrereadCurrent;
pgnoPrereadWaypoint = pgnoPrereadNext - ( cpgPrereadCurrent / 2 );
}
OBJID objidCurrent = objidNil;
SpaceCategoryFlags spcatfCurrent = spcatfNone;
Call( ErrSPGetSpaceCategory(
ppib,
ifmp,
pgnoCurrent,
objidHint,
fRunFullSpaceCat,
&objidCurrent,
&spcatfCurrent ) );
objidHint = ( objidCurrent != objidNil ) ? objidCurrent : objidHint;
Assert( FSPValidSpaceCategoryFlags( spcatfCurrent ) );
Assert( !FSPSpaceCatUnknown( spcatfCurrent ) );
pfnCallback( pgnoCurrent, objidCurrent, spcatfCurrent, pvContext );
}
HandleError:
return err;
}
ERR ErrSPICheckExtentIsAllocatable( const IFMP ifmp, const PGNO pgnoFirst, const CPG cpg )
{
Assert( ifmp != ifmpNil );
Assert( pgnoFirst != pgnoNull );
Assert( cpg > 0 );
if ( g_rgfmp[ ifmp ].FBeyondPgnoShrinkTarget( pgnoFirst, cpg ) )
{
AssertTrack( fFalse, "ShrinkExtentOverlap" );
return ErrERRCheck( JET_errSPAvailExtCorrupted );
}
if ( ( pgnoFirst + cpg - 1 ) > g_rgfmp[ ifmp ].PgnoLast() )
{
AssertTrack( fFalse, "PageBeyondEofAlloc" );
return ErrERRCheck( JET_errSPAvailExtCorrupted );
}
return JET_errSuccess;
}
ERR ErrSPISmallGetExt(
FUCB *pfucbParent,
CPG *pcpgReq,
CPG cpgMin,
PGNO *ppgnoFirst )
{
FCB * const pfcb = pfucbParent->u.pfcb;
ERR err = errSPNoSpaceForYou;
AssertSPIPfucbOnRoot( pfucbParent );
Assert( pfcb->PgnoFDP() != pgnoSystemRoot );
if ( cpgMin <= cpgSmallSpaceAvailMost )
{
SPACE_HEADER sph;
UINT rgbitT;
PGNO pgnoAvail;
DATA data;
INT iT;
NDGetExternalHeader( pfucbParent, pfucbParent->pcsrRoot, noderfSpaceHeader );
Assert( pfucbParent->pcsrRoot->Latch() == latchRIW
|| pfucbParent->pcsrRoot->Latch() == latchWrite );
Assert( sizeof( SPACE_HEADER ) == pfucbParent->kdfCurr.data.Cb() );
UtilMemCpy( &sph, pfucbParent->kdfCurr.data.Pv(), sizeof(sph) );
const PGNO pgnoFDP = PgnoFDP( pfucbParent );
const CPG cpgSingleExtent = min( sph.CpgPrimary(), cpgSmallSpaceAvailMost+1 );
Assert( cpgSingleExtent > 0 );
Assert( cpgSingleExtent <= cpgSmallSpaceAvailMost+1 );
Assert( cpgMin > 0 );
Assert( cpgMin <= 32 );
for ( rgbitT = 1, iT = 1; iT < cpgMin; iT++ )
{
rgbitT = (rgbitT<<1) + 1;
}
for( pgnoAvail = pgnoFDP + 1;
pgnoAvail + cpgMin <= pgnoFDP + cpgSingleExtent;
pgnoAvail++, rgbitT <<= 1 )
{
Assert( rgbitT != 0 );
if ( ( rgbitT & sph.RgbitAvail() ) == rgbitT )
{
SPIUpgradeToWriteLatch( pfucbParent );
sph.SetRgbitAvail( sph.RgbitAvail() ^ rgbitT );
data.SetPv( &sph );
data.SetCb( sizeof(sph) );
Assert( errSPNoSpaceForYou == err );
CallR( ErrNDSetExternalHeader(
pfucbParent,
pfucbParent->pcsrRoot,
&data,
( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfSpaceHeader ) );
Assert( pgnoAvail != pgnoNull );
Assert( !g_rgfmp[ pfucbParent->ifmp ].FBeyondPgnoShrinkTarget( pgnoAvail, cpgMin ) );
Assert( ( pgnoAvail + cpgMin - 1 ) <= g_rgfmp[ pfucbParent->ifmp ].PgnoLast() );
*ppgnoFirst = pgnoAvail;
*pcpgReq = cpgMin;
err = JET_errSuccess;
goto HandleError;
}
}
}
HandleError:
return err;
}
ERR ErrSPIAEFindExt(
__inout FUCB * const pfucbAE,
__in const CPG cpgMin,
__in const SpacePool sppAvailPool,
__out CSPExtentInfo * pcspaei )
{
ERR err = JET_errSuccess;
DIB dib;
BOOL fFoundNextAvailSE = fFalse;
FCB* const pfcb = pfucbAE->u.pfcb;
Assert( FFUCBSpace( pfucbAE ) );
Assert( !FSPIIsSmall( pfcb ) );
const PGNO pgnoSeek = ( cpgMin >= cpageSEDefault ? pfcb->PgnoNextAvailSE() : pgnoNull );
const CSPExtentKeyBM spaeFindExt( SPEXTKEY::fSPExtentTypeAE, pgnoSeek, sppAvailPool );
dib.pos = posDown;
dib.pbm = spaeFindExt.Pbm( pfucbAE );
dib.dirflag = fDIRFavourNext;
if ( ( err = ErrBTDown( pfucbAE, &dib, latchReadTouch ) ) < 0 )
{
Assert( err != JET_errNoCurrentRecord );
if ( JET_errRecordNotFound == err )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "ErrSPGetExt could not down into available extent tree. [ifmp=0x%x]\n", pfucbAE->ifmp ) );
Call( err );
}
do
{
pcspaei->Set( pfucbAE );
if ( pcspaei->SppPool() != sppAvailPool )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
#ifdef DEPRECATED_ZERO_SIZED_AVAIL_EXTENT_CLEANUP
if ( 0 == pcspaei->CpgExtent() )
{
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Pcsr( pfucbAE )->Downgrade( latchReadTouch );
}
#endif
if ( pcspaei->CpgExtent() > 0 )
{
if ( g_rgfmp[ pfucbAE->ifmp ].FBeyondPgnoShrinkTarget( pcspaei->PgnoFirst(), pcspaei->CpgExtent() ) )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
if ( pcspaei->PgnoLast() > g_rgfmp[ pfucbAE->ifmp ].PgnoLast() )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
if ( !fFoundNextAvailSE
&& pcspaei->CpgExtent() >= cpageSEDefault )
{
pfcb->SetPgnoNextAvailSE( pcspaei->PgnoLast() - pcspaei->CpgExtent() + 1 );
fFoundNextAvailSE = fTrue;
}
if ( pcspaei->CpgExtent() >= cpgMin )
{
if ( !fFoundNextAvailSE
&& pfcb->PgnoNextAvailSE() <= pcspaei->PgnoLast() )
{
pfcb->SetPgnoNextAvailSE( pcspaei->PgnoLast() + 1 );
}
err = JET_errSuccess;
goto HandleError;
}
}
err = ErrBTNext( pfucbAE, fDIRNull );
}
while ( err >= 0 );
if ( err != JET_errNoCurrentRecord )
{
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "ErrSPGetExt could not scan available extent tree. [ifmp=0x%x]\n", pfucbAE->ifmp ) );
Assert( err < 0 );
goto HandleError;
}
if ( !fFoundNextAvailSE )
{
pfcb->SetPgnoNextAvailSE( pcspaei->PgnoLast() + 1 );
}
err = ErrERRCheck( errSPNoSpaceForYou );
HandleError:
if ( err >= JET_errSuccess )
{
Assert( pcspaei->FIsSet() );
const ERR errT = ErrSPICheckExtentIsAllocatable( pfucbAE->ifmp, pcspaei->PgnoFirst(), pcspaei->CpgExtent() );
if ( errT < JET_errSuccess )
{
err = errT;
}
}
Assert( err != JET_errRecordNotFound );
Assert( err != JET_errNoCurrentRecord );
if ( err < JET_errSuccess )
{
pcspaei->Unset();
BTUp( pfucbAE );
}
else
{
Assert( Pcsr( pfucbAE )->FLatched() );
}
return err;
}
LOCAL ERR ErrSPIGetExt(
FCB *pfcbDstTracingOnly,
FUCB *pfucbSrc,
CPG *pcpgReq,
CPG cpgMin,
PGNO *ppgnoFirst,
ULONG fSPFlags = 0,
UINT fPageFlags = 0,
OBJID *pobjidFDP = NULL,
const BOOL fMayViolateMaxSize = fFalse )
{
ERR err;
PIB * const ppib = pfucbSrc->ppib;
FCB * const pfcb = pfucbSrc->u.pfcb;
FUCB *pfucbAE = pfucbNil;
const BOOL fSelfReserving = ( fSPFlags & fSPSelfReserveExtent ) != 0;
CSPExtentInfo cspaei;
#ifdef DEBUG
Assert( *pcpgReq > 0 || ( (fSPFlags & fSPNewFDP) && *pcpgReq == 0 ) );
Assert( *pcpgReq >= cpgMin );
Assert( !FFUCBSpace( pfucbSrc ) );
AssertSPIPfucbOnRoot( pfucbSrc );
#endif
#ifdef SPACECHECK
Assert( !( ErrSPIValidFDP( ppib, pfucbParent->ifmp, PgnoFDP( pfucbParent ) ) < 0 ) );
#endif
if ( fSPFlags & fSPNewFDP )
{
Assert( !fSelfReserving );
const CPG cpgFDPMin = ( fSPFlags & fSPMultipleExtent ?
cpgMultipleExtentMin :
cpgSingleExtentMin );
cpgMin = max( cpgMin, cpgFDPMin );
*pcpgReq = max( *pcpgReq, cpgMin );
Assert( NULL != pobjidFDP );
}
Assert( cpgMin > 0 );
if ( !pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucbSrc, fTrue );
}
if ( FSPIIsSmall( pfcb ) )
{
Expected( !fSelfReserving );
Assert( !fMayViolateMaxSize );
err = ErrSPISmallGetExt( pfucbSrc, pcpgReq, cpgMin, ppgnoFirst );
if ( JET_errSuccess <= err )
{
Expected( err == JET_errSuccess );
goto NewFDP;
}
if( errSPNoSpaceForYou == err )
{
CallR( ErrSPIConvertToMultipleExtent( pfucbSrc, *pcpgReq, cpgMin ) );
}
Assert( FSPExpectedError( err ) );
Call( err );
}
CallR( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbAE ) );
Assert( pfcb == pfucbAE->u.pfcb );
if ( pfcb->FUtilizeParentSpace() ||
fSelfReserving ||
FCATBaseSystemFDP( pfcb->PgnoFDP() ) )
{
const CPG cpgMinT = fSelfReserving ? ( cpgMin + 1 ) : cpgMin;
err = ErrSPIAEFindExt( pfucbAE, cpgMinT, spp::AvailExtLegacyGeneralPool, &cspaei );
Assert( err != JET_errRecordNotFound );
Assert( err != JET_errNoCurrentRecord );
if ( err >= JET_errSuccess )
{
Assert( cspaei.CpgExtent() >= cpgMinT );
const CPG cpgMax = fSelfReserving ? ( cspaei.CpgExtent() - 1 ) : cspaei.CpgExtent();
*pcpgReq = min( cpgMax, *pcpgReq );
}
else if ( err != errSPNoSpaceForYou )
{
Call( err );
}
}
else
{
err = ErrERRCheck( errSPNoSpaceForYou );
}
if ( err == errSPNoSpaceForYou )
{
BTUp( pfucbAE );
if ( fSelfReserving )
{
Error( err );
}
if ( !FSPIParentIsFs( pfucbSrc ) )
{
Call( ErrSPIGetSe(
pfucbSrc,
pfucbAE,
*pcpgReq,
cpgMin,
fSPFlags & ( fSPSplitting | fSPExactExtent ),
spp::AvailExtLegacyGeneralPool,
fMayViolateMaxSize ) );
}
else
{
Call( ErrSPIGetFsSe(
pfucbSrc,
pfucbAE,
*pcpgReq,
cpgMin,
fSPFlags & ( fSPSplitting | fSPExactExtent ),
fFalse,
fTrue,
fMayViolateMaxSize ) );
}
Assert( Pcsr( pfucbAE )->FLatched() );
cspaei.Set( pfucbAE );
Assert( cspaei.CpgExtent() > 0 );
Assert( cspaei.CpgExtent() >= cpgMin );
}
err = cspaei.ErrCheckCorrupted();
if ( err < JET_errSuccess )
{
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"8aed90f2-6b6f-4bc4-902e-5ef1f328ebc3" );
}
Call( err );
Assert( Pcsr( pfucbAE )->FLatched() );
*ppgnoFirst = cspaei.PgnoFirst();
const CPG cpgDb = (CPG)g_rgfmp[pfucbAE->ifmp].PgnoLast();
if ( pfcb->PgnoFDP() == pgnoSystemRoot )
{
OSTraceFMP( pfucbSrc->ifmp, JET_tracetagSpaceInternal,
OSFormat( "found root space for alloc: %lu at %lu ... %d, %d\n",
cspaei.CpgExtent(), cspaei.PgnoFirst(),
(LONG)UlParam( PinstFromPpib( ppib ), JET_paramPageFragment ), cpgDb ) );
}
Assert( *pcpgReq >= cpgMin );
Assert( cspaei.CpgExtent() >= cpgMin );
Assert( !fSelfReserving || ( cspaei.CpgExtent() > *pcpgReq ) );
if ( FSPIAllocateAllAvail( &cspaei, *pcpgReq, (LONG)UlParam( PinstFromPpib( ppib ), JET_paramPageFragment ), pfcb->PgnoFDP(), cpgDb, fSPFlags )
&& !fSelfReserving )
{
*pcpgReq = cspaei.CpgExtent();
SPCheckPgnoAllocTrap( *ppgnoFirst, *pcpgReq );
Assert( cspaei.CpgExtent() > 0 );
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
}
else
{
Assert( cspaei.CpgExtent() > *pcpgReq );
SPCheckPgnoAllocTrap( *ppgnoFirst, *pcpgReq );
CSPExtentNodeKDF spAdjustedSize( SPEXTKEY::fSPExtentTypeAE, cspaei.PgnoLast(), cspaei.CpgExtent(), spp::AvailExtLegacyGeneralPool );
OnDebug( const PGNO pgnoLastBefore = cspaei.PgnoLast() );
Call( spAdjustedSize.ErrConsumeSpace( *ppgnoFirst, *pcpgReq ) );
Assert( spAdjustedSize.CpgExtent() > 0 );
Assert( pgnoLastBefore == cspaei.PgnoLast() );
Call( ErrBTReplace(
pfucbAE,
spAdjustedSize.GetData( ),
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
CallS( err );
err = JET_errSuccess;
}
BTUp( pfucbAE );
if ( ( pgnoSystemRoot == pfucbAE->u.pfcb->PgnoFDP() )
&& g_rgfmp[pfucbAE->u.pfcb->Ifmp()].FCacheAvail() )
{
g_rgfmp[pfucbAE->u.pfcb->Ifmp()].AdjustCpgAvail( -(*pcpgReq) );
}
NewFDP:
if ( fSPFlags & fSPNewFDP )
{
Assert( PgnoFDP( pfucbSrc ) != *ppgnoFirst );
if ( fSPFlags & fSPMultipleExtent )
{
Assert( *pcpgReq >= cpgMultipleExtentMin );
}
else
{
Assert( *pcpgReq >= cpgSingleExtentMin );
}
Assert( pgnoSystemRoot != *ppgnoFirst );
VEREXT verext;
verext.pgnoFDP = PgnoFDP( pfucbSrc );
verext.pgnoChildFDP = *ppgnoFirst;
verext.pgnoFirst = *ppgnoFirst;
verext.cpgSize = *pcpgReq;
if ( !( fSPFlags & fSPUnversionedExtent ) )
{
VER *pver = PverFromIfmp( pfucbSrc->ifmp );
Call( pver->ErrVERFlag( pfucbSrc, operAllocExt, &verext, sizeof(verext) ) );
}
Assert( PgnoFDP( pfucbSrc ) != pgnoNull );
Assert( *ppgnoFirst != pgnoSystemRoot );
Call( ErrSPCreate(
ppib,
pfucbSrc->ifmp,
PgnoFDP( pfucbSrc ),
*ppgnoFirst,
*pcpgReq,
fSPFlags,
fPageFlags,
pobjidFDP ) );
Assert( *pobjidFDP > objidSystemRoot );
if ( fSPFlags & fSPMultipleExtent )
{
(*pcpgReq) -= cpgMultipleExtentMin;
}
else
{
(*pcpgReq) -= cpgSingleExtentMin;
}
#ifdef DEBUG
if ( 0 == ppib->Level() )
{
FMP *pfmp = &g_rgfmp[pfucbSrc->ifmp];
Assert( fSPFlags & fSPUnversionedExtent );
Assert( pfmp->FIsTempDB() || pfmp->FCreatingDB() );
}
#endif
}
err = JET_errSuccess;
CPG cpgExt = *pcpgReq + ( (fSPFlags & fSPNewFDP) ?
( fSPFlags & fSPMultipleExtent ? cpgMultipleExtentMin : cpgSingleExtentMin ):
0
);
const PGNO pgnoParentFDP = PgnoFDP( pfucbSrc );
const PGNO pgnoFDP = pfcbDstTracingOnly->PgnoFDP();
ETSpaceAllocExt( pfucbSrc->ifmp, pgnoFDP, *ppgnoFirst, cpgExt, pfcbDstTracingOnly->ObjidFDP(), pfcbDstTracingOnly->TCE() );
OSTraceFMP( pfucbSrc->ifmp, JET_tracetagSpaceManagement,
OSFormat( "ErrSPIGetExt: %hs from %d.%lu for %lu at %lu for %lu pages (0x%x)\n",
fSPFlags & fSPNewFDP ? "NewExtFDP" : "AddlExt",
pfucbSrc->ifmp,
pgnoParentFDP,
pgnoFDP,
*ppgnoFirst,
cpgExt,
fSPFlags ) );
Assert( cpgExt == ( (fSPFlags & fSPNewFDP) ?
*pcpgReq + ( (fSPFlags & fSPMultipleExtent) ? cpgMultipleExtentMin : cpgSingleExtentMin ) : *pcpgReq ) );
if ( pgnoParentFDP == pgnoSystemRoot )
{
TLS* const ptls = Ptls();
ptls->threadstats.cPageTableAllocated += cpgExt;
}
HandleError:
if ( pfucbAE != pfucbNil )
{
BTClose( pfucbAE );
}
return err;
}
ERR ErrSPGetExt(
FUCB *pfucb,
PGNO pgnoParentFDP,
CPG *pcpgReq,
CPG cpgMin,
PGNO *ppgnoFirst,
ULONG fSPFlags,
UINT fPageFlags,
OBJID *pobjidFDP )
{
ERR err;
FUCB *pfucbParent = pfucbNil;
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortSpace );
Assert( !g_rgfmp[ pfucb->ifmp ].FReadOnlyAttach() );
Assert( !Pcsr( pfucb )->FLatched() );
Assert( 0 == ( fSPFlags & ~fMaskSPGetExt ) );
CallR( ErrBTIOpenAndGotoRoot( pfucb->ppib, pgnoParentFDP, pfucb->ifmp, &pfucbParent ) );
err = ErrSPIGetExt( pfucb->u.pfcb, pfucbParent, pcpgReq, cpgMin, ppgnoFirst, fSPFlags, fPageFlags, pobjidFDP );
Assert( Pcsr( pfucbParent ) == pfucbParent->pcsrRoot );
Assert( pfucbParent->pcsrRoot->Latch() == latchRIW
|| pfucbParent->pcsrRoot->Latch() == latchWrite );
pfucbParent->pcsrRoot->ReleasePage();
pfucbParent->pcsrRoot = pcsrNil;
Assert( pfucbParent != pfucbNil );
BTClose( pfucbParent );
return err;
}
ERR ErrSPISPGetPage(
__inout FUCB * pfucb,
__out PGNO * ppgnoAlloc )
{
ERR err = JET_errSuccess;
const BOOL fAvailExt = FFUCBAvailExt( pfucb );
Assert( FFUCBSpace( pfucb ) );
Assert( ppgnoAlloc );
Assert( pgnoNull == *ppgnoAlloc );
AssertSPIPfucbOnSpaceTreeRoot( pfucb, pfucb->pcsrRoot );
if ( NULL == pfucb->u.pfcb->Psplitbuf( fAvailExt ) )
{
CSR *pcsrRoot = pfucb->pcsrRoot;
SPLIT_BUFFER spbuf;
DATA data;
UtilMemCpy( &spbuf, PspbufSPISpaceTreeRootPage( pfucb, pcsrRoot ), sizeof(SPLIT_BUFFER) );
CallR( spbuf.ErrGetPage( pfucb->ifmp, ppgnoAlloc, fAvailExt ) );
Assert( latchRIW == pcsrRoot->Latch() );
pcsrRoot->UpgradeFromRIWLatch();
data.SetPv( &spbuf );
data.SetCb( sizeof(spbuf) );
err = ErrNDSetExternalHeader(
pfucb,
pcsrRoot,
&data,
( pfucb->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfWhole );
pcsrRoot->Downgrade( latchRIW );
}
else
{
SPITraceSplitBufferMsg( pfucb, "Retrieved page from" );
err = pfucb->u.pfcb->Psplitbuf( fAvailExt )->ErrGetPage( pfucb->ifmp, ppgnoAlloc, fAvailExt );
}
Assert( ( err < JET_errSuccess ) || !g_rgfmp[ pfucb->ifmp ].FBeyondPgnoShrinkTarget( *ppgnoAlloc, 1 ) );
Assert( ( err < JET_errSuccess ) || ( *ppgnoAlloc <= g_rgfmp[ pfucb->ifmp ].PgnoLast() ) );
return err;
}
ERR ErrSPISmallGetPage(
__inout FUCB * pfucb,
__in PGNO pgnoLast,
__out PGNO * ppgnoAlloc )
{
ERR err = JET_errSuccess;
SPACE_HEADER sph;
UINT rgbitT;
PGNO pgnoAvail;
DATA data;
const FCB * const pfcb = pfucb->u.pfcb;
Assert( NULL != ppgnoAlloc );
Assert( pgnoNull == *ppgnoAlloc );
Assert( pfcb->FSpaceInitialized() );
Assert( FSPIIsSmall( pfcb ) );
AssertSPIPfucbOnRoot( pfucb );
NDGetExternalHeader( pfucb, pfucb->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
UtilMemCpy( &sph, pfucb->kdfCurr.data.Pv(), sizeof(sph) );
const PGNO pgnoFDP = PgnoFDP( pfucb );
const CPG cpgSingleExtent = min( sph.CpgPrimary(), cpgSmallSpaceAvailMost+1 );
Assert( cpgSingleExtent > 0 );
Assert( cpgSingleExtent <= cpgSmallSpaceAvailMost+1 );
for( pgnoAvail = pgnoFDP + 1, rgbitT = 1;
pgnoAvail <= pgnoFDP + cpgSingleExtent - 1;
pgnoAvail++, rgbitT <<= 1 )
{
Assert( rgbitT != 0 );
if ( rgbitT & sph.RgbitAvail() )
{
Assert( ( rgbitT & sph.RgbitAvail() ) == rgbitT );
SPIUpgradeToWriteLatch( pfucb );
sph.SetRgbitAvail( sph.RgbitAvail() ^ rgbitT );
data.SetPv( &sph );
data.SetCb( sizeof(sph) );
CallR( ErrNDSetExternalHeader(
pfucb,
pfucb->pcsrRoot,
&data,
( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfSpaceHeader ) );
Assert( !g_rgfmp[ pfucb->ifmp ].FBeyondPgnoShrinkTarget( pgnoAvail, 1 ) );
Assert( pgnoAvail <= g_rgfmp[ pfucb->ifmp ].PgnoLast() );
*ppgnoAlloc = pgnoAvail;
SPCheckPgnoAllocTrap( *ppgnoAlloc );
ETSpaceAllocPage( pfucb->ifmp, pgnoFDP, *ppgnoAlloc, pfucb->u.pfcb->ObjidFDP(), TceFromFUCB( pfucb ) );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpace,
OSFormat( "get page 1 at %lu from %d.%lu\n", *ppgnoAlloc, pfucb->ifmp, PgnoFDP( pfucb ) ) );
return JET_errSuccess;
}
}
return ErrERRCheck( errSPNoSpaceForYou );
}
enum SPFindFlags {
fSPFindContinuousPage = 0x1,
fSPFindAnyGreaterPage = 0x2
};
ERR ErrSPIAEFindPage(
__inout FUCB * const pfucbAE,
__in const SPFindFlags fSPFindFlags,
__in const SpacePool sppAvailPool,
__in const PGNO pgnoLast,
__out CSPExtentInfo * pspaeiAlloc,
__out CPG * pcpgFindInsertionRegionMarker
)
{
ERR err = JET_errSuccess;
FCB * const pfcb = pfucbAE->u.pfcb;
DIB dib;
Assert( pfucbAE );
Assert( pspaeiAlloc );
Assert( FFUCBSpace( pfucbAE ) );
Assert( !FSPIIsSmall( pfcb ) );
pspaeiAlloc->Unset();
if ( pcpgFindInsertionRegionMarker )
{
*pcpgFindInsertionRegionMarker = 0;
}
CSPExtentKeyBM spaeFindPage( SPEXTKEY::fSPExtentTypeAE, pgnoLast, sppAvailPool );
dib.pos = posDown;
dib.pbm = spaeFindPage.Pbm( pfucbAE );
spaeFindPage.SPExtentMakeKeyBM( SPEXTKEY::fSPExtentTypeAE, pgnoLast, sppAvailPool );
dib.dirflag = fDIRNull;
err = ErrBTDown( pfucbAE, &dib, latchReadTouch );
switch ( err )
{
default:
Assert( err < JET_errSuccess );
Assert( err != JET_errNoCurrentRecord );
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "ErrSPGetPage could not go down into available extent tree. [ifmp=0x%x]\n", pfucbAE->ifmp ) );
Call( err );
break;
case JET_errRecordNotFound:
Error( ErrERRCheck( errSPNoSpaceForYou ) );
break;
case JET_errSuccess:
pspaeiAlloc->Set( pfucbAE );
if ( !( fSPFindContinuousPage & fSPFindFlags ) ||
( spp::ContinuousPool != sppAvailPool ) ||
( !pspaeiAlloc->FEmptyExtent() ) ||
( pspaeiAlloc->SppPool() != sppAvailPool ) )
{
AssertSz( fFalse, "AvailExt corrupted." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"bc14a209-3a29-4f60-957b-3e847f0eefd0" );
Call( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
Assert( sppAvailPool == spp::ContinuousPool );
Assert( fSPFindContinuousPage & fSPFindFlags );
{
CSPExtentInfo spoePreviousExtSize;
Call( ErrSPIFindExtOE( pfucbAE->ppib, pfcb, pgnoLast, &spoePreviousExtSize ) );
if ( !spoePreviousExtSize.FContains( pgnoLast ) )
{
AssertSz( fFalse, "OwnExt corrupted." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"bfc12437-d215-4768-a6e9-3e534da76285" );
Call( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
if ( NULL == pcpgFindInsertionRegionMarker )
{
spoePreviousExtSize.Unset();
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
Assert( pcpgFindInsertionRegionMarker );
*pcpgFindInsertionRegionMarker = spoePreviousExtSize.CpgExtent();
spoePreviousExtSize.Unset();
pspaeiAlloc->Unset();
err = JET_errSuccess;
goto HandleError;
}
break;
case wrnNDFoundLess:
pspaeiAlloc->Set( pfucbAE );
if ( pgnoNull != pgnoLast &&
pspaeiAlloc->SppPool() == sppAvailPool &&
( fSPFindFlags & fSPFindAnyGreaterPage ) )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
case wrnNDFoundGreater:
pspaeiAlloc->Set( pfucbAE );
if ( pspaeiAlloc->SppPool() != sppAvailPool )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
if ( pspaeiAlloc->FEmptyExtent() )
{
Assert( fSPFindContinuousPage & fSPFindFlags );
Assert( spp::ContinuousPool == pspaeiAlloc->SppPool() );
#ifdef DEPRECATED_ZERO_SIZED_AVAIL_EXTENT_CLEANUP
if ( pspaeiAlloc->Pool() != spp::ContinuousPool &&
0 == pspaeiAlloc->CpgExtent() )
{
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
BTUp( pfucbAE );
goto FindPage;
}
#endif
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
if ( ( fSPFindContinuousPage & fSPFindFlags ) &&
( pspaeiAlloc->PgnoFirst() != ( pgnoLast + 1 ) ) )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
if ( g_rgfmp[ pfucbAE->ifmp ].FBeyondPgnoShrinkTarget( pspaeiAlloc->PgnoFirst(), pspaeiAlloc->CpgExtent() ) )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
if ( pspaeiAlloc->PgnoLast() > g_rgfmp[ pfucbAE->ifmp ].PgnoLast() )
{
Error( ErrERRCheck( errSPNoSpaceForYou ) );
}
break;
}
err = JET_errSuccess;
HandleError:
if ( ( err >= JET_errSuccess ) && pspaeiAlloc->FIsSet() )
{
const ERR errT = ErrSPICheckExtentIsAllocatable( pfucbAE->ifmp, pspaeiAlloc->PgnoFirst(), pspaeiAlloc->CpgExtent() );
if ( errT < JET_errSuccess )
{
err = errT;
}
}
if ( err < JET_errSuccess )
{
pspaeiAlloc->Unset();
BTUp( pfucbAE );
Assert( !Pcsr( pfucbAE )->FLatched() );
}
else
{
Assert( Pcsr( pfucbAE )->FLatched() );
if ( NULL == pcpgFindInsertionRegionMarker || 0 == *pcpgFindInsertionRegionMarker )
{
Assert( pspaeiAlloc->SppPool() == sppAvailPool );
Assert( pspaeiAlloc->PgnoLast() && pspaeiAlloc->PgnoLast() != pgnoBadNews );
Assert( !pspaeiAlloc->FEmptyExtent() );
}
else
{
Assert( *pcpgFindInsertionRegionMarker );
}
}
return err;
}
ERR ErrSPIAEGetExtentAndPage(
__inout FUCB * const pfucb,
__inout FUCB * const pfucbAE,
__in const SpacePool sppAvailPool,
__in const CPG cpgRequest,
__in const ULONG fSPFlags,
__out CSPExtentInfo * pspaeiAlloc
)
{
ERR err = JET_errSuccess;
Assert( cpgRequest );
Assert( fSPFlags );
Assert( !Pcsr( pfucbAE )->FLatched() );
BTUp( pfucbAE );
Assert( !FSPIParentIsFs( pfucb ) );
if ( !FSPIParentIsFs( pfucb ) )
{
Call( ErrSPIGetSe( pfucb, pfucbAE, cpgRequest, cpgRequest, fSPFlags, sppAvailPool ) );
}
else
{
Call( ErrSPIGetFsSe( pfucb, pfucbAE, cpgRequest, cpgRequest, fSPFlags ) );
}
Assert( Pcsr( pfucbAE )->FLatched() );
pspaeiAlloc->Set( pfucbAE );
Assert( pspaeiAlloc->SppPool() == sppAvailPool );
HandleError:
return err;
}
ERR ErrSPIAEGetContinuousPage(
__inout FUCB * const pfucb,
__inout FUCB * const pfucbAE,
__in const PGNO pgnoLast,
__in const CPG cpgReserve,
__in const BOOL fHardReserve,
__out CSPExtentInfo * pspaeiAlloc
)
{
ERR err = JET_errSuccess;
FCB * const pfcb = pfucbAE->u.pfcb;
CPG cpgEscalatingRequest = 0;
Assert( pfucb );
Assert( pfucbAE );
Assert( pspaeiAlloc );
err = ErrSPIAEFindPage( pfucbAE, fSPFindContinuousPage, spp::ContinuousPool, pgnoLast, pspaeiAlloc, &cpgEscalatingRequest );
if ( cpgEscalatingRequest )
{
CallS( err );
Assert( Pcsr( pfucbAE )->FLatched() );
cpgEscalatingRequest = CpgSPIGetNextAlloc( pfcb->Pfcbspacehints(), cpgEscalatingRequest );
err = ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) );
BTUp( pfucbAE );
Assert( !Pcsr( pfucbAE )->FLatched() );
Call( err );
err = ErrERRCheck( errSPNoSpaceForYou );
}
else
{
cpgEscalatingRequest = 1;
}
if ( fHardReserve &&
err >= JET_errSuccess &&
pspaeiAlloc->CpgExtent() < cpgReserve )
{
pspaeiAlloc->Unset();
BTUp( pfucbAE );
Assert( !Pcsr( pfucbAE )->FLatched() );
err = ErrERRCheck( errSPNoSpaceForYou );
}
if ( errSPNoSpaceForYou == err )
{
if ( cpgEscalatingRequest == 1 )
{
if ( cpgReserve )
{
cpgEscalatingRequest += cpgReserve;
}
else
{
cpgEscalatingRequest = CpgSPIGetNextAlloc( pfcb->Pfcbspacehints(), cpgEscalatingRequest );
}
}
if ( fHardReserve &&
cpgReserve != 0 &&
cpgReserve != cpgEscalatingRequest )
{
const CPG cpgFullReserveRequest = ( cpgReserve + 1 );
if ( ( cpgEscalatingRequest % cpgFullReserveRequest ) != 0 )
{
cpgEscalatingRequest = cpgFullReserveRequest;
}
}
Call( ErrSPIAEGetExtentAndPage( pfucb, pfucbAE,
spp::ContinuousPool,
cpgEscalatingRequest,
fSPSplitting,
pspaeiAlloc ) );
}
CallS( err );
Call( err );
Assert( Pcsr( pfucbAE )->FLatched() );
Assert( pspaeiAlloc->SppPool() == spp::ContinuousPool );
Assert( pspaeiAlloc->PgnoFirst() && pspaeiAlloc->PgnoFirst() != pgnoBadNews );
Assert( !pspaeiAlloc->FEmptyExtent() );
HandleError:
Assert( JET_errSuccess == err || !Pcsr( pfucbAE )->FLatched() );
Assert( err < JET_errSuccess || Pcsr( pfucbAE )->FLatched() );
return err;
}
ERR ErrSPIAEGetAnyPage(
__inout FUCB * const pfucb,
__inout FUCB * const pfucbAE,
__in const PGNO pgnoLastHint,
__in const BOOL fSPAllocFlags,
__out CSPExtentInfo * pspaeiAlloc
)
{
ERR err = JET_errSuccess;
Assert( pfucb );
Assert( pfucbAE );
Assert( pspaeiAlloc );
err = ErrSPIAEFindPage( pfucbAE, fSPFindContinuousPage, spp::ContinuousPool, pgnoLastHint, pspaeiAlloc, NULL );
if ( errSPNoSpaceForYou == err )
{
err = ErrSPIAEFindPage( pfucbAE, fSPFindAnyGreaterPage, spp::AvailExtLegacyGeneralPool, pgnoLastHint, pspaeiAlloc, NULL );
if ( errSPNoSpaceForYou == err )
{
err = ErrSPIAEFindPage( pfucbAE, fSPFindAnyGreaterPage, spp::AvailExtLegacyGeneralPool, pgnoNull, pspaeiAlloc, NULL );
}
}
if ( errSPNoSpaceForYou == err )
{
Call( ErrSPIAEGetExtentAndPage( pfucb, pfucbAE,
spp::AvailExtLegacyGeneralPool,
1,
fSPAllocFlags | fSPSplitting | fSPOriginatingRequest,
pspaeiAlloc ) );
Assert( Pcsr( pfucbAE )->FLatched() );
}
Call( err );
Assert( Pcsr( pfucbAE )->FLatched() );
Assert( pspaeiAlloc->PgnoFirst() && pspaeiAlloc->PgnoFirst() != pgnoBadNews );
Assert( !pspaeiAlloc->FEmptyExtent() );
HandleError:
Assert( JET_errSuccess == err || !Pcsr( pfucbAE )->FLatched() );
Assert( err < JET_errSuccess || Pcsr( pfucbAE )->FLatched() );
return err;
}
ERR ErrSPIAEGetPage(
__inout FUCB * pfucb,
__in PGNO pgnoLast,
__inout PGNO * ppgnoAlloc,
__in const BOOL fSPAllocFlags,
__in const CPG cpgReserve
)
{
ERR err = JET_errSuccess;
FCB * const pfcb = pfucb->u.pfcb;
FUCB * pfucbAE = pfucbNil;
CSPExtentInfo cspaeiAlloc;
Assert( 0 == ( fSPAllocFlags & ~( fSPContinuous | fSPUseActiveReserve | fSPExactExtent ) ) );
AssertSPIPfucbOnRoot( pfucb );
CallR( ErrSPIOpenAvailExt( pfucb->ppib, pfcb, &pfucbAE ) );
Assert( pfcb == pfucbAE->u.pfcb );
Assert( pfucb->ppib == pfucbAE->ppib );
if ( fSPContinuous & fSPAllocFlags )
{
Call( ErrSPIAEGetContinuousPage( pfucb, pfucbAE, pgnoLast, cpgReserve, fSPAllocFlags & fSPUseActiveReserve, &cspaeiAlloc ) );
}
else
{
Call( ErrSPIAEGetAnyPage( pfucb, pfucbAE, pgnoLast, fSPAllocFlags & fSPExactExtent, &cspaeiAlloc ) );
}
Assert( err >= 0 );
Assert( Pcsr( pfucbAE )->FLatched() );
err = cspaeiAlloc.ErrCheckCorrupted();
CallS( err );
if ( err < JET_errSuccess )
{
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"4fbc1735-8688-40ae-898f-40e86deb52c4" );
}
Call( err );
Assert( cspaeiAlloc.PgnoFirst() && cspaeiAlloc.PgnoFirst() != pgnoBadNews );
Assert( !cspaeiAlloc.FEmptyExtent() );
Assert( cspaeiAlloc.CpgExtent() > 0 );
if ( cspaeiAlloc.FContains( pgnoLast ) )
{
AssertSz( fFalse, "AvailExt corrupted." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"ad23b08a-84d6-4d21-aefc-746560b0eceb" );
Call( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
*ppgnoAlloc = cspaeiAlloc.PgnoFirst();
SPCheckPgnoAllocTrap( *ppgnoAlloc );
Assert( *ppgnoAlloc != pgnoLast );
{
CSPExtentNodeKDF spAdjustedAvail( SPEXTKEY::fSPExtentTypeAE,
cspaeiAlloc.PgnoLast(),
cspaeiAlloc.CpgExtent(),
cspaeiAlloc.SppPool() );
Call( spAdjustedAvail.ErrConsumeSpace( cspaeiAlloc.PgnoFirst() ) );
if ( spAdjustedAvail.FDelete() )
{
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
}
else
{
Assert( FKeysEqual( pfucbAE->kdfCurr.key, spAdjustedAvail.GetKey() ) );
Call( ErrBTReplace(
pfucbAE,
spAdjustedAvail.GetData( ),
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
}
}
BTUp( pfucbAE );
err = JET_errSuccess;
if ( ( pgnoSystemRoot == pfucbAE->u.pfcb->PgnoFDP() )
&& g_rgfmp[pfucbAE->u.pfcb->Ifmp()].FCacheAvail() )
{
g_rgfmp[pfucbAE->u.pfcb->Ifmp()].AdjustCpgAvail( -1 );
}
HandleError:
if ( pfucbAE != pfucbNil )
{
BTClose( pfucbAE );
}
return err;
}
CPG CpgSPIConsumeActiveSpaceRequestReserve( FUCB * const pfucb )
{
Assert( !FFUCBSpace( pfucb ) );
const CPG cpgAddlReserve = CpgDIRActiveSpaceRequestReserve( pfucb );
DIRSetActiveSpaceRequestReserve( pfucb, cpgDIRReserveConsumed );
Assert( CpgDIRActiveSpaceRequestReserve( pfucb ) == cpgDIRReserveConsumed );
AssertSz( cpgAddlReserve != cpgDIRReserveConsumed, "The active space reserve should only be consumed one time." );
return cpgAddlReserve;
}
ERR ErrSPGetPage(
__inout FUCB * pfucb,
__in const PGNO pgnoLast,
__in const ULONG fSPAllocFlags,
__out PGNO * ppgnoAlloc
)
{
ERR err = errCodeInconsistency;
FCB * const pfcb = pfucb->u.pfcb;
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortSpace );
Assert( ppgnoAlloc != NULL );
Assert( 0 == ( fSPAllocFlags & ~fMaskSPGetPage ) );
CPG cpgAddlReserve = 0;
if ( fSPAllocFlags & fSPNewExtent )
{
cpgAddlReserve = 15;
}
if ( ( fSPAllocFlags & fSPContinuous ) && ( fSPAllocFlags & fSPUseActiveReserve ) )
{
cpgAddlReserve = CpgSPIConsumeActiveSpaceRequestReserve( pfucb );
}
if ( FFUCBSpace( pfucb ) )
{
err = ErrSPISPGetPage( pfucb, ppgnoAlloc );
}
else
{
#ifdef SPACECHECK
Assert( !( ErrSPIValidFDP( pfucb->ppib, pfucb->ifmp, PgnoFDP( pfucb ) ) < 0 ) );
if ( pgnoNull != pgnoLast )
{
CallS( ErrSPIWasAlloc( pfucb, pgnoLast, (CPG)1 ) );
}
#endif
if ( !pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucb, fTrue );
}
if ( FSPIIsSmall( pfcb ) )
{
err = ErrSPISmallGetPage( pfucb, pgnoLast, ppgnoAlloc );
if ( errSPNoSpaceForYou != err )
{
Assert( FSPExpectedError( err ) );
goto HandleError;
}
Call( ErrSPIConvertToMultipleExtent( pfucb, 1, 1 ) );
}
Call( ErrSPIAEGetPage(
pfucb,
pgnoLast,
ppgnoAlloc,
fSPAllocFlags & ( fSPContinuous | fSPUseActiveReserve | fSPExactExtent ),
cpgAddlReserve ) );
}
HandleError:
if ( err < JET_errSuccess )
{
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Failed to get page from %d.%lu\n", pfucb->ifmp, PgnoFDP( pfucb ) ) );
if ( errSPNoSpaceForYou == err ||
errCodeInconsistency == err )
{
AssertSz( fFalse, "Code malfunction." );
err = ErrERRCheck( JET_errInternalError );
}
}
else
{
Assert( FSPValidAllocPGNO( *ppgnoAlloc ) );
const PGNO pgnoFDP = PgnoFDP( pfucb );
ETSpaceAllocPage( pfucb->ifmp, pgnoFDP, *ppgnoAlloc, pfucb->u.pfcb->ObjidFDP(), TceFromFUCB( pfucb ) );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpace,
OSFormat( "get page 1 at %lu from %d.%lu\n", *ppgnoAlloc, pfucb->ifmp, PgnoFDP( pfucb ) ) );
}
return err;
}
LOCAL ERR ErrSPIFreeSEToParent(
FUCB *pfucb,
FUCB *pfucbOE,
FUCB *pfucbAE,
FUCB* const pfucbParent,
const PGNO pgnoLast,
const CPG cpgSize )
{
ERR err;
FCB *pfcb = pfucb->u.pfcb;
FCB *pfcbParent;
BOOL fState;
DIB dib;
FUCB *pfucbParentLocal = pfucbParent;
const CSPExtentKeyBM CSPOEKey( SPEXTKEY::fSPExtentTypeOE, pgnoLast );
Assert( pfcbNil != pfcb );
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRootOrNull( pfucbParent );
const PGNO pgnoParentFDP = PgnoSPIParentFDP( pfucb );
if ( pgnoParentFDP == pgnoNull )
{
Assert( pfucb->u.pfcb->PgnoFDP() == pgnoSystemRoot );
return JET_errSuccess;
}
pfcbParent = FCB::PfcbFCBGet( pfucb->ifmp, pgnoParentFDP, &fState, fTrue, fTrue );
Assert( pfcbParent != pfcbNil );
Assert( fFCBStateInitialized == fState );
Assert( !pfcb->FTypeNull() );
if ( !pfcb->FInitedForRecovery() )
{
if ( pfcb->FTypeSecondaryIndex() || pfcb->FTypeLV() )
{
Assert( pfcbParent->FTypeTable() );
}
else
{
Assert( pfcbParent->FTypeDatabase() );
Assert( !pfcbParent->FDeletePending() );
Assert( !pfcbParent->FDeleteCommitted() );
}
}
if ( pfucbAE != pfucbNil )
{
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
BTUp( pfucbAE );
}
dib.pos = posDown;
dib.pbm = CSPOEKey.Pbm( pfucbOE );
dib.dirflag = fDIRNull;
Call( ErrBTDown( pfucbOE, &dib, latchReadTouch ) );
Call( ErrBTFlagDelete(
pfucbOE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
BTUp( pfucbOE );
if ( pfucbParentLocal == pfucbNil )
{
Call( ErrBTIOpenAndGotoRoot( pfucb->ppib, pgnoParentFDP, pfucb->ifmp, &pfucbParentLocal ) );
}
Call( ErrSPFreeExt( pfucbParentLocal, pgnoLast - cpgSize + 1, cpgSize, "FreeToParent" ) );
if ( pgnoParentFDP == pgnoSystemRoot )
{
TLS* const ptls = Ptls();
ptls->threadstats.cPageTableReleased += cpgSize;
}
HandleError:
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRootOrNull( pfucbParent );
if ( ( pfucbParentLocal != pfucbNil ) && ( pfucbParentLocal != pfucbParent ) )
{
Expected( pfucbParent == pfucbNil );
AssertSPIPfucbOnRoot( pfucbParentLocal );
pfucbParentLocal->pcsrRoot->ReleasePage();
pfucbParentLocal->pcsrRoot = pcsrNil;
BTClose( pfucbParentLocal );
pfucbParentLocal = pfucbNil;
}
pfcbParent->Release();
return err;
}
LOCAL_BROKEN VOID SPIReportLostPages(
const IFMP ifmp,
const OBJID objidFDP,
const PGNO pgnoLast,
const CPG cpgLost )
{
WCHAR wszStartPagesLost[16];
WCHAR wszEndPagesLost[16];
WCHAR wszObjidFDP[16];
const WCHAR *rgcwszT[4];
OSStrCbFormatW( wszStartPagesLost, sizeof(wszStartPagesLost), L"%d", pgnoLast - cpgLost + 1 );
OSStrCbFormatW( wszEndPagesLost, sizeof(wszEndPagesLost), L"%d", pgnoLast );
OSStrCbFormatW( wszObjidFDP, sizeof(wszObjidFDP), L"%d", objidFDP );
rgcwszT[0] = g_rgfmp[ifmp].WszDatabaseName();
rgcwszT[1] = wszStartPagesLost;
rgcwszT[2] = wszEndPagesLost;
rgcwszT[3] = wszObjidFDP;
UtilReportEvent(
eventWarning,
SPACE_MANAGER_CATEGORY,
SPACE_LOST_ON_FREE_ID,
4,
rgcwszT,
0,
NULL,
PinstFromIfmp( ifmp ) );
}
ERR ErrSPISPFreeExt( __inout FUCB * pfucb, __in const PGNO pgnoFirst, __in const CPG cpgSize )
{
ERR err = JET_errSuccess;
const BOOL fAvailExt = FFUCBAvailExt( pfucb );
Assert( 1 == cpgSize );
if ( NULL == pfucb->u.pfcb->Psplitbuf( fAvailExt ) )
{
CSR *pcsrRoot = pfucb->pcsrRoot;
SPLIT_BUFFER spbuf;
DATA data;
AssertSPIPfucbOnSpaceTreeRoot( pfucb, pcsrRoot );
UtilMemCpy( &spbuf, PspbufSPISpaceTreeRootPage( pfucb, pcsrRoot ), sizeof(SPLIT_BUFFER) );
spbuf.ReturnPage( pgnoFirst );
Assert( latchRIW == pcsrRoot->Latch() );
pcsrRoot->UpgradeFromRIWLatch();
data.SetPv( &spbuf );
data.SetCb( sizeof(spbuf) );
err = ErrNDSetExternalHeader(
pfucb,
pcsrRoot,
&data,
( pfucb->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfWhole );
pcsrRoot->Downgrade( latchRIW );
}
else
{
AssertSPIPfucbOnSpaceTreeRoot( pfucb, pfucb->pcsrRoot );
pfucb->u.pfcb->Psplitbuf( fAvailExt )->ReturnPage( pgnoFirst );
err = JET_errSuccess;
}
return err;
}
ERR ErrSPISmallFreeExt( __inout FUCB * pfucb, __in const PGNO pgnoFirst, __in const CPG cpgSize )
{
ERR err = JET_errSuccess;
SPACE_HEADER sph;
UINT rgbitT;
INT iT;
DATA data;
AssertSPIPfucbOnRoot( pfucb );
Assert( cpgSize <= cpgSmallSpaceAvailMost );
Assert( FSPIIsSmall( pfucb->u.pfcb ) );
Assert( pgnoFirst > PgnoFDP( pfucb ) );
Assert( pgnoFirst - PgnoFDP( pfucb ) <= cpgSmallSpaceAvailMost );
Assert( ( pgnoFirst + cpgSize - 1 - PgnoFDP( pfucb ) ) <= cpgSmallSpaceAvailMost );
Assert( ( pgnoFirst + cpgSize - 1 ) <= g_rgfmp[pfucb->ifmp].PgnoLast() );
if ( latchWrite != pfucb->pcsrRoot->Latch() )
{
SPIUpgradeToWriteLatch( pfucb );
}
NDGetExternalHeader( pfucb, pfucb->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
UtilMemCpy( &sph, pfucb->kdfCurr.data.Pv(), sizeof(sph) );
for ( rgbitT = 1, iT = 1; iT < cpgSize; iT++ )
{
rgbitT = ( rgbitT << 1 ) + 1;
}
rgbitT <<= ( pgnoFirst - PgnoFDP( pfucb ) - 1 );
sph.SetRgbitAvail( sph.RgbitAvail() | rgbitT );
data.SetPv( &sph );
data.SetCb( sizeof(sph) );
Call( ErrNDSetExternalHeader(
pfucb,
pfucb->pcsrRoot,
&data,
( pfucb->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfSpaceHeader ) );
HandleError:
return err;
}
ERR ErrSPIAERemoveInsertionRegion(
__in const FCB * const pfcb,
__inout FUCB * const pfucbAE,
__in const CSPExtentInfo * const pcspoeContaining,
__in const PGNO pgnoFirstToFree,
__inout CPG * const pcpgSizeToFree
)
{
ERR err = JET_errSuccess;
DIB dibAE;
CSPExtentKeyBM cspextkeyAE;
CSPExtentInfo cspaei;
PGNO pgnoLast = pgnoFirstToFree + (*pcpgSizeToFree) - 1;
Assert( !Pcsr( pfucbAE )->FLatched() );
const SpacePool sppAvailContinuousPool = spp::ContinuousPool;
cspextkeyAE.SPExtentMakeKeyBM( SPEXTKEY::fSPExtentTypeAE, pgnoFirstToFree - 1, sppAvailContinuousPool );
Assert( cspextkeyAE.GetBm( pfucbAE ).data.Pv() == NULL );
Assert( cspextkeyAE.GetBm( pfucbAE ).data.Cb() == 0 );
dibAE.pos = posDown;
dibAE.pbm = cspextkeyAE.Pbm( pfucbAE );
dibAE.dirflag = fDIRFavourNext;
err = ErrBTDown( pfucbAE, &dibAE, latchReadTouch );
Assert( err != JET_errNoCurrentRecord );
if ( JET_errRecordNotFound == err )
{
err = JET_errSuccess;
goto HandleError;
}
if ( err < 0 )
{
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "ErrSPIAERemoveInsertionRegion could not go down into nonempty available extent tree. [ifmp=0x%x]\n", pfucbAE->ifmp ) );
}
Call( err );
BOOL fOnNextExtent = fFalse;
cspaei.Set( pfucbAE );
ERR errT = cspaei.ErrCheckCorrupted();
if( errT < JET_errSuccess )
{
CallS( errT );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"af6f9c2c-efa4-4c9e-bb1d-0cf605697457" );
Call( errT );
}
if ( cspaei.SppPool() != sppAvailContinuousPool )
{
ExpectedSz( ( cspaei.SppPool() == spp::AvailExtLegacyGeneralPool ) ||
( pfcb->PgnoFDP() == pgnoSystemRoot ), "We only have a next pool for the DB root today." );
err = JET_errSuccess;
goto HandleError;
}
if( !cspaei.FEmptyExtent() )
{
Assert( pgnoFirstToFree > cspaei.PgnoLast() ||
pgnoLast < cspaei.PgnoFirst() );
}
if ( wrnNDFoundGreater == err )
{
Assert( cspaei.PgnoLast() > pgnoFirstToFree - 1 );
fOnNextExtent = fTrue;
}
else
{
Assert( wrnNDFoundLess == err || JET_errSuccess == err );
Assert( cspaei.PgnoLast() <= pgnoFirstToFree - 1 );
cspaei.Unset();
err = ErrBTNext( pfucbAE, fDIRNull );
if ( err < 0 )
{
if ( JET_errNoCurrentRecord == err )
{
err = JET_errSuccess;
goto HandleError;
}
Call( err );
CallS( err );
}
else
{
cspaei.Set( pfucbAE );
errT = cspaei.ErrCheckCorrupted();
if( errT < JET_errSuccess )
{
CallS( errT );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"30d82277-2e77-4742-af4d-1d1808205ba6" );
Call( errT );
}
if ( cspaei.SppPool() != sppAvailContinuousPool )
{
ExpectedSz( ( cspaei.SppPool() == spp::AvailExtLegacyGeneralPool ) ||
( pfcb->PgnoFDP() == pgnoSystemRoot ), "We only have a next pool for the DB root today." );
err = JET_errSuccess;
goto HandleError;
}
if( !cspaei.FEmptyExtent() )
{
Assert( pgnoFirstToFree > cspaei.PgnoLast() ||
pgnoLast < cspaei.PgnoFirst() );
}
fOnNextExtent = fTrue;
}
}
Assert( cspaei.FValidExtent() );
Assert( fOnNextExtent );
Assert( cspaei.SppPool() == sppAvailContinuousPool );
if ( !cspaei.FEmptyExtent() &&
pgnoLast >= cspaei.PgnoFirst() )
{
AssertSz( fFalse, "AvailExt corrupted." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"d02a83ff-28b7-4523-8dee-c862ca33cf7e" );
Call( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
BOOL fDeleteInsertionRegion = fFalse;
if ( cspaei.FEmptyExtent() )
{
if ( pgnoLast == cspaei.PgnoMarker() &&
cspaei.PgnoLast() <= pcspoeContaining->PgnoLast() )
{
fDeleteInsertionRegion = fTrue;
}
}
else
{
Assert( cspaei.FValidExtent() );
Assert( cspaei.CpgExtent() != 0 );
if ( pgnoLast >= cspaei.PgnoFirst() )
{
AssertSz( fFalse, "AvailExt corrupted." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"ba12baa3-cd1e-4726-9e9b-94bf34d99a14" );
Call( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( pgnoLast == cspaei.PgnoLast() - cspaei.CpgExtent() &&
cspaei.PgnoLast() <= pcspoeContaining->PgnoLast() )
{
fDeleteInsertionRegion = fTrue;
}
}
if ( fDeleteInsertionRegion )
{
if ( !cspaei.FEmptyExtent() )
{
Assert( cspaei.PgnoLast() <= pcspoeContaining->PgnoLast() );
*pcpgSizeToFree = *pcpgSizeToFree + cspaei.CpgExtent();
}
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Assert( Pcsr( pfucbAE )->FLatched() );
err = cspaei.FEmptyExtent() ? JET_errSuccess : wrnSPReservedPages;
}
else
{
err = JET_errSuccess;
}
HandleError:
BTUp( pfucbAE );
return err;
}
LOCAL VOID SPIReportSpaceLeak( __in const FUCB* const pfucb, __in const ERR err, __in const PGNO pgnoFirst, __in const CPG cpg, __in_z const CHAR* const szTag )
{
Assert( pfucb != NULL );
Expected( err < JET_errSuccess );
Assert( pgnoFirst != pgnoNull );
Assert( cpg > 0 );
const PGNO pgnoLast = pgnoFirst + cpg - 1;
const OBJID objidFDP = pfucb->u.pfcb->ObjidFDP();
const BOOL fDbRoot = ( pfucb->u.pfcb->PgnoFDP() == pgnoSystemRoot );
OSTraceSuspendGC();
const WCHAR* rgcwsz[] =
{
g_rgfmp[ pfucb->ifmp ].WszDatabaseName(),
OSFormatW( L"%I32d", err ),
OSFormatW( L"%I32u", objidFDP ),
OSFormatW( L"%I32d", cpg ),
OSFormatW( L"%I32u", pgnoFirst ),
OSFormatW( L"%I32u", pgnoLast ),
OSFormatW( L"%hs", szTag ),
};
UtilReportEvent(
fDbRoot ? eventError : eventWarning,
GENERAL_CATEGORY,
fDbRoot ? DATABASE_LEAKED_ROOT_SPACE_ID : DATABASE_LEAKED_NON_ROOT_SPACE_ID,
_countof( rgcwsz ),
rgcwsz,
0,
NULL,
g_rgfmp[ pfucb->ifmp ].Pinst() );
OSTraceResumeGC();
}
LOCAL ERR ErrSPIAEFreeExt( __inout FUCB * pfucb, __in PGNO pgnoFirst, __in CPG cpgSize, __in FUCB * const pfucbParent = pfucbNil )
{
ERR err = errCodeInconsistency;
PIB * const ppib = pfucb->ppib;
FCB * const pfcb = pfucb->u.pfcb;
PGNO pgnoLast = pgnoFirst + cpgSize - 1;
BOOL fCoalesced = fFalse;
CPG cpgSizeAdj = 0;
Assert( !FSPIIsSmall( pfcb ) );
Assert( cpgSize > 0 );
CSPExtentInfo cspoeContaining;
CSPExtentInfo cspaei;
CSPExtentKeyBM cspextkeyAE;
DIB dibAE;
FUCB *pfucbAE = pfucbNil;
FUCB *pfucbOE = pfucbNil;
const SpacePool sppAvailGeneralPool = spp::AvailExtLegacyGeneralPool;
#ifdef DEBUG
BOOL fWholeKitAndKabudle = fFalse;
#endif
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRootOrNull( pfucbParent );
if ( ( pgnoLast > g_rgfmp[pfcb->Ifmp()].PgnoLast() ) && ( pfcb->PgnoFDP() == pgnoSystemRoot ) )
{
Assert( pfucbParent == pfucbNil );
Assert( !g_rgfmp[pfcb->Ifmp()].FIsTempDB() );
const PGNO pgnoFirstUnshelve = max( pgnoFirst, g_rgfmp[pfcb->Ifmp()].PgnoLast() + 1 );
Call( ErrSPIUnshelvePagesInRange( pfucb, pgnoFirstUnshelve, pgnoLast ) );
if ( pgnoFirst > g_rgfmp[pfcb->Ifmp()].PgnoLast() )
{
goto HandleError;
}
pgnoLast = min( pgnoLast, g_rgfmp[pfcb->Ifmp()].PgnoLast() );
Assert( pgnoLast >= pgnoFirst );
cpgSize = pgnoLast - pgnoFirst + 1;
}
cpgSizeAdj = cpgSize;
Call( ErrSPIOpenOwnExt( ppib, pfcb, &pfucbOE ) );
Assert( pfcb == pfucbOE->u.pfcb );
Call( ErrSPIFindExtOE( pfucbOE, pgnoFirst, &cspoeContaining ) );
if ( ( pgnoFirst > cspoeContaining.PgnoLast() ) || ( pgnoLast < cspoeContaining.PgnoFirst() ) )
{
err = JET_errSuccess;
goto HandleError;
}
else if ( ( pgnoFirst < cspoeContaining.PgnoFirst() ) || ( pgnoLast > cspoeContaining.PgnoLast() ) )
{
FireWall( "CorruptedOeTree" );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbOE ), HaDbFailureTagCorruption, L"9322391a-63fb-4718-948e-89425a75ed2e" );
Call( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
BTUp( pfucbOE );
Call( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbAE ) );
Assert( pfcb == pfucbAE->u.pfcb );
if ( pgnoLast == cspoeContaining.PgnoLast()
&& cpgSizeAdj == cspoeContaining.CpgExtent() )
{
Call( ErrSPIReserveSPBufPages( pfucb, pfucbParent ) );
OnDebug( fWholeKitAndKabudle = fTrue );
goto InsertExtent;
}
CoallesceWithNeighbors:
Call( ErrSPIReserveSPBufPages( pfucb, pfucbParent ) );
cspextkeyAE.SPExtentMakeKeyBM( SPEXTKEY::fSPExtentTypeAE, pgnoFirst - 1, sppAvailGeneralPool );
Assert( cspextkeyAE.GetBm( pfucbAE ).data.Pv() == NULL );
Assert( cspextkeyAE.GetBm( pfucbAE ).data.Cb() == 0 );
dibAE.pos = posDown;
dibAE.pbm = cspextkeyAE.Pbm( pfucbAE );
dibAE.dirflag = fDIRFavourNext;
err = ErrBTDown( pfucbAE, &dibAE, latchReadTouch );
if ( JET_errRecordNotFound != err )
{
BOOL fOnNextExtent = fFalse;
Assert( err != JET_errNoCurrentRecord );
if ( err < 0 )
{
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "ErrSPFreeExt could not go down into nonempty available extent tree. [ifmp=0x%x]\n", pfucbAE->ifmp ) );
}
Call( err );
cspaei.Set( pfucbAE );
ERR errT = cspaei.ErrCheckCorrupted();
if( errT < JET_errSuccess )
{
AssertSz( fFalse, "Corruption bad." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"2bc482de-56bd-44ce-ae3d-d51b7a0343df" );
Call( errT );
}
Assert( cspaei.CpgExtent() >= 0 );
#ifdef DEPRECATED_ZERO_SIZED_AVAIL_EXTENT_CLEANUP
if ( 0 == cspaei.CpgExtent() )
{
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
BTUp( pfucbAE );
goto CoallesceWithNeighbors;
}
#endif
if ( cspaei.SppPool() == sppAvailGeneralPool )
{
Assert( pgnoFirst > cspaei.PgnoLast() ||
pgnoLast < cspaei.PgnoFirst() );
if ( wrnNDFoundGreater == err )
{
Assert( cspaei.PgnoLast() > pgnoFirst - 1 );
fOnNextExtent = fTrue;
}
else if ( wrnNDFoundLess == err )
{
Assert( cspaei.PgnoLast() < pgnoFirst - 1 );
}
else
{
Assert( cspaei.PgnoLast() == pgnoFirst - 1 );
CallS( err );
}
if ( JET_errSuccess == err
&& pgnoFirst > cspoeContaining.PgnoFirst() )
{
Assert( cspaei.PgnoFirst() >= cspoeContaining.PgnoFirst() );
#ifdef DEBUG
CPG cpgAECurrencyCheck;
CallS( ErrSPIExtentCpg( pfucbAE, &cpgAECurrencyCheck ) );
Assert( cspaei.CpgExtent() == cpgAECurrencyCheck );
#endif
Assert( cspaei.PgnoLast() == pgnoFirst - 1 );
cpgSizeAdj += cspaei.CpgExtent();
pgnoFirst -= cspaei.CpgExtent();
Assert( pgnoLast == pgnoFirst + cpgSizeAdj - 1 );
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Assert( !fOnNextExtent );
if ( pgnoLast == cspoeContaining.PgnoLast()
&& cpgSizeAdj == cspoeContaining.CpgExtent() )
{
OnDebug( fWholeKitAndKabudle = fTrue );
goto InsertExtent;
}
Pcsr( pfucbAE )->Downgrade( latchReadTouch );
Assert( cspoeContaining.PgnoFirst() <= pgnoFirst );
Assert( cspoeContaining.PgnoLast() >= pgnoLast );
}
if ( !fOnNextExtent )
{
err = ErrBTNext( pfucbAE, fDIRNull );
if ( err < 0 )
{
if ( JET_errNoCurrentRecord == err )
{
err = JET_errSuccess;
}
else
{
Call( err );
}
}
else
{
fOnNextExtent = fTrue;
}
}
if ( fOnNextExtent )
{
cspaei.Set( pfucbAE );
if ( cspaei.SppPool() == sppAvailGeneralPool )
{
Assert( cspaei.CpgExtent() != 0 );
if ( pgnoLast >= cspaei.PgnoFirst() )
{
AssertSz( fFalse, "AvailExt corrupted." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"5bc71f68-0ef3-4fb6-9c36-20bdbb1f5a70" );
Call( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( ( pgnoLast == ( cspaei.PgnoFirst() - 1 ) ) &&
( cspaei.PgnoLast() <= cspoeContaining.PgnoLast() ) )
{
CSPExtentNodeKDF spAdjustedSize( SPEXTKEY::fSPExtentTypeAE, cspaei.PgnoLast(), cspaei.CpgExtent(), sppAvailGeneralPool );
spAdjustedSize.ErrUnconsumeSpace( cpgSizeAdj );
cpgSizeAdj += cspaei.CpgExtent();
Call( ErrBTReplace(
pfucbAE,
spAdjustedSize.GetData( ),
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Assert( Pcsr( pfucbAE )->FLatched() );
pgnoLast = cspaei.PgnoLast();
fCoalesced = fTrue;
if ( cpgSizeAdj >= cpageSEDefault
&& pgnoNull != pfcb->PgnoNextAvailSE()
&& pgnoFirst < pfcb->PgnoNextAvailSE() )
{
pfcb->SetPgnoNextAvailSE( pgnoFirst );
}
}
}
}
}
}
if ( !fCoalesced )
{
InsertExtent:
BTUp( pfucbAE );
const CPG cpgSave = cpgSizeAdj;
Call( ErrSPIAERemoveInsertionRegion( pfcb, pfucbAE, &cspoeContaining, pgnoFirst, &cpgSizeAdj ) );
Assert( !fWholeKitAndKabudle || wrnSPReservedPages != err );
if ( wrnSPReservedPages == err ||
cpgSave != cpgSizeAdj )
{
Assert( wrnSPReservedPages == err && cpgSave != cpgSizeAdj );
pgnoLast = pgnoFirst + cpgSizeAdj - 1;
Assert( cspoeContaining.FContains( pgnoLast ) );
Assert( cspoeContaining.FContains( pgnoFirst ) );
goto CoallesceWithNeighbors;
}
BTUp( pfucbAE );
Call( ErrSPIAddFreedExtent(
pfucb,
pfucbAE,
pgnoLast,
cpgSizeAdj ) );
}
Assert( Pcsr( pfucbAE )->FLatched() );
if ( ( pgnoSystemRoot == pfucbAE->u.pfcb->PgnoFDP() )
&& g_rgfmp[pfucbAE->u.pfcb->Ifmp()].FCacheAvail() )
{
g_rgfmp[pfucbAE->u.pfcb->Ifmp()].AdjustCpgAvail( cpgSize );
}
Assert( pgnoLast != cspoeContaining.PgnoLast() || cpgSizeAdj <= cspoeContaining.CpgExtent() );
if ( pgnoLast == cspoeContaining.PgnoLast() && cpgSizeAdj == cspoeContaining.CpgExtent() )
{
Assert( cpgSizeAdj > 0 );
#ifdef DEBUG
Assert( Pcsr( pfucbAE )->FLatched() );
cspaei.Set( pfucbAE );
Assert( cspaei.PgnoLast() == pgnoLast );
Assert( cspaei.CpgExtent() == cpgSizeAdj );
#endif
#ifdef DEBUG
if ( ErrFaultInjection( 62250 ) >= JET_errSuccess )
#endif
{
Call( ErrSPIFreeSEToParent( pfucb, pfucbOE, pfucbAE, pfucbParent, cspoeContaining.PgnoLast(), cspoeContaining.CpgExtent() ) );
}
}
HandleError:
Assert( FSPExpectedError( err ) );
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRootOrNull( pfucbParent );
if ( pfucbAE != pfucbNil )
{
BTClose( pfucbAE );
}
if ( pfucbOE != pfucbNil )
{
BTClose( pfucbOE );
}
Assert( err != JET_errKeyDuplicate );
return err;
}
ERR ErrSPCaptureSnapshot( FUCB* const pfucb, const PGNO pgnoFirst, const CPG cpgSize )
{
ERR err = JET_errSuccess;
BOOL fEfvEnabled = ( g_rgfmp[pfucb->ifmp].FLogOn() && PinstFromPfucb( pfucb )->m_plog->ErrLGFormatFeatureEnabled( JET_efvRevertSnapshot ) >= JET_errSuccess );
const CPG cpgPrereadMax = LFunctionalMax( 1, (CPG)( UlParam( JET_paramMaxCoalesceReadSize ) / g_cbPage ) );
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortFreeExtSnapshot );
for ( CPG cpgT = 0; cpgT < cpgSize; cpgT += cpgPrereadMax )
{
CPG cpgRead = LFunctionalMin( cpgSize - cpgT, cpgPrereadMax );
if ( g_rgfmp[ pfucb->ifmp ].FRBSOn() )
{
BFPrereadPageRange( pfucb->ifmp, pgnoFirst + cpgT, cpgRead, bfprfDefault, pfucb->ppib->BfpriPriority( pfucb->ifmp ), *tcScope );
BFLatch bfl;
for( int i = 0; i < cpgRead; ++i )
{
err = ErrBFWriteLatchPage( &bfl, pfucb->ifmp, pgnoFirst + cpgT + i, bflfUninitPageOk, pfucb->ppib->BfpriPriority( pfucb->ifmp ), *tcScope );
if ( err == JET_errPageNotInitialized )
{
BFMarkAsSuperCold( pfucb->ifmp, pgnoFirst + cpgT + i );
continue;
}
CallR( err );
BFMarkAsSuperCold( &bfl );
BFWriteUnlatch( &bfl );
}
}
if ( fEfvEnabled )
{
CallR( ErrLGExtentFreed( PinstFromPfucb( pfucb )->m_plog, pfucb->ifmp, pgnoFirst + cpgT, cpgRead ) );
}
}
return JET_errSuccess;
}
ERR ErrSPFreeExt( FUCB* const pfucb, const PGNO pgnoFirst, const CPG cpgSize, const CHAR* const szTag )
{
ERR err;
FCB * const pfcb = pfucb->u.pfcb;
BOOL fRootLatched = fFalse;
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucb );
tcScope->SetDwEngineObjid( ObjidFDP( pfucb ) );
tcScope->iorReason.SetIort( iortSpace );
Assert( cpgSize > 0 );
#ifdef SPACECHECK
CallS( ErrSPIValidFDP( ppib, pfucb->ifmp, PgnoFDP( pfucb ) ) );
#endif
Call( ErrFaultInjection( 41610 ) );
if ( FFUCBSpace( pfucb ) )
{
Call( ErrSPISPFreeExt( pfucb, pgnoFirst, cpgSize ) );
}
else
{
if ( pfucb->pcsrRoot == pcsrNil )
{
Assert( !Pcsr( pfucb )->FLatched() );
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
fRootLatched = fTrue;
}
else
{
Assert( pfucb->pcsrRoot->Pgno() == PgnoRoot( pfucb ) );
Assert( pfucb->pcsrRoot->Latch() == latchRIW
|| pfucb->pcsrRoot->Latch() == latchWrite );
}
if ( !pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucb, fTrue );
}
#ifdef SPACECHECK
CallS( ErrSPIWasAlloc( pfucb, pgnoFirst, cpgSize ) );
#endif
Assert( pfucb->pcsrRoot != pcsrNil );
if ( FSPIIsSmall( pfcb ) )
{
Call( ErrSPISmallFreeExt( pfucb, pgnoFirst, cpgSize ) );
}
else
{
Call( ErrSPIAEFreeExt( pfucb, pgnoFirst, cpgSize ) );
}
}
CallS( err );
HandleError:
if( err < JET_errSuccess )
{
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Failed to free space %lu at %lu to FDP %d.%lu\n", cpgSize, pgnoFirst, pfucb->ifmp, PgnoFDP( pfucb ) ) );
SPIReportSpaceLeak( pfucb, err, pgnoFirst, cpgSize, szTag );
}
else
{
const PGNO pgnoFDP = PgnoFDP( pfucb );
if ( cpgSize > 1 )
{
ETSpaceFreeExt( pfucb->ifmp, pgnoFDP, pgnoFirst, cpgSize, pfucb->u.pfcb->ObjidFDP(), TceFromFUCB( pfucb ) );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceManagement,
OSFormat( "Free space %lu at %lu to FDP %d.%lu\n", cpgSize, pgnoFirst, pfucb->ifmp, PgnoFDP( pfucb ) ) );
}
else
{
ETSpaceFreePage( pfucb->ifmp, pgnoFDP, pgnoFirst, pfucb->u.pfcb->ObjidFDP(), TceFromFUCB( pfucb ) );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceManagement,
OSFormat( "Free page at %lu to FDP %d.%lu\n", pgnoFirst, pfucb->ifmp, PgnoFDP( pfucb ) ) );
}
}
if ( fRootLatched )
{
Assert( Pcsr( pfucb ) == pfucb->pcsrRoot );
Assert( pfucb->pcsrRoot->FLatched() );
pfucb->pcsrRoot->ReleasePage();
pfucb->pcsrRoot = pcsrNil;
}
Assert( err != JET_errKeyDuplicate );
return err;
}
LOCAL ERR ErrErrBitmapToJetErr( const IBitmapAPI::ERR err )
{
switch ( err )
{
case IBitmapAPI::ERR::errSuccess:
return JET_errSuccess;
case IBitmapAPI::ERR::errInvalidParameter:
return ErrERRCheck( JET_errInvalidParameter );
case IBitmapAPI::ERR::errOutOfMemory:
return ErrERRCheck( JET_errOutOfMemory );
}
AssertSz( fFalse, "UnknownIBitmapAPI::ERR: %s", (int)err );
return ErrERRCheck( JET_errInternalError );
}
ERR ErrSPTryCoalesceAndFreeAvailExt( FUCB* const pfucb, const PGNO pgnoInExtent, BOOL* const pfCoalesced )
{
Assert( !FFUCBSpace( pfucb ) );
ERR err = JET_errSuccess;
PIB* const ppib = pfucb->ppib;
FCB* const pfcb = pfucb->u.pfcb;
FUCB* pfucbOE = pfucbNil;
FUCB* pfucbAE = pfucbNil;
CSPExtentInfo speiContaining;
CSparseBitmap spbmAvail;
Assert( !FSPIIsSmall( pfcb ) );
Assert( pfcb->PgnoFDP() != pgnoSystemRoot );
*pfCoalesced = fFalse;
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
Call( ErrSPIOpenOwnExt( ppib, pfcb, &pfucbOE ) );
Call( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbAE ) );
err = ErrSPIFindExtOE( pfucbOE, pgnoInExtent, &speiContaining );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
err = JET_errSuccess;
}
Call( err );
if ( !speiContaining.FIsSet() || !speiContaining.FContains( pgnoInExtent ) )
{
goto HandleError;
}
BTUp( pfucbOE );
const PGNO pgnoOeFirst = speiContaining.PgnoFirst();
const PGNO pgnoOeLast = speiContaining.PgnoLast();
const CPG cpgOwnExtent = speiContaining.CpgExtent();
Call( ErrErrBitmapToJetErr( spbmAvail.ErrInitBitmap( cpgOwnExtent ) ) );
for ( SpacePool sppAvailPool = spp::MinPool;
sppAvailPool < spp::MaxPool;
sppAvailPool++ )
{
if ( sppAvailPool == spp::ShelvedPool )
{
continue;
}
PGNO pgno = pgnoOeFirst;
while ( pgno <= pgnoOeLast )
{
CSPExtentInfo speiAE;
err = ErrSPIFindExtAE( pfucbAE, pgno, sppAvailPool, &speiAE );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
err = JET_errSuccess;
}
Call( err );
err = JET_errSuccess;
Assert( !speiAE.FIsSet() || ( speiAE.PgnoLast() >= pgno ) );
if ( speiAE.FIsSet() &&
( speiAE.CpgExtent() > 0 ) &&
( ( speiAE.PgnoFirst() < pgnoOeFirst ) ||
( speiContaining.FContains( speiAE.PgnoFirst() ) && !speiContaining.FContains( speiAE.PgnoLast() ) ) ) )
{
AssertTrack( fFalse, "TryCoalesceAvailOverlapExt" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( speiAE.FIsSet() &&
( speiAE.SppPool() != spp::AvailExtLegacyGeneralPool ) &&
( speiAE.SppPool() != spp::ContinuousPool ) )
{
FireWall( OSFormat( "TryCoalesceAvailUnkPool:0x%I32x", speiAE.SppPool() ) );
goto HandleError;
}
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() > pgnoOeLast ) )
{
break;
}
if ( speiAE.CpgExtent() > 0 )
{
for ( PGNO pgnoAvail = speiAE.PgnoFirst(); pgnoAvail <= speiAE.PgnoLast(); pgnoAvail++ )
{
#ifdef DEBUG
BOOL fSet = fFalse;
if ( spbmAvail.ErrGet( pgnoAvail - pgnoOeFirst, &fSet ) == IBitmapAPI::ERR::errSuccess )
{
Assert( !fSet );
}
#endif
Call( ErrErrBitmapToJetErr( spbmAvail.ErrSet( pgnoAvail - pgnoOeFirst, fTrue ) ) );
}
}
BTUp( pfucbAE );
pgno = speiAE.PgnoLast() + 1;
}
BTUp( pfucbAE );
}
BTUp( pfucbAE );
Expected( g_rgfmp[pfucb->ifmp].FShrinkIsRunning() );
for ( PGNO ipgno = 0; ipgno < (PGNO)cpgOwnExtent; ipgno++ )
{
const size_t i = ( ( ipgno % 2 ) == 0 ) ? ( ipgno / 2 ) : ( (PGNO)cpgOwnExtent - 1 - ( ipgno / 2 ) );
BOOL fSet = fFalse;
Call( ErrErrBitmapToJetErr( spbmAvail.ErrGet( i, &fSet ) ) );
if ( !fSet )
{
goto HandleError;
}
}
for ( SpacePool sppAvailPool = spp::MinPool;
sppAvailPool < spp::MaxPool;
sppAvailPool++ )
{
if ( sppAvailPool == spp::ShelvedPool )
{
continue;
}
PGNO pgno = pgnoOeFirst;
while ( pgno <= pgnoOeLast )
{
Call( ErrSPIReserveSPBufPages( pfucb, pfucbNil ) );
CSPExtentInfo speiAE;
err = ErrSPIFindExtAE( pfucbAE, pgno, sppAvailPool, &speiAE );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
err = JET_errSuccess;
}
Call( err );
err = JET_errSuccess;
Assert( !speiAE.FIsSet() || ( speiAE.PgnoLast() >= pgno ) );
Assert( !( speiAE.FIsSet() &&
( speiAE.CpgExtent() > 0 ) &&
( ( speiAE.PgnoFirst() < pgnoOeFirst ) ||
( speiContaining.FContains( speiAE.PgnoFirst() ) && !speiContaining.FContains( speiAE.PgnoLast() ) ) ) ) );
Assert( !( speiAE.FIsSet() &&
( speiAE.SppPool() != spp::AvailExtLegacyGeneralPool ) &&
( speiAE.SppPool() != spp::ContinuousPool ) ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() > pgnoOeLast ) )
{
break;
}
pgno = speiAE.PgnoFirst();
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
BTUp( pfucbAE );
while ( pgno <= speiAE.PgnoLast() )
{
Call( ErrErrBitmapToJetErr( spbmAvail.ErrSet( pgno - pgnoOeFirst, fFalse ) ) );
pgno++;
}
}
BTUp( pfucbAE );
}
BTUp( pfucbAE );
for ( PGNO pgno = pgnoOeFirst; pgno <= pgnoOeLast; pgno++ )
{
BOOL fSet = fFalse;
Call( ErrErrBitmapToJetErr( spbmAvail.ErrGet( pgno - pgnoOeFirst, &fSet ) ) );
if ( fSet )
{
AssertTrack( fFalse, "TryCoalesceAvailAeChanged" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
}
Call( ErrSPIReserveSPBufPages( pfucb, pfucbNil ) );
Call( ErrSPIFreeSEToParent(
pfucb,
pfucbOE,
pfucbNil,
pfucbNil,
pgnoOeLast,
cpgOwnExtent ) );
*pfCoalesced = fTrue;
HandleError:
if ( pfucbAE != pfucbNil )
{
BTUp( pfucbAE );
BTClose( pfucbAE );
pfucbAE = pfucbNil;
}
if ( pfucbOE != pfucbNil )
{
BTUp( pfucbOE );
BTClose( pfucbOE );
pfucbOE = pfucbNil;
}
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
return err;
}
ERR ErrSPShelvePage( PIB* const ppib, const IFMP ifmp, const PGNO pgno )
{
Assert( pgno != pgnoNull );
ERR err = JET_errSuccess;
FMP* const pfmp = g_rgfmp + ifmp;
Assert( !pfmp->FIsTempDB() );
Assert( pfmp->FBeyondPgnoShrinkTarget( pgno ) );
Assert( pgno <= pfmp->PgnoLast() );
FUCB* pfucbRoot = pfucbNil;
FUCB* pfucbAE = pfucbNil;
Call( ErrBTIOpenAndGotoRoot( ppib, pgnoSystemRoot, ifmp, &pfucbRoot ) );
Call( ErrSPIOpenAvailExt( ppib, pfucbRoot->u.pfcb, &pfucbAE ) );
Call( ErrSPIReserveSPBufPages( pfucbRoot, pfucbNil ) );
Call( ErrSPIAddToAvailExt( pfucbAE, pgno, 1, spp::ShelvedPool ) );
Assert( Pcsr( pfucbAE )->FLatched() );
HandleError:
if ( pfucbAE != pfucbNil )
{
BTUp( pfucbAE );
BTClose( pfucbAE );
pfucbAE = pfucbNil;
}
if ( pfucbRoot != pfucbNil )
{
pfucbRoot->pcsrRoot->ReleasePage();
pfucbRoot->pcsrRoot = pcsrNil;
BTClose( pfucbRoot );
pfucbRoot = pfucbNil;
}
return err;
}
ERR ErrSPUnshelveShelvedPagesBelowEof( PIB* const ppib, const IFMP ifmp )
{
ERR err = JET_errSuccess;
FMP* const pfmp = g_rgfmp + ifmp;
FUCB* pfucbRoot = pfucbNil;
BOOL fInTransaction = fFalse;
Assert( !pfmp->FIsTempDB() );
Expected( pfmp->FShrinkIsRunning() );
Call( ErrDIRBeginTransaction( ppib, 46018, NO_GRBIT ) );
fInTransaction = fTrue;
Call( ErrBTIOpenAndGotoRoot( ppib, pgnoSystemRoot, ifmp, &pfucbRoot ) );
Call( ErrSPIUnshelvePagesInRange( pfucbRoot, 1, pfmp->PgnoLast() ) );
HandleError:
if ( pfucbRoot != pfucbNil )
{
pfucbRoot->pcsrRoot->ReleasePage();
pfucbRoot->pcsrRoot = pcsrNil;
BTClose( pfucbRoot );
pfucbRoot = pfucbNil;
}
if ( fInTransaction )
{
if ( err >= JET_errSuccess )
{
err = ErrDIRCommitTransaction( ppib, NO_GRBIT );
fInTransaction = ( err < JET_errSuccess );
}
if ( fInTransaction )
{
CallSx( ErrDIRRollback( ppib ), JET_errRollbackError );
fInTransaction = fFalse;
}
}
return err;
}
ERR ErrSPIUnshelvePagesInRange( FUCB* const pfucbRoot, const PGNO pgnoFirst, const PGNO pgnoLast )
{
ERR err = JET_errSuccess;
FUCB* pfucbAE = pfucbNil;
AssertSPIPfucbOnRoot( pfucbRoot );
Assert( ( pgnoFirst != pgnoNull ) && ( pgnoLast != pgnoNull) );
Assert( pgnoFirst <= pgnoLast );
FMP* const pfmp = g_rgfmp + pfucbRoot->ifmp;
Assert( !pfmp->FIsTempDB() );
const PGNO pgnoLastDbRootInitial = pfmp->PgnoLast();
PGNO pgnoLastDbRootPrev = pgnoLastDbRootInitial;
PGNO pgnoLastDbRoot = pgnoLastDbRootInitial;
Expected( ( pgnoLast <= pgnoLastDbRootInitial ) || ( pgnoFirst > pgnoLastDbRootInitial ) );
PGNO pgno = pgnoFirst;
Call( ErrSPIOpenAvailExt( pfucbRoot->ppib, pfucbRoot->u.pfcb, &pfucbAE ) );
while ( pgno <= pgnoLast )
{
pgnoLastDbRootPrev = pgnoLastDbRoot;
Call( ErrSPIReserveSPBufPages( pfucbRoot, pfucbNil ) );
pgnoLastDbRoot = pfmp->PgnoLast();
Assert( pgnoLastDbRoot >= pgnoLastDbRootPrev );
CSPExtentInfo speiAE;
Call( ErrSPISeekRootAE( pfucbAE, pgno, spp::ShelvedPool, &speiAE ) );
Assert( !speiAE.FIsSet() || ( speiAE.CpgExtent() == 1 ) );
AssertTrack( !speiAE.FIsSet() ||
( pgnoLastDbRoot == pgnoLastDbRootPrev ) ||
( speiAE.PgnoLast() <= pgnoLastDbRootPrev ) ||
( speiAE.PgnoFirst() > pgnoLastDbRoot ),
"UnshelvePagesNotUnshelvedByGrowth" );
AssertTrack( ( pgnoFirst <= pgnoLastDbRootInitial ) ||
( speiAE.FIsSet() && ( pgno == speiAE.PgnoFirst() ) ||
( pgno <= pgnoLastDbRoot ) ),
"UnshelvePagesUnexpectedMissingShelves" );
if ( !speiAE.FIsSet() || ( speiAE.PgnoFirst() < pgnoFirst ) || ( speiAE.PgnoLast() > pgnoLast ) )
{
break;
}
Call( ErrBTFlagDelete( pfucbAE, fDIRNoVersion | ( pfucbRoot->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
BTUp( pfucbAE );
pgno = speiAE.PgnoLast() + 1;
}
HandleError:
if ( pfucbAE != pfucbNil )
{
BTUp( pfucbAE );
BTClose( pfucbAE );
pfucbAE = pfucbNil;
}
return err;
}
class CPgnoFlagged
{
public:
CPgnoFlagged()
{
m_pgnoflagged = pgnoNull;
}
CPgnoFlagged( const PGNO pgno )
{
Assert( ( pgno & 0x80000000 ) == 0 );
m_pgnoflagged = pgno;
}
CPgnoFlagged( const CPgnoFlagged& pgnoflagged )
{
m_pgnoflagged = pgnoflagged.m_pgnoflagged;
}
PGNO Pgno() const
{
return ( m_pgnoflagged & 0x7FFFFFFF );
}
BOOL FFlagged() const
{
return ( ( m_pgnoflagged & 0x80000000 ) != 0 );
}
void SetFlagged()
{
Expected( !FFlagged() );
m_pgnoflagged = m_pgnoflagged | 0x80000000;
}
private:
PGNO m_pgnoflagged;
};
static_assert( sizeof( CPgnoFlagged ) == sizeof( PGNO ), "SizeOfCPgnoFlaggedMustBeEqualToSizeOfPgno." );
LOCAL ERR ErrErrArrayPgnoToJetErr( const CArray<CPgnoFlagged>::ERR err )
{
switch ( err )
{
case CArray<CPgnoFlagged>::ERR::errSuccess:
return JET_errSuccess;
case CArray<CPgnoFlagged>::ERR::errOutOfMemory:
return ErrERRCheck( JET_errOutOfMemory );
}
AssertSz( fFalse, "UnknownCArray<CPgnoFlagged>::ERR: %s", (int)err );
return ErrERRCheck( JET_errInternalError );
}
INT __cdecl PgnoShvdListCmpFunction( const CPgnoFlagged* ppgnoflagged1, const CPgnoFlagged* ppgnoflagged2 )
{
if ( ppgnoflagged1->Pgno() > ppgnoflagged2->Pgno() )
{
return 1;
}
if ( ppgnoflagged1->Pgno() < ppgnoflagged2->Pgno() )
{
return -1;
}
return 0;
}
LOCAL ERR ErrSPILRProcessObjectSpaceOwnershipSetPgnos(
_Inout_ CSparseBitmap* const pspbmOwned,
_Inout_ CArray<CPgnoFlagged>* const parrShelved,
_In_ const PGNO pgno,
_In_ const PGNO pgnoLast,
_In_ const BOOL fDbRoot,
_In_ const BOOL fAvailSpace,
_In_ const BOOL fMayAlreadyBeSet )
{
ERR err = JET_errSuccess;
Assert( !( fDbRoot && fMayAlreadyBeSet ) );
Assert( !( !fDbRoot && ( !fAvailSpace != !fMayAlreadyBeSet ) ) );
if ( pgno < 1 )
{
AssertTrack( fFalse, "LeakReclaimPgnoTooLow" );
Error( ErrERRCheck( fAvailSpace ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
if ( pgno <= pgnoLast )
{
const size_t iBit = pgno - 1;
BOOL fSet = fFalse;
if ( !fMayAlreadyBeSet )
{
Call( ErrErrBitmapToJetErr( pspbmOwned->ErrGet( iBit, &fSet ) ) );
if ( fSet )
{
AssertTrack( fFalse, "LeakReclaimPgnoDoubleBelowEof" );
Error( ErrERRCheck( fAvailSpace ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
}
if ( !fSet )
{
Call( ErrErrBitmapToJetErr( pspbmOwned->ErrSet( iBit, fTrue ) ) );
}
}
else
{
const size_t iEntry = parrShelved->SearchBinary( (CPgnoFlagged)pgno, PgnoShvdListCmpFunction );
if ( iEntry == CArray<CPgnoFlagged>::iEntryNotFound )
{
if ( fDbRoot && !fAvailSpace )
{
if ( ( parrShelved->Size() > 0 ) &&
( ( parrShelved->Entry( parrShelved->Size() - 1 ).Pgno() > pgno ) ) )
{
AssertTrack( fFalse, "LeakReclaimShelvedPagesOutOfOrder" );
Error( ErrERRCheck( fAvailSpace ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
if ( ( parrShelved->Size() + 1 ) > parrShelved->Capacity() )
{
Call( ErrErrArrayPgnoToJetErr( parrShelved->ErrSetCapacity( 2 * ( parrShelved->Size() + 1 ) ) ) );
}
Call( ErrErrArrayPgnoToJetErr( parrShelved->ErrSetEntry( parrShelved->Size(), (CPgnoFlagged)pgno ) ) );
}
else
{
AssertTrack( fFalse, "LeakReclaimUntrackedPgnoBeyondEof" );
Error( ErrERRCheck( fAvailSpace ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
}
else
{
if ( ( fDbRoot && fAvailSpace ) || ( !fDbRoot && ( !fAvailSpace || fMayAlreadyBeSet ) ) )
{
CPgnoFlagged pgnoflaggedFound = parrShelved->Entry( iEntry );
if ( !pgnoflaggedFound.FFlagged() )
{
pgnoflaggedFound.SetFlagged();
Call( ErrErrArrayPgnoToJetErr( parrShelved->ErrSetEntry( iEntry, pgnoflaggedFound ) ) );
}
else if ( !fMayAlreadyBeSet )
{
AssertTrack( fFalse, "LeakReclaimPgnoDoubleProcBeyondEof" );
Error( ErrERRCheck( fAvailSpace ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
}
else
{
AssertTrack( fFalse, "LeakReclaimPgnoDoubleShelvedBeyondEof" );
Error( ErrERRCheck( fAvailSpace ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
}
}
HandleError:
return err;
}
LOCAL ERR ErrSPILRProcessObjectSpaceOwnership(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const OBJID objid,
_Inout_ CSparseBitmap* const pspbmOwned,
_Inout_ CArray<CPgnoFlagged>* const parrShelved )
{
ERR err = JET_errSuccess;
PGNO pgnoFDP = pgnoNull;
PGNO pgnoFDPParentUnused = pgnoNull;
FCB* pfcb = pfcbNil;
FUCB* pfucb = pfucbNil;
FUCB* pfucbParentUnused = pfucbNil;
BOOL fSmallSpace = fFalse;
FUCB* pfucbSpace = pfucbNil;
const BOOL fDbRoot = ( objid == objidSystemRoot );
const OBJID objidParent = fDbRoot ? objidNil : objidSystemRoot;
const SYSOBJ sysobj = fDbRoot ? sysobjNil : sysobjTable ;
const PGNO pgnoLast = g_rgfmp[ifmp].PgnoLast();
Call( ErrCATGetCursorsFromObjid(
ppib,
ifmp,
objid,
objidParent,
sysobj,
&pgnoFDP,
&pgnoFDPParentUnused,
&pfucb,
&pfucbParentUnused ) );
pfcb = pfucb->u.pfcb;
fSmallSpace = FSPIIsSmall( pfcb );
if ( fDbRoot )
{
Assert( !fSmallSpace );
Call( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbSpace ) );
}
else
{
if ( !fSmallSpace )
{
Call( ErrSPIOpenOwnExt( ppib, pfcb, &pfucbSpace ) );
}
else
{
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
const SPACE_HEADER* const psph = PsphSPIRootPage( pfucb );
Assert( psph->FSingleExtent() );
const PGNO pgnoFirstSmallExt = PgnoFDP( pfucb );
const PGNO pgnoLastSmallExt = pgnoFirstSmallExt + psph->CpgPrimary() - 1;
for ( PGNO pgno = pgnoFirstSmallExt; pgno <= pgnoLastSmallExt; pgno++ )
{
Call( ErrSPILRProcessObjectSpaceOwnershipSetPgnos(
pspbmOwned,
parrShelved,
pgno,
pgnoLast,
fFalse,
fFalse,
fFalse ) );
}
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
}
}
Assert( !!fSmallSpace == ( pfucbSpace == pfucbNil ) );
if ( fSmallSpace )
{
goto HandleError;
}
Assert( !!pfucbSpace->fOwnExt ^ !!pfucbSpace->fAvailExt );
FUCBSetSequential( pfucbSpace );
FUCBSetPrereadForward( pfucbSpace, cpgPrereadSequential );
DIB dib;
dib.pos = posFirst;
dib.dirflag = fDIRNull;
err = ErrBTDown( pfucbSpace, &dib, latchReadTouch );
if ( err == JET_errRecordNotFound )
{
err = JET_errSuccess;
goto HandleError;
}
Call( err );
while ( err >= JET_errSuccess )
{
const CSPExtentInfo spext( pfucbSpace );
Call( spext.ErrCheckCorrupted() );
Assert( spext.FIsSet() );
if ( spext.CpgExtent() > 0 )
{
const SpacePool spp = spext.SppPool();
if ( !( ( pfucbSpace->fOwnExt && ( spp == spp::AvailExtLegacyGeneralPool ) ) ||
( pfucbSpace->fAvailExt && ( spp == spp::AvailExtLegacyGeneralPool ) ) ||
( pfucbSpace->fAvailExt && ( spp == spp::ContinuousPool ) ) ||
( pfucbSpace->fAvailExt && ( spp == spp::ShelvedPool ) ) ||
( !fDbRoot && ( spp == spp::ShelvedPool ) ) ) )
{
AssertTrack( fFalse, OSFormat( "LeakReclaimUnknownPool:%d:%d:%d", (int)fDbRoot, (int)pfucbSpace->fAvailExt, (int)spp ) );
Error( ErrERRCheck( pfucbSpace->fAvailExt ? JET_errSPAvailExtCorrupted : JET_errSPOwnExtCorrupted ) );
}
if ( ( spp == spp::ShelvedPool ) && ( spext.PgnoFirst() <= pgnoLast ) && ( spext.PgnoLast() > pgnoLast ) )
{
AssertTrack( fFalse, "LeakReclaimOverlappingShelvedExt" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( ( spp != spp::ShelvedPool ) || ( spext.PgnoFirst() > pgnoLast ) )
{
for ( PGNO pgno = spext.PgnoFirst(); pgno <= spext.PgnoLast(); pgno++ )
{
const BOOL fAvailSpace = pfucbSpace->fAvailExt && ( spp != spp::ShelvedPool );
Call( ErrSPILRProcessObjectSpaceOwnershipSetPgnos(
pspbmOwned,
parrShelved,
pgno,
pgnoLast,
fDbRoot,
fAvailSpace,
fFalse ) );
}
}
}
err = ErrBTNext( pfucbSpace, dib.dirflag );
if ( err == JET_errNoCurrentRecord )
{
err = JET_errSuccess;
goto HandleError;
}
}
Call( err );
if ( !fSmallSpace )
{
BTUp( pfucbSpace );
for ( int iSpaceTree = 1; iSpaceTree <= 2; iSpaceTree++ )
{
SPLIT_BUFFER* pspbuf = NULL;
Call( ErrBTIGotoRoot( pfucbSpace, latchRIW ) );
Call( ErrSPIGetSPBuf( pfucbSpace, &pspbuf ) );
if ( pspbuf->CpgBuffer1() > 0 )
{
for ( PGNO pgno = pspbuf->PgnoFirstBuffer1(); pgno <= pspbuf->PgnoLastBuffer1(); pgno++ )
{
Call( ErrSPILRProcessObjectSpaceOwnershipSetPgnos(
pspbmOwned,
parrShelved,
pgno,
pgnoLast,
fDbRoot,
fTrue,
!fDbRoot ) );
}
}
if ( pspbuf->CpgBuffer2() > 0 )
{
for ( PGNO pgno = pspbuf->PgnoFirstBuffer2(); pgno <= pspbuf->PgnoLastBuffer2(); pgno++ )
{
Call( ErrSPILRProcessObjectSpaceOwnershipSetPgnos(
pspbmOwned,
parrShelved,
pgno,
pgnoLast,
fDbRoot,
fTrue,
!fDbRoot ) );
}
}
const BOOL fAvailTree = pfucbSpace->fAvailExt;
BTUp( pfucbSpace );
BTClose( pfucbSpace );
pfucbSpace = pfucbNil;
if ( iSpaceTree == 1 )
{
if ( fAvailTree )
{
Call( ErrSPIOpenOwnExt( ppib, pfcb, &pfucbSpace ) );
}
else
{
Call( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbSpace ) );
}
}
}
}
err = JET_errSuccess;
HandleError:
if ( pfucb != pfucbNil )
{
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
}
if ( pfucbSpace != pfucbNil )
{
BTUp( pfucbSpace );
BTClose( pfucbSpace );
pfucbSpace = pfucbNil;
}
CATFreeCursorsFromObjid( pfucb, pfucbParentUnused );
pfucb = pfucbNil;
pfucbParentUnused = pfucbNil;
return err;
}
LOCAL ERR ErrSPILRProcessPotentiallyLeakedPage(
_In_ PIB* const ppib,
_In_ const IFMP ifmp,
_In_ const PGNO pgno,
_Inout_ CSparseBitmap* const pspbmOwned,
_Out_ BOOL* const pfLeaked )
{
ERR err = JET_errSuccess;
OBJID objid = objidNil;
SpaceCategoryFlags spcatf = spcatfNone;
SpaceCatCtx* pSpCatCtx = NULL;
BOOL fNotLeaked = fFalse;
*pfLeaked = fFalse;
Call( ErrErrBitmapToJetErr( pspbmOwned->ErrGet( pgno - 1, &fNotLeaked ) ) );
if ( fNotLeaked )
{
goto HandleError;
}
Call( ErrSPGetSpaceCategory(
ppib,
ifmp,
pgno,
objidSystemRoot,
fFalse,
&objid,
&spcatf,
&pSpCatCtx ) );
const BOOL fRootDb = ( ( pSpCatCtx != NULL ) && ( pSpCatCtx->pfucb != pfucbNil ) ) ?
( PgnoFDP( pSpCatCtx->pfucb ) == pgnoSystemRoot ) :
fFalse ;
*pfLeaked = FSPSpaceCatIndeterminate( spcatf );
if ( !(
*pfLeaked ||
(
fRootDb &&
(
FSPSpaceCatAnySpaceTree( spcatf ) ||
( !FSPSpaceCatAnySpaceTree( spcatf ) && FSPSpaceCatRoot( spcatf ) && ( pgno == pgnoSystemRoot ) )
)
) ||
(
!fRootDb && FSPSpaceCatAnySpaceTree( spcatf )
)
) )
{
AssertTrack( fFalse, OSFormat( "LeakReclaimUnexpectedCat:%d:%d", (int)fRootDb, (int)spcatf ) );
Error( ErrERRCheck( JET_errDatabaseCorrupted ) );
}
SPFreeSpaceCatCtx( &pSpCatCtx );
if ( !( *pfLeaked ) )
{
Call( ErrErrBitmapToJetErr( pspbmOwned->ErrSet( pgno - 1, fTrue ) ) );
}
HandleError:
SPFreeSpaceCatCtx( &pSpCatCtx );
return err;
}
typedef enum
{
lrdrNone,
lrdrCompleted,
lrdrFailed,
lrdrTimeout,
lrdrMSysObjIdsNotReady,
} LeakReclaimerDoneReason;
ERR ErrSPReclaimSpaceLeaks( PIB* const ppib, const IFMP ifmp )
{
ERR err = JET_errSuccess;
ERR errVerClean = JET_errSuccess;
LeakReclaimerDoneReason lrdr = lrdrNone;
FMP* const pfmp = g_rgfmp + ifmp;
pfmp->SetLeakReclaimerIsRunning();
const HRT hrtStarted = HrtHRTCount();
const LONG dtickQuota = pfmp->DtickLeakReclaimerTimeQuota();
BOOL fDbOpen = fFalse;
BOOL fInTransaction = fFalse;
PGNO pgnoFirstReclaimed = pgnoNull, pgnoLastReclaimed = pgnoNull;
CPG cpgReclaimed = 0, cpgShelved = -1;
PGNO pgnoLastInitial = pfmp->PgnoLast();
PGNO pgnoMaxToProcess = pgnoNull;
PGNO pgnoFirstShelved = pgnoNull, pgnoLastShelved = pgnoNull;
FUCB* pfucbCatalog = pfucbNil;
FUCB* pfucbRoot = pfucbNil;
CSparseBitmap spbmOwned;
CArray<CPgnoFlagged> arrShelved;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortSpace );
Assert( !pfmp->FIsTempDB() );
IFMP ifmpDummy;
Call( ErrDBOpenDatabase( ppib, pfmp->WszDatabaseName(), &ifmpDummy, JET_bitDbExclusive ) );
EnforceSz( pfmp->FExclusiveBySession( ppib ), "LeakReclaimDbNotExclusive" );
Assert( ifmpDummy == ifmp );
fDbOpen = fTrue;
{
BOOL fMSysObjidsReady = fFalse;
Call( ErrCATCheckMSObjidsReady( ppib, ifmp, &fMSysObjidsReady ) );
if ( !fMSysObjidsReady )
{
lrdr = lrdrMSysObjIdsNotReady;
err = JET_errSuccess;
goto HandleError;
}
}
errVerClean = PverFromPpib( ppib )->ErrVERRCEClean( ifmp );
if ( errVerClean != JET_errSuccess )
{
AssertTrack( fFalse, OSFormat( "LeakReclaimBeginVerCleanErr:%d", errVerClean ) );
Error( ErrERRCheck( JET_errDatabaseInUse ) );
}
pfmp->WaitForTasksToComplete();
if ( ( dtickQuota >= 0 ) && ( CmsecHRTFromHrtStart( hrtStarted ) >= (QWORD)dtickQuota ) )
{
lrdr = lrdrTimeout;
err = JET_errSuccess;
goto HandleError;
}
Call( ErrSPGetLastPgno( ppib, ifmp, &pgnoLastInitial ) );
EnforceSz( pgnoLastInitial == pfmp->PgnoLast(), "LeakReclaimPgnoLastMismatch" );
pgnoMaxToProcess = pgnoLastInitial;
Call( ErrErrBitmapToJetErr( spbmOwned.ErrInitBitmap( pgnoLastInitial ) ) );
Call( ErrSPILRProcessObjectSpaceOwnership( ppib, ifmp, objidSystemRoot, &spbmOwned, &arrShelved ) );
cpgShelved = arrShelved.Size();
if ( arrShelved.Size() > 0 )
{
pgnoFirstShelved = arrShelved.Entry( 0 ).Pgno();
pgnoLastShelved = arrShelved.Entry( arrShelved.Size() - 1 ).Pgno();
Assert( pgnoFirstShelved <= pgnoLastShelved );
Assert( pgnoLastShelved > pgnoMaxToProcess );
pgnoMaxToProcess = pgnoLastShelved;
}
if ( ( dtickQuota >= 0 ) && ( CmsecHRTFromHrtStart( hrtStarted ) >= (QWORD)dtickQuota ) )
{
lrdr = lrdrTimeout;
err = JET_errSuccess;
goto HandleError;
}
{
OBJID objid = objidNil;
for ( err = ErrCATGetNextRootObject( ppib, ifmp, &pfucbCatalog, &objid );
( err >= JET_errSuccess ) && ( objid != objidNil );
err = ErrCATGetNextRootObject( ppib, ifmp, &pfucbCatalog, &objid ) )
{
Call( ErrSPILRProcessObjectSpaceOwnership( ppib, ifmp, objid, &spbmOwned, &arrShelved ) );
if ( ( dtickQuota >= 0 ) && ( CmsecHRTFromHrtStart( hrtStarted ) >= (QWORD)dtickQuota ) )
{
lrdr = lrdrTimeout;
err = JET_errSuccess;
goto HandleError;
}
}
Call( err );
CallS( ErrCATClose( ppib, pfucbCatalog ) );
pfucbCatalog = pfucbNil;
}
EnforceSz( cpgShelved == arrShelved.Size(), "LeakReclaimExtraShelvedPagesBefore" );
EnforceSz( pgnoMaxToProcess < ulMax, "LeakReclaimPgnoMaxToProcessTooHigh" );
{
size_t iEntryShelvedFound = CArray<CPgnoFlagged>::iEntryNotFound;
for ( PGNO pgnoCurrent = 1; pgnoCurrent <= pgnoMaxToProcess; )
{
PGNO pgnoFirstToReclaim = pgnoNull;
while ( ( pgnoCurrent <= pgnoMaxToProcess ) && ( pgnoFirstToReclaim == pgnoNull ) )
{
BOOL fLeaked = fFalse;
if ( pgnoCurrent <= pgnoLastInitial )
{
Assert( iEntryShelvedFound == CArray<CPgnoFlagged>::iEntryNotFound );
Call( ErrSPILRProcessPotentiallyLeakedPage( ppib, ifmp, pgnoCurrent, &spbmOwned, &fLeaked ) );
}
else
{
const BOOL fFirstShelvedSeen = ( iEntryShelvedFound == CArray<CPgnoFlagged>::iEntryNotFound );
iEntryShelvedFound = fFirstShelvedSeen ? 0 : ( iEntryShelvedFound + 1 );
EnforceSz( arrShelved.Size() > 0, "LeakReclaimShelvedListEmpty" );
EnforceSz( arrShelved.Size() > iEntryShelvedFound, "LeakReclaimShelvedListTooLow" );
const CPgnoFlagged pgnoFlagged = arrShelved.Entry( iEntryShelvedFound );
EnforceSz( ( pgnoFlagged.Pgno() >= pgnoCurrent ) || fFirstShelvedSeen, "LeakReclaimPgnoCurrentGoesBack" );
pgnoCurrent = pgnoFlagged.Pgno();
fLeaked = !pgnoFlagged.FFlagged();
}
if ( fLeaked )
{
pgnoFirstToReclaim = pgnoCurrent;
}
pgnoCurrent++;
}
EnforceSz( cpgShelved == arrShelved.Size(), "LeakReclaimExtraShelvedPagesFirst" );
if ( pgnoFirstToReclaim == pgnoNull )
{
err = JET_errSuccess;
goto HandleError;
}
PGNO pgnoMaxToReclaim = pgnoMaxToProcess;
if ( pgnoFirstToReclaim <= pfmp->PgnoLast() )
{
Call( ErrDIRBeginTransaction( ppib, 37218, NO_GRBIT ) );
fInTransaction = fTrue;
Call( ErrDIROpen( ppib, pgnoSystemRoot, ifmp, &pfucbRoot ) );
CSPExtentInfo spext;
err = ErrSPIFindExtOE( ppib, pfucbRoot->u.pfcb, pgnoFirstToReclaim, &spext );
if ( ( err == JET_errNoCurrentRecord ) ||
( err == JET_errRecordNotFound ) ||
( ( err >= JET_errSuccess ) &&
( !spext.FIsSet() || ( spext.PgnoFirst() > pgnoFirstToReclaim ) ) ) )
{
AssertTrack( fFalse, "LeakReclaimOeGap" );
Error( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
Call( err );
err = JET_errSuccess;
pgnoMaxToReclaim = UlFunctionalMin( pgnoMaxToReclaim, spext.PgnoLast() );
EnforceSz( pgnoMaxToReclaim >= pgnoFirstToReclaim, "LeakReclaimPgnoMaxToReclaimTooLow" );
DIRClose( pfucbRoot );
pfucbRoot = pfucbNil;
Call( ErrDIRCommitTransaction( ppib, NO_GRBIT ) );
fInTransaction = fFalse;
}
EnforceSz( pgnoCurrent == ( pgnoFirstToReclaim + 1 ), "LeakReclaimPgnoCurrentMisplacedFirst" );
PGNO pgnoLastToReclaim = pgnoFirstToReclaim;
while ( pgnoCurrent <= pgnoMaxToReclaim )
{
BOOL fLeaked = fFalse;
if ( pgnoCurrent <= pgnoLastInitial )
{
Assert( pgnoFirstToReclaim <= pgnoLastInitial );
Assert( iEntryShelvedFound == CArray<CPgnoFlagged>::iEntryNotFound );
Call( ErrSPILRProcessPotentiallyLeakedPage( ppib, ifmp, pgnoCurrent, &spbmOwned, &fLeaked ) );
}
else
{
Assert( pgnoFirstToReclaim > pgnoLastInitial );
Assert( iEntryShelvedFound != CArray<CPgnoFlagged>::iEntryNotFound );
const size_t iEntryShelvedFoundT = ( iEntryShelvedFound == CArray<CPgnoFlagged>::iEntryNotFound ) ? 0 : ( iEntryShelvedFound + 1 );
if ( arrShelved.Size() > iEntryShelvedFoundT )
{
const CPgnoFlagged pgnoFlagged = arrShelved.Entry( iEntryShelvedFoundT );
fLeaked = ( ( pgnoFlagged.Pgno() == ( pgnoLastToReclaim + 1 ) ) && !pgnoFlagged.FFlagged() );
if ( fLeaked )
{
Assert( pgnoCurrent == pgnoFlagged.Pgno() );
iEntryShelvedFound = iEntryShelvedFoundT;
}
}
else
{
fLeaked = fFalse;
}
}
if ( fLeaked )
{
Assert( pgnoLastToReclaim == ( pgnoCurrent - 1 ) );
pgnoLastToReclaim = pgnoCurrent;
pgnoCurrent++;
}
else
{
break;
}
}
EnforceSz( cpgShelved == arrShelved.Size(), "LeakReclaimExtraShelvedPagesLast" );
EnforceSz( pgnoCurrent == ( pgnoLastToReclaim + 1 ), "LeakReclaimPgnoCurrentMisplacedLast" );
EnforceSz( pgnoFirstToReclaim >= 1, "LeakReclaimPgnoFirstToReclaimTooLow" );
EnforceSz( pgnoLastToReclaim >= 1, "LeakReclaimPgnoLastToReclaimTooLow" );
EnforceSz( pgnoFirstToReclaim <= pgnoLastToReclaim, "LeakReclaimInvalidReclaimRange" );
EnforceSz( pgnoLastToReclaim <= pgnoMaxToProcess, "LeakReclaimPgnoLastToReclaimTooHighMaxToProcess" );
EnforceSz( pgnoLastToReclaim <= pgnoMaxToReclaim, "LeakReclaimPgnoLastToReclaimTooHighMaxToReclaim" );
EnforceSz( ( ( pgnoFirstToReclaim <= pgnoLastInitial ) && ( pgnoLastToReclaim <= pgnoLastInitial ) ) ||
( ( pgnoFirstToReclaim > pgnoLastInitial ) && ( pgnoLastToReclaim > pgnoLastInitial ) ),
"LeakReclaimRangeOverlapsInitialPgnoLast" );
for ( PGNO pgnoToReclaim = pgnoFirstToReclaim; pgnoToReclaim <= pgnoLastToReclaim; pgnoToReclaim++ )
{
BOOL fNotLeaked = fTrue;
if ( pgnoToReclaim <= pgnoLastInitial )
{
Call( ErrErrBitmapToJetErr( spbmOwned.ErrGet( pgnoToReclaim - 1, &fNotLeaked ) ) );
}
else
{
const size_t iEntry = arrShelved.SearchBinary( (CPgnoFlagged)pgnoToReclaim, PgnoShvdListCmpFunction );
if ( iEntry == CArray<CPgnoFlagged>::iEntryNotFound )
{
fNotLeaked = fTrue;
}
else
{
const CPgnoFlagged pgnoflaggedFound = arrShelved.Entry( iEntry );
fNotLeaked = pgnoflaggedFound.FFlagged();
}
}
EnforceSz( !fNotLeaked, "LeakReclaimRangeNotFullyLeaked" );
}
const CPG cpgToReclaim = pgnoLastToReclaim - pgnoFirstToReclaim + 1;
Call( ErrDIRBeginTransaction( ppib, 51150, NO_GRBIT ) );
fInTransaction = fTrue;
Call( ErrDIROpen( ppib, pgnoSystemRoot, ifmp, &pfucbRoot ) );
const PGNO pgnoLastToReclaimBelowEof = UlFunctionalMin( pgnoLastToReclaim, pgnoLastInitial );
if ( pgnoFirstToReclaim <= pgnoLastInitial )
{
Assert( pgnoLastToReclaimBelowEof >= pgnoFirstToReclaim );
Call( ErrSPCaptureSnapshot( pfucbRoot, pgnoFirstToReclaim, pgnoLastToReclaimBelowEof - pgnoFirstToReclaim + 1 ) );
}
Call( ErrSPFreeExt( pfucbRoot, pgnoFirstToReclaim, cpgToReclaim, "LeakReclaimer" ) );
cpgReclaimed += cpgToReclaim;
if ( pgnoFirstReclaimed == pgnoNull )
{
pgnoFirstReclaimed = pgnoFirstToReclaim;
}
pgnoLastReclaimed = pgnoLastToReclaim;
DIRClose( pfucbRoot );
pfucbRoot = pfucbNil;
Call( ErrDIRCommitTransaction( ppib, NO_GRBIT ) );
fInTransaction = fFalse;
for ( PGNO pgno = pgnoFirstToReclaim; pgno <= pgnoLastToReclaimBelowEof; pgno++ )
{
BFMarkAsSuperCold( ifmp, pgno );
}
if ( ( dtickQuota >= 0 ) && ( CmsecHRTFromHrtStart( hrtStarted ) >= (QWORD)dtickQuota ) )
{
lrdr = lrdrTimeout;
err = JET_errSuccess;
goto HandleError;
}
}
}
err = JET_errSuccess;
HandleError:
if ( lrdr == lrdrNone )
{
lrdr = ( err >= JET_errSuccess ? lrdrCompleted : lrdrFailed );
}
if ( pfucbCatalog != pfucbNil )
{
CallS( ErrCATClose( ppib, pfucbCatalog ) );
pfucbCatalog = pfucbNil;
}
if ( pfucbRoot != pfucbNil )
{
DIRClose( pfucbRoot );
pfucbRoot = pfucbNil;
}
if ( fInTransaction )
{
if ( err >= JET_errSuccess )
{
fInTransaction = ( ErrDIRCommitTransaction( ppib, NO_GRBIT ) < JET_errSuccess );
}
if ( fInTransaction )
{
CallSx( ErrDIRRollback( ppib ), JET_errRollbackError );
fInTransaction = fFalse;
}
}
errVerClean = PverFromPpib( ppib )->ErrVERRCEClean( ifmp );
if ( errVerClean != JET_errSuccess )
{
AssertTrack( fFalse, OSFormat( "LeakReclaimEndVerCleanErr:%d", errVerClean ) );
if ( errVerClean > JET_errSuccess )
{
errVerClean = ErrERRCheck( JET_errDatabaseInUse );
}
}
else
{
pfmp->WaitForTasksToComplete();
FCB::PurgeDatabase( ifmp, fFalse );
}
Assert( errVerClean <= JET_errSuccess );
if ( ( err >= JET_errSuccess ) && ( errVerClean < JET_errSuccess ) )
{
err = errVerClean;
}
if ( fDbOpen )
{
Assert( pfmp->FExclusiveBySession( ppib ) );
CallS( ErrDBCloseDatabase( ppib, ifmp, NO_GRBIT ) );
fDbOpen = fFalse;
}
pfmp->ResetLeakReclaimerIsRunning();
OSTraceSuspendGC();
const HRT dhrtElapsed = DhrtHRTElapsedFromHrtStart( hrtStarted );
const double dblSecTotalElapsed = DblHRTSecondsElapsed( dhrtElapsed );
const DWORD dwMinElapsed = (DWORD)( dblSecTotalElapsed / 60.0 );
const double dblSecElapsed = dblSecTotalElapsed - (double)dwMinElapsed * 60.0;
const WCHAR* rgwsz[] =
{
pfmp->WszDatabaseName(),
OSFormatW( L"%d", (int)lrdr ),
OSFormatW( L"%I32u", dwMinElapsed ), OSFormatW( L"%.2f", dblSecElapsed ),
OSFormatW( L"%d", err ),
OSFormatW( L"%I64u", pfmp->CbOfCpg( (CPG)pgnoLastInitial ) ), OSFormatW( L"%I32d", (CPG)pgnoLastInitial ),
OSFormatW( L"%I64u", pfmp->CbOfCpg( (CPG)pfmp->PgnoLast() ) ), OSFormatW( L"%I32d", (CPG)pfmp->PgnoLast() ),
OSFormatW( L"%I32d", cpgReclaimed ),
( pgnoFirstReclaimed != pgnoNull ) ? OSFormatW( L"%I32u", pgnoFirstReclaimed ) : L"-",
( pgnoLastReclaimed != pgnoNull ) ? OSFormatW( L"%I32u", pgnoLastReclaimed ) : L"-",
( cpgShelved != -1 ) ? OSFormatW( L"%I32d", cpgShelved ) : L"-",
( pgnoFirstShelved != pgnoNull ) ? OSFormatW( L"%I32u", pgnoFirstShelved ) : L"-",
( pgnoLastShelved != pgnoNull ) ? OSFormatW( L"%I32u", pgnoLastShelved ) : L"-",
};
UtilReportEvent(
( err < JET_errSuccess ) ? eventError : eventInformation,
GENERAL_CATEGORY,
( err < JET_errSuccess ) ? DB_LEAK_RECLAIMER_FAILED_ID : DB_LEAK_RECLAIMER_SUCCEEDED_ID,
_countof( rgwsz ),
rgwsz,
0,
NULL,
pfmp->Pinst() );
OSTraceResumeGC();
return err;
}
const ULONG cOEListEntriesInit = 32;
const ULONG cOEListEntriesMax = 127;
class OWNEXT_LIST
{
public:
OWNEXT_LIST( OWNEXT_LIST **ppOEListHead );
~OWNEXT_LIST();
public:
EXTENTINFO *RgExtentInfo() { return m_extentinfo; }
ULONG CEntries() const;
OWNEXT_LIST *POEListNext() const { return m_pOEListNext; }
VOID AddExtentInfoEntry( const PGNO pgnoLast, const CPG cpgSize );
private:
EXTENTINFO m_extentinfo[cOEListEntriesMax];
ULONG m_centries;
OWNEXT_LIST *m_pOEListNext;
};
INLINE OWNEXT_LIST::OWNEXT_LIST( OWNEXT_LIST **ppOEListHead )
{
m_centries = 0;
m_pOEListNext = *ppOEListHead;
*ppOEListHead = this;
}
INLINE ULONG OWNEXT_LIST::CEntries() const
{
Assert( m_centries <= cOEListEntriesMax );
return m_centries;
}
INLINE VOID OWNEXT_LIST::AddExtentInfoEntry(
const PGNO pgnoLast,
const CPG cpgSize )
{
Assert( m_centries < cOEListEntriesMax );
m_extentinfo[m_centries].pgnoLastInExtent = pgnoLast;
m_extentinfo[m_centries].cpgExtent = cpgSize;
m_centries++;
}
INLINE ERR ErrSPIFreeOwnedExtentsInList(
FUCB *pfucbParent,
EXTENTINFO *rgextinfo,
const ULONG cExtents )
{
ERR err;
for ( size_t i = 0; i < cExtents; i++ )
{
const CPG cpgSize = rgextinfo[i].CpgExtent();
const PGNO pgnoFirst = rgextinfo[i].PgnoLast() - cpgSize + 1;
Assert( !FFUCBSpace( pfucbParent ) );
CallR( ErrSPCaptureSnapshot( pfucbParent, pgnoFirst, cpgSize ) );
CallR( ErrSPFreeExt( pfucbParent, pgnoFirst, cpgSize, "FreeFdpLarge" ) );
}
return JET_errSuccess;
}
LOCAL ERR ErrSPIFreeAllOwnedExtents( FUCB *pfucbParent, FCB *pfcb, const BOOL fPreservePrimaryExtent )
{
ERR err;
FUCB *pfucbOE;
DIB dib;
PGNO pgnoLastPrev;
ULONG cExtents = 0;
CPG cpgOwned = 0;
Assert( pfcb != pfcbNil );
CallR( ErrSPIOpenOwnExt( pfucbParent->ppib, pfcb, &pfucbOE ) );
dib.pos = posFirst;
dib.dirflag = fDIRNull;
if ( ( err = ErrBTDown( pfucbOE, &dib, latchReadTouch ) ) < 0 )
{
BTClose( pfucbOE );
return err;
}
Assert( wrnNDFoundLess != err );
Assert( wrnNDFoundGreater != err );
EXTENTINFO extinfo[cOEListEntriesInit];
OWNEXT_LIST *pOEList = NULL;
OWNEXT_LIST *pOEListCurr = NULL;
ULONG cOEListEntries = 0;
pgnoLastPrev = 0;
do
{
const CSPExtentInfo spOwnedExt( pfucbOE );
CallS( spOwnedExt.ErrCheckCorrupted() );
if ( pgnoLastPrev > ( spOwnedExt.PgnoFirst() - 1 ) )
{
AssertSzRTL( fFalse, "OwnExt nodes are not in monotonically-increasing key order." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbOE ), HaDbFailureTagCorruption, L"eb31e6ec-553f-4ac9-b2f6-2561ae325954" );
Call( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
pgnoLastPrev = spOwnedExt.PgnoLast();
cExtents++;
cpgOwned += spOwnedExt.CpgExtent();
if ( !fPreservePrimaryExtent
|| ( pfcb->PgnoFDP() != spOwnedExt.PgnoFirst() ) )
{
if ( cOEListEntries < cOEListEntriesInit )
{
extinfo[cOEListEntries].pgnoLastInExtent = spOwnedExt.PgnoLast();
extinfo[cOEListEntries].cpgExtent = spOwnedExt.CpgExtent();
}
else
{
Assert( ( NULL == pOEListCurr && NULL == pOEList )
|| ( NULL != pOEListCurr && NULL != pOEList ) );
if ( NULL == pOEListCurr || pOEListCurr->CEntries() == cOEListEntriesMax )
{
pOEListCurr = (OWNEXT_LIST *)PvOSMemoryHeapAlloc( sizeof( OWNEXT_LIST ) );
if ( NULL == pOEListCurr )
{
Assert( pfucbNil != pfucbOE );
BTClose( pfucbOE );
err = ErrERRCheck( JET_errOutOfMemory );
goto HandleError;
}
new( pOEListCurr ) OWNEXT_LIST( &pOEList );
Assert( pOEList == pOEListCurr );
}
pOEListCurr->AddExtentInfoEntry( spOwnedExt.PgnoLast(), spOwnedExt.CpgExtent() );
}
cOEListEntries++;
}
err = ErrBTNext( pfucbOE, fDIRNull );
}
while ( err >= 0 );
OSTraceFMP( pfucbOE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Free FDP with %08d owned pages and %08d owned extents [objid:0x%x,pgnoFDP:0x%x,ifmp=0x%x]\n",
cpgOwned, cExtents, pfcb->ObjidFDP(), pfcb->PgnoFDP(), pfucbOE->ifmp ) );
Assert( pfucbNil != pfucbOE );
BTClose( pfucbOE );
if ( err != JET_errNoCurrentRecord )
{
Assert( err < 0 );
goto HandleError;
}
Call( ErrSPIFreeOwnedExtentsInList(
pfucbParent,
extinfo,
min( cOEListEntries, cOEListEntriesInit ) ) );
for ( pOEListCurr = pOEList;
pOEListCurr != NULL;
pOEListCurr = pOEListCurr->POEListNext() )
{
Assert( cOEListEntries > cOEListEntriesInit );
Call( ErrSPIFreeOwnedExtentsInList(
pfucbParent,
pOEListCurr->RgExtentInfo(),
pOEListCurr->CEntries() ) );
}
PERFOpt( cSPDeletedTreeFreedPages.Add( PinstFromPfucb( pfucbParent ), cpgOwned ) );
PERFOpt( cSPDeletedTreeFreedExtents.Add( PinstFromPfucb( pfucbParent ), cExtents ) );
HandleError:
pOEListCurr = pOEList;
while ( pOEListCurr != NULL )
{
OWNEXT_LIST *pOEListKill = pOEListCurr;
#ifdef DEBUG
Assert( cOEListEntries > cOEListEntriesInit );
Assert( cOEListEntries > pOEListCurr->CEntries() );
cOEListEntries -= pOEListCurr->CEntries();
#endif
pOEListCurr = pOEListCurr->POEListNext();
OSMemoryHeapFree( pOEListKill );
}
Assert( cOEListEntries <= cOEListEntriesInit );
return err;
}
LOCAL ERR ErrSPIReportAEsFreedWithFDP( PIB * const ppib, FCB * const pfcb )
{
ERR err;
FUCB *pfucbAE;
DIB dib;
ULONG cExtents = 0;
CPG cpgFree = 0;
Assert( pfcb != pfcbNil );
CallR( ErrSPIOpenAvailExt( ppib, pfcb, &pfucbAE ) );
dib.pos = posFirst;
dib.dirflag = fDIRNull;
err = ErrBTDown( pfucbAE, &dib, latchReadTouch );
Assert( wrnNDFoundLess != err );
Assert( wrnNDFoundGreater != err );
if ( err == JET_errRecordNotFound )
{
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Free FDP with 0 avail pages [objid:0x%x,pgnoFDP:0x%x,ifmp=0x%x]\n",
pfcb->ObjidFDP(), pfcb->PgnoFDP(), pfucbAE->ifmp ) );
err = JET_errSuccess;
goto HandleError;
}
do
{
Call( err );
const CSPExtentInfo spavailext( pfucbAE );
cExtents++;
cpgFree += spavailext.CpgExtent();
err = ErrBTNext( pfucbAE, fDIRNull );
}
while ( JET_errNoCurrentRecord != err );
err = JET_errSuccess;
OSTraceFMP( pfucbAE->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Free FDP with %08d avail pages and %08u avail extents [objid:0x%x,pgnoFDP:0x%x,ifmp=0x%x]\n",
cpgFree, cExtents, pfcb->ObjidFDP(), pfcb->PgnoFDP(), pfucbAE->ifmp ) );
HandleError:
Assert( pfucbNil != pfucbAE );
BTClose( pfucbAE );
return err;
}
ERR ErrSPFreeFDP(
PIB *ppib,
FCB *pfcbFDPToFree,
const PGNO pgnoFDPParent,
const BOOL fPreservePrimaryExtent )
{
ERR err;
const IFMP ifmp = pfcbFDPToFree->Ifmp();
const PGNO pgnoFDPFree = pfcbFDPToFree->PgnoFDP();
FUCB *pfucbParent = pfucbNil;
FUCB *pfucb = pfucbNil;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->nParentObjectClass = pfcbFDPToFree->TCE( fTrue );
tcScope->SetDwEngineObjid( pfcbFDPToFree->ObjidFDP() );
tcScope->iorReason.SetIort( iortSpace );
BOOL fBeginTrx = fFalse;
if ( ppib->Level() == 0 )
{
CallR( ErrDIRBeginTransaction( ppib, 47141, NO_GRBIT ) );
fBeginTrx = fTrue;
}
Assert( pgnoNull != pgnoFDPParent );
Assert( pgnoNull != pgnoFDPFree );
Assert( !FFMPIsTempDB( ifmp ) || pgnoSystemRoot == pgnoFDPParent );
Call( ErrBTOpen( ppib, pgnoFDPParent, ifmp, &pfucbParent ) );
Assert( pfucbNil != pfucbParent );
Assert( pfucbParent->u.pfcb->FInitialized() );
#ifdef SPACECHECK
CallS( ErrSPIValidFDP( ppib, pfucbParent->ifmp, pgnoFDPFree ) );
#endif
OSTraceFMP( pfucbParent->ifmp, JET_tracetagSpaceManagement,
OSFormat( "free space FDP at %d.%lu\n", pfucbParent->ifmp, pgnoFDPFree ) );
Call( ErrBTOpen( ppib, pfcbFDPToFree, &pfucb ) );
Assert( pfucbNil != pfucb );
Assert( pfucb->u.pfcb->FInitialized() );
Assert( pfucb->u.pfcb->FDeleteCommitted() );
FUCBSetIndex( pfucb );
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
#ifdef SPACECHECK
CallS( ErrSPIWasAlloc( pfucb, pgnoFDPFree, 1 ) );
#endif
Assert( pgnoFDPParent == PgnoSPIParentFDP( pfucb ) );
Assert( pgnoFDPParent == PgnoFDP( pfucbParent ) );
if ( !pfucb->u.pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucb, fTrue );
}
if ( FSPIIsSmall( pfucb->u.pfcb ) )
{
if ( !fPreservePrimaryExtent )
{
AssertSPIPfucbOnRoot( pfucb );
NDGetExternalHeader( pfucb, pfucb->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
const SPACE_HEADER * const psph = reinterpret_cast <SPACE_HEADER *> ( pfucb->kdfCurr.data.Pv() );
ULONG cpgPrimary = psph->CpgPrimary();
Assert( psph->CpgPrimary() != 0 );
pfucb->pcsrRoot = pcsrNil;
BTClose( pfucb );
pfucb = pfucbNil;
Assert( !FFUCBSpace( pfucbParent ) );
Call( ErrSPCaptureSnapshot( pfucbParent, pgnoFDPFree, cpgPrimary ) );
Call( ErrSPFreeExt( pfucbParent, pgnoFDPFree, cpgPrimary, "FreeFdpSmall" ) );
PERFOpt( cSPDeletedTreeFreedPages.Add( PinstFromPfucb( pfucbParent ), cpgPrimary ) );
PERFOpt( cSPDeletedTreeFreedExtents.Inc( PinstFromPfucb( pfucbParent ) ) );
}
}
else
{
FCB *pfcb = pfucb->u.pfcb;
pfucb->pcsrRoot = pcsrNil;
BTClose( pfucb );
pfucb = pfucbNil;
if ( FOSTraceTagEnabled( JET_tracetagSpaceInternal ) &&
FFMPIsTempDB( pfucbParent->ifmp ) )
{
Call( ErrSPIReportAEsFreedWithFDP( ppib, pfcb ) );
}
Call( ErrSPIFreeAllOwnedExtents( pfucbParent, pfcb, fPreservePrimaryExtent ) );
Assert( !Pcsr( pfucbParent )->FLatched() );
}
PERFOpt( cSPDeletedTrees.Inc( PinstFromPfucb( pfucbParent ) ) );
HandleError:
if ( pfucbNil != pfucb )
{
pfucb->pcsrRoot = pcsrNil;
BTClose( pfucb );
}
if ( pfucbNil != pfucbParent )
{
BTClose( pfucbParent );
}
if ( fBeginTrx )
{
if ( err >= 0 )
{
err = ErrDIRCommitTransaction( ppib, JET_bitCommitLazyFlush );
}
if ( err < 0 )
{
CallSx( ErrDIRRollback( ppib ), JET_errRollbackError );
}
}
#ifdef DEBUG
if ( !FSPExpectedError( err ) )
{
CallS( err );
AssertSz( fFalse, ( !FFMPIsTempDB( ifmp ) ?
"Space potentially lost permanently in user database." :
"Space potentially lost in temporary database." ) );
}
#endif
return err;
}
INLINE ERR ErrSPIAddExtent(
__inout FUCB *pfucb,
__in const CSPExtentNodeKDF * const pcspextnode )
{
ERR err;
Assert( FFUCBSpace( pfucb ) );
Assert( !Pcsr( pfucb )->FLatched() );
Assert( pcspextnode->CpgExtent() > 0 );
Assert( pcspextnode->FValid() );
const KEY key = pcspextnode->GetKey();
const DATA data = pcspextnode->GetData();
BTUp( pfucb );
Call( ErrBTInsert(
pfucb,
key,
data,
fDIRNoVersion | ( pfucb->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Assert( Pcsr( pfucb )->FLatched() );
Assert( pfucb->fOwnExt || pfucb->fAvailExt );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceManagement,
OSFormat( "ErrSPIAddExtent: Add %lu + %d pages to 0x%x.%lu %hs.",
pcspextnode->PgnoFirst(),
pcspextnode->CpgExtent(),
pfucb->ifmp,
PgnoFDP( pfucb ),
pfucb->fOwnExt ? "OE" : "AE" ) );
HandleError:
Assert( errSPOutOfOwnExtCacheSpace != err );
Assert( errSPOutOfAvailExtCacheSpace != err );
return err;
}
LOCAL ERR ErrSPIAddToAvailExt(
__in FUCB * pfucbAE,
__in const PGNO pgnoAELast,
__in const CPG cpgAESize,
__in SpacePool sppPool )
{
ERR err;
FCB * const pfcb = pfucbAE->u.pfcb;
const CSPExtentNodeKDF cspaei( SPEXTKEY::fSPExtentTypeAE, pgnoAELast, cpgAESize, sppPool );
Assert( FFUCBAvailExt( pfucbAE ) );
err = ErrSPIAddExtent( pfucbAE, &cspaei );
if ( err < 0 )
{
if ( JET_errKeyDuplicate == err )
{
AssertSz( fFalse, "This is a bad thing, please show to ESE developers - likely explanation is the code around the ErrBTReplace() in ErrSPIAEFreeExt() is not taking care of insertion regions." );
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"917f5355-a040-4919-9503-81a9bdbcaa16" );
err = ErrERRCheck( JET_errSPAvailExtCorrupted );
}
}
else if ( ( sppPool != spp::ShelvedPool ) &&
( cspaei.CpgExtent() >= cpageSEDefault ) &&
( pgnoNull != pfcb->PgnoNextAvailSE() ) &&
( cspaei.PgnoFirst() < pfcb->PgnoNextAvailSE() ) )
{
pfcb->SetPgnoNextAvailSE( cspaei.PgnoFirst() );
}
return err;
}
LOCAL ERR ErrSPIAddToOwnExt(
FUCB *pfucb,
const PGNO pgnoOELast,
CPG cpgOESize,
CPG *pcpgCoalesced )
{
ERR err;
FUCB *pfucbOE;
CallR( ErrSPIOpenOwnExt( pfucb->ppib, pfucb->u.pfcb, &pfucbOE ) );
Assert( FFUCBOwnExt( pfucbOE ) );
if ( NULL != pcpgCoalesced && FFMPIsTempDB( pfucb->ifmp ) )
{
DIB dib;
const CSPExtentKeyBM spPgnoBeforeFirst( SPEXTKEY::fSPExtentTypeOE, pgnoOELast - cpgOESize );
dib.pos = posDown;
dib.pbm = spPgnoBeforeFirst.Pbm( pfucbOE );
dib.dirflag = fDIRExact;
err = ErrBTDown( pfucbOE, &dib, latchReadTouch );
if ( JET_errRecordNotFound == err )
{
err = JET_errSuccess;
}
else if ( JET_errSuccess == err )
{
CSPExtentInfo spextToCoallesce( pfucbOE );
Assert( spextToCoallesce.PgnoLast() == pgnoOELast - cpgOESize );
err = spextToCoallesce.ErrCheckCorrupted();
if ( err < JET_errSuccess )
{
OSUHAEmitFailureTag( PinstFromPfucb( pfucbOE ), HaDbFailureTagCorruption, L"4441dbd5-f6ff-4314-9315-efe96362f0a2" );
}
Call( err );
Assert( spextToCoallesce.CpgExtent() > 0 );
Call( ErrBTFlagDelete(
pfucbOE,
fDIRNoVersion | ( pfucbOE->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Assert( NULL != pcpgCoalesced );
*pcpgCoalesced = spextToCoallesce.CpgExtent();
cpgOESize += spextToCoallesce.CpgExtent();
}
else
{
Call( err );
}
BTUp( pfucbOE );
}
if( pgnoSystemRoot == pfucb->u.pfcb->PgnoFDP() )
{
QWORD cbFsFileSize = 0;
if ( g_rgfmp[pfucb->ifmp].Pfapi()->ErrSize( &cbFsFileSize, IFileAPI::filesizeLogical ) >= JET_errSuccess )
{
AssertTrack( CbFileSizeOfPgnoLast( pgnoOELast ) <= cbFsFileSize, "RootPgnoOeLastBeyondEof" );
}
}
{
const CSPExtentNodeKDF cspextnode( SPEXTKEY::fSPExtentTypeOE, pgnoOELast, cpgOESize );
Call( ErrSPIAddExtent( pfucbOE, &cspextnode ) );
}
HandleError:
Assert( errSPOutOfOwnExtCacheSpace != err );
Assert( errSPOutOfAvailExtCacheSpace != err );
pfucbOE->pcsrRoot = pcsrNil;
BTClose( pfucbOE );
return err;
}
LOCAL ERR ErrSPICoalesceAvailExt(
FUCB *pfucbAE,
const PGNO pgnoLast,
const CPG cpgSize,
CPG *pcpgCoalesce )
{
ERR err;
DIB dib;
Assert( FFMPIsTempDB( pfucbAE->ifmp ) );
*pcpgCoalesce = 0;
CSPExtentKeyBM spavailextSeek( SPEXTKEY::fSPExtentTypeAE, pgnoLast - cpgSize, spp::AvailExtLegacyGeneralPool );
dib.pos = posDown;
dib.pbm = spavailextSeek.Pbm( pfucbAE );
dib.dirflag = fDIRNull;
err = ErrBTDown( pfucbAE, &dib, latchReadTouch );
if ( JET_errRecordNotFound == err )
{
err = JET_errSuccess;
}
else if ( JET_errSuccess == err )
{
const CSPExtentInfo spavailext( pfucbAE );
#ifdef DEBUG
Assert( spavailext.PgnoLast() == pgnoLast - cpgSize );
#endif
err = spavailext.ErrCheckCorrupted();
if ( err < JET_errSuccess )
{
OSUHAEmitFailureTag( PinstFromPfucb( pfucbAE ), HaDbFailureTagCorruption, L"9f63b812-97ed-46ce-b40d-3a05a844351b" );
}
Call( err );
*pcpgCoalesce = spavailext.CpgExtent();
err = ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfucbAE->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) );
}
HandleError:
BTUp( pfucbAE );
return err;
}
LOCAL ERR ErrSPIAddSecondaryExtent(
__in FUCB* const pfucb,
__in FUCB* const pfucbAE,
__in const PGNO pgnoLast,
__in CPG cpgNewSpace,
__in CPG cpgAvailable,
__in CArray<EXTENTINFO>* const parreiReleased,
__in const SpacePool sppPool )
{
ERR err;
CPG cpgOECoalesced = 0;
const BOOL fRootDB = ( pfucb->u.pfcb->PgnoFDP() == pgnoSystemRoot );
BOOL fAddedToOwnExt = fFalse;
BOOL fAddedToAvailExt = fFalse;
Assert( cpgNewSpace > 0 );
Assert( cpgAvailable > 0 );
Assert( ( cpgNewSpace == cpgAvailable ) ||
( fRootDB && ( cpgNewSpace > cpgAvailable ) ) );
Assert( ( parreiReleased == NULL ) || ( parreiReleased->Size() == 0 ) ||
( fRootDB && ( cpgNewSpace > cpgAvailable ) ) );
Assert( ( cpgNewSpace == cpgAvailable ) ||
( ( cpgNewSpace > cpgAvailable ) && !g_rgfmp[pfucb->ifmp].FIsTempDB() ) );
Assert( sppPool != spp::ShelvedPool );
Assert( !Pcsr( pfucbAE )->FLatched() );
Call( ErrSPIAddToOwnExt(
pfucb,
pgnoLast,
cpgNewSpace,
&cpgOECoalesced ) );
fAddedToOwnExt = fTrue;
if ( fRootDB )
{
g_rgfmp[pfucb->ifmp].SetOwnedFileSize( CbFileSizeOfPgnoLast( pgnoLast ) );
}
if ( cpgOECoalesced > 0 )
{
Assert( g_rgfmp[pfucb->ifmp].Dbid() == dbidTemp );
Expected( sppPool == spp::AvailExtLegacyGeneralPool );
if ( sppPool == spp::AvailExtLegacyGeneralPool )
{
CPG cpgAECoalesced;
Call( ErrSPICoalesceAvailExt( pfucbAE, pgnoLast, cpgAvailable, &cpgAECoalesced ) );
Assert( cpgAECoalesced <= cpgOECoalesced );
cpgAvailable += cpgAECoalesced;
Assert( cpgAvailable > 0 );
}
}
Assert( !Pcsr( pfucbAE )->FLatched() );
if ( ( parreiReleased != NULL ) && ( parreiReleased->Size() > 0 ) )
{
Assert( !Pcsr( pfucbAE )->FLatched() );
while ( parreiReleased->Size() > 0 )
{
const EXTENTINFO& extinfoReleased = parreiReleased->Entry( parreiReleased->Size() - 1 );
Assert( extinfoReleased.FValid() && ( extinfoReleased.CpgExtent() > 0 ) );
Call( ErrSPIAEFreeExt( pfucb, extinfoReleased.PgnoFirst(), extinfoReleased.CpgExtent(), pfucbNil ) );
CallS( ( parreiReleased->ErrSetSize( parreiReleased->Size() - 1 ) == CArray<EXTENTINFO>::ERR::errSuccess ) ?
JET_errSuccess :
ErrERRCheck( JET_errOutOfMemory ) );
}
Assert( !Pcsr( pfucbAE )->FLatched() );
Call( ErrSPIReserveSPBufPages( pfucb, pfucbNil ) );
Assert( !Pcsr( pfucbAE )->FLatched() );
}
if ( fRootDB && ( cpgNewSpace > cpgAvailable ) )
{
Assert( !g_rgfmp[pfucb->ifmp].FIsTempDB() );
Assert( !Pcsr( pfucbAE )->FLatched() );
Call( ErrSPIUnshelvePagesInRange(
pfucb,
pgnoLast - cpgNewSpace + 1,
pgnoLast - cpgAvailable ) );
Assert( !Pcsr( pfucbAE )->FLatched() );
Call( ErrSPIReserveSPBufPages( pfucb, pfucbNil ) );
Assert( !Pcsr( pfucbAE )->FLatched() );
}
Call( ErrSPIAddToAvailExt( pfucbAE, pgnoLast, cpgAvailable, sppPool ) );
fAddedToAvailExt = fTrue;
Assert( Pcsr( pfucbAE )->FLatched() );
HandleError:
Assert( ( err < JET_errSuccess ) || ( fAddedToOwnExt && fAddedToAvailExt ) );
if ( fAddedToOwnExt && !fAddedToAvailExt )
{
SPIReportSpaceLeak( pfucb, err, pgnoLast - cpgAvailable + 1, cpgAvailable, "NewExt" );
}
return err;
}
INLINE ERR ErrSPICheckSmallFDP( FUCB *pfucb, BOOL *pfSmallFDP )
{
ERR err;
FUCB *pfucbOE = pfucbNil;
CPG cpgOwned = 0;
DIB dib;
CallR( ErrSPIOpenOwnExt( pfucb->ppib, pfucb->u.pfcb, &pfucbOE ) );
Assert( pfucbNil != pfucbOE );
dib.pos = posFirst;
dib.dirflag = fDIRNull;
err = ErrBTDown( pfucbOE, &dib, latchReadTouch );
Assert( err != JET_errNoCurrentRecord );
Assert( err != JET_errRecordNotFound );
*pfSmallFDP = fTrue;
do
{
Call( err );
const CSPExtentInfo spextOwnedCurr( pfucbOE );
cpgOwned += spextOwnedCurr.CpgExtent();
if ( cpgOwned > cpgSmallFDP )
{
*pfSmallFDP = fFalse;
break;
}
err = ErrBTNext( pfucbOE, fDIRNull );
}
while ( JET_errNoCurrentRecord != err );
err = JET_errSuccess;
HandleError:
Assert( pfucbNil != pfucbOE );
BTClose( pfucbOE );
return err;
}
LOCAL VOID SPReportMaxDbSizeExceeded( const IFMP ifmp, const CPG cpg )
{
WCHAR wszCurrentSizeMb[16];
const WCHAR * rgcwszT[2] = { g_rgfmp[ifmp].WszDatabaseName(), wszCurrentSizeMb };
OSStrCbFormatW( wszCurrentSizeMb, sizeof(wszCurrentSizeMb), L"%d", (ULONG)(( (QWORD)cpg * (QWORD)( g_cbPage >> 10 ) ) >> 10 ) );
UtilReportEvent(
eventWarning,
SPACE_MANAGER_CATEGORY,
SPACE_MAX_DB_SIZE_REACHED_ID,
2,
rgcwszT,
0,
NULL,
PinstFromIfmp( ifmp ) );
}
LOCAL ERR ErrSPINewSize(
const TraceContext& tc,
const IFMP ifmp,
const PGNO pgnoLastCurr,
const CPG cpgReq,
const CPG cpgAsyncExtension )
{
ERR err = JET_errSuccess;
BOOL fUpdateLgposResizeHdr = fFalse;
LGPOS lgposResize = lgposMin;
OnDebug( g_rgfmp[ifmp].AssertSafeToChangeOwnedSize() );
Assert( ( cpgReq <= 0 ) || !g_rgfmp[ifmp].FBeyondPgnoShrinkTarget( pgnoLastCurr + 1, cpgReq ) );
Assert( ( cpgReq <= 0 ) || ( pgnoLastCurr <= g_rgfmp[ifmp].PgnoLast() ) );
Expected( cpgAsyncExtension >= 0 );
if ( cpgReq < 0 )
{
Call( ErrBFPreparePageRangeForExternalZeroing( ifmp, pgnoLastCurr + cpgReq + 1, -1 * cpgReq, tc ) );
}
if ( g_rgfmp[ifmp].FLogOn() )
{
LOG* const plog = PinstFromIfmp( ifmp )->m_plog;
if ( cpgReq >= 0 )
{
Call( ErrLGExtendDatabase( plog, ifmp, pgnoLastCurr + cpgReq, &lgposResize ) );
}
else
{
if ( g_rgfmp[ifmp].FRBSOn() )
{
Call( g_rgfmp[ifmp].PRBS()->ErrFlushAll() );
}
Call( ErrLGShrinkDatabase( plog, ifmp, pgnoLastCurr + cpgReq, -1 * cpgReq, &lgposResize ) );
}
fUpdateLgposResizeHdr = ( g_rgfmp[ifmp].ErrDBFormatFeatureEnabled( JET_efvLgposLastResize ) == JET_errSuccess );
}
Call( ErrIOResizeUpdateDbHdrCount( ifmp, ( cpgReq >= 0 ) ) );
Call( ErrIONewSize(
ifmp,
tc,
pgnoLastCurr + cpgReq,
cpgAsyncExtension,
( cpgReq >= 0 ) ? JET_bitResizeDatabaseOnlyGrow : JET_bitResizeDatabaseOnlyShrink ) );
Call( ErrIOFlushDatabaseFileBuffers( ifmp, iofrDbResize ) );
if ( fUpdateLgposResizeHdr )
{
Assert( CmpLgpos( lgposResize, lgposMin ) != 0 );
Call( ErrIOResizeUpdateDbHdrLgposLast( ifmp, lgposResize ) );
}
HandleError:
OSTraceFMP(
ifmp,
JET_tracetagSpaceManagement,
OSFormat(
"Request to resize database=['%ws':0x%x] by %I64d bytes to %I64u bytes (and an additional %I64d bytes asynchronously) completed with error %d (0x%x)",
g_rgfmp[ifmp].WszDatabaseName(),
ifmp,
(__int64)cpgReq * g_cbPage,
QWORD( pgnoLastCurr + cpgReq ) * g_cbPage,
(__int64)cpgAsyncExtension * g_cbPage,
err,
err ) );
return err;
}
LOCAL ERR ErrSPIWriteZeroesDatabase(
_In_ const IFMP ifmp,
_In_ const QWORD ibOffsetStart,
_In_ const QWORD cbZeroes,
_In_ const TraceContext& tc )
{
Assert( 0 != cbZeroes );
ERR err = JET_errSuccess;
DWORD_PTR dwRangeLockContext = NULL;
const PGNO pgnoStart = PgnoOfOffset( ibOffsetStart );
const PGNO pgnoEnd = PgnoOfOffset( ibOffsetStart + cbZeroes ) - 1;
Assert( 0 == ( cbZeroes % ( g_cbPage ) ) );
Assert( pgnoStart <= pgnoEnd );
Assert( pgnoStart >= PgnoOfOffset( cpgDBReserved * g_cbPage ) );
Assert( pgnoStart != pgnoNull );
Assert( pgnoEnd != pgnoNull );
Assert( ibOffsetStart == OffsetOfPgno( pgnoStart ) );
Assert( ( ibOffsetStart + cbZeroes ) == OffsetOfPgno( pgnoEnd + 1 ) );
FMP* const pfmp = &g_rgfmp[ ifmp ];
const CPG cpg = ( pgnoEnd - pgnoStart ) + 1;
TraceContextScope tcScope( iorpSPDatabaseInlineZero, iorsNone, iortSpace );
OSTraceFMP(
ifmp,
JET_tracetagSpaceManagement,
OSFormat(
"%hs: Zeroing %I64d k at %#I64x (pages %lu through %lu).\n",
__FUNCTION__, cbZeroes / 1024, ibOffsetStart, pgnoStart, pgnoEnd ) );
CPG cpgZeroOptimal = CpgBFGetOptimalLockPageRangeSizeForExternalZeroing( ifmp );
cpgZeroOptimal = LFunctionalMin( cpgZeroOptimal, pfmp->CpgOfCb( ::g_cbZero ) );
PGNO pgnoZeroRangeThis = pgnoStart;
while ( pgnoZeroRangeThis <= pgnoEnd )
{
const CPG cpgZeroRangeThis = LFunctionalMin( cpgZeroOptimal, (CPG)( pgnoEnd - pgnoZeroRangeThis + 1 ) );
dwRangeLockContext = NULL;
Call( ErrBFLockPageRangeForExternalZeroing( ifmp, pgnoZeroRangeThis, cpgZeroRangeThis, fTrue, *tcScope, &dwRangeLockContext ) );
Call( pfmp->Pfapi()->ErrIOWrite(
*tcScope,
OffsetOfPgno( pgnoZeroRangeThis ),
(DWORD)pfmp->CbOfCpg( cpgZeroRangeThis ),
g_rgbZero,
qosIONormal | ( ( UlParam( PinstFromIfmp( ifmp ), JET_paramFlight_NewQueueOptions ) & bitUseMetedQ ) ? qosIODispatchWriteMeted : 0x0 ) ) );
BFPurgeLockedPageRangeForExternalZeroing( dwRangeLockContext, *tcScope );
BFUnlockPageRangeForExternalZeroing( dwRangeLockContext, *tcScope );
dwRangeLockContext = NULL;
pgnoZeroRangeThis += cpgZeroRangeThis;
}
HandleError:
BFUnlockPageRangeForExternalZeroing( dwRangeLockContext, *tcScope );
return err;
}
ERR ErrSPITrimUpdateDatabaseHeader( const IFMP ifmp )
{
ERR err = JET_errSuccess;
FMP *pfmp = &g_rgfmp[ifmp];
Assert( pfmp->Pdbfilehdr() );
if ( NULL != pfmp->Pdbfilehdr() )
{
BOOL fUpdateHeader = fTrue;
{
PdbfilehdrReadWrite pdbfilehdr = pfmp->PdbfilehdrUpdateable();
pdbfilehdr->le_ulTrimCount++;
#ifndef DEBUG
fUpdateHeader = ( pdbfilehdr->le_ulTrimCount <= 2 );
#endif
}
if ( fUpdateHeader )
{
Call( ErrUtilWriteAttachedDatabaseHeaders( PinstFromIfmp( ifmp ), PinstFromIfmp( ifmp )->m_pfsapi, pfmp->WszDatabaseName(), pfmp, pfmp->Pfapi() ) );
}
}
HandleError:
return err;
}
LOCAL ERR ErrSPIExtendDB(
FUCB *pfucbRoot,
const CPG cpgSEMin,
CPG *pcpgSEReq,
PGNO *ppgnoSELast,
const BOOL fPermitAsyncExtension,
const BOOL fMayViolateMaxSize,
CArray<EXTENTINFO>* const parreiReleased,
CPG *pcpgSEAvail )
{
ERR err = JET_errSuccess;
PGNO pgnoSEMaxAdj = pgnoNull;
CPG cpgSEMaxAdj = 0;
PGNO pgnoSELast = pgnoNull;
PGNO pgnoSELastAdj = pgnoNull;
CPG cpgAdj = 0;
CPG cpgSEReq = *pcpgSEReq;
CPG cpgSEReqAdj = 0;
CPG cpgSEMinAdj = 0;
FUCB *pfucbOE = pfucbNil;
FUCB *pfucbAE = pfucbNil;
CPG cpgAsyncExtension = 0;
DIB dib;
CSPExtentInfo speiAEShelved;
Assert( cpgSEMin > 0 );
Assert( cpgSEReq > 0 );
Assert( cpgSEReq >= cpgSEMin );
Assert( parreiReleased != NULL );
Assert( pgnoSystemRoot == pfucbRoot->u.pfcb->PgnoFDP() );
Assert( !g_rgfmp[pfucbRoot->ifmp].FReadOnlyAttach() );
AssertSPIPfucbOnRoot( pfucbRoot );
if ( g_rgfmp[pfucbRoot->ifmp].FShrinkIsActive() )
{
if ( fMayViolateMaxSize )
{
g_rgfmp[pfucbRoot->ifmp].ResetPgnoShrinkTarget();
}
else
{
Error( ErrERRCheck( errSPNoSpaceBelowShrinkTarget ) );
}
}
Call( ErrSPIOpenOwnExt( pfucbRoot->ppib, pfucbRoot->u.pfcb, &pfucbOE ) );
dib.pos = posLast;
dib.dirflag = fDIRNull;
Call( ErrBTDown( pfucbOE, &dib, latchReadTouch ) );
CallS( ErrSPIExtentLastPgno( pfucbOE, &pgnoSELast ) );
pgnoSELastAdj = pgnoSELast;
BTUp( pfucbOE );
pgnoSEMaxAdj = pgnoSysMax;
if ( g_rgfmp[pfucbRoot->ifmp].CpgDatabaseSizeMax() > 0 )
{
pgnoSEMaxAdj = min( pgnoSEMaxAdj, (PGNO)g_rgfmp[pfucbRoot->ifmp].CpgDatabaseSizeMax() );
}
if ( pgnoSEMaxAdj >= pgnoSELast )
{
cpgSEMaxAdj = pgnoSEMaxAdj - pgnoSELast;
}
Call( ErrSPIOpenAvailExt( pfucbRoot->ppib, pfucbRoot->u.pfcb, &pfucbAE ) );
Call( ErrSPISeekRootAE( pfucbAE, pgnoSELastAdj + 1, spp::ShelvedPool, &speiAEShelved ) );
Assert( !speiAEShelved.FIsSet() || !g_rgfmp[pfucbRoot->ifmp].FIsTempDB() );
while ( ( ( pgnoSELastAdj + cpgSEMin ) <= pgnoSysMax ) && speiAEShelved.FIsSet() )
{
Assert( speiAEShelved.PgnoFirst() > pgnoSELastAdj );
const CPG cpgAvail = (CPG)( speiAEShelved.PgnoFirst() - pgnoSELastAdj - 1 );
if ( cpgAvail >= cpgSEMin )
{
cpgSEMaxAdj = cpgAdj + cpgAvail;
break;
}
if ( cpgAvail > 0 )
{
EXTENTINFO extinfoReleased;
extinfoReleased.pgnoLastInExtent = pgnoSELastAdj + cpgAvail;
extinfoReleased.cpgExtent = cpgAvail;
Call( ( parreiReleased->ErrSetEntry( parreiReleased->Size(), extinfoReleased ) == CArray<EXTENTINFO>::ERR::errSuccess ) ?
JET_errSuccess :
ErrERRCheck( JET_errOutOfMemory ) );
}
pgnoSELastAdj = speiAEShelved.PgnoLast();
cpgAdj = pgnoSELastAdj - pgnoSELast;
speiAEShelved.Unset();
err = ErrBTNext( pfucbAE, fDIRNull );
if ( err >= JET_errSuccess )
{
speiAEShelved.Set( pfucbAE );
if ( speiAEShelved.SppPool() != spp::ShelvedPool )
{
speiAEShelved.Unset();
}
}
else if ( err == JET_errNoCurrentRecord )
{
err = JET_errSuccess;
}
Call( err );
}
BTUp( pfucbAE );
BTClose( pfucbAE );
pfucbAE = pfucbNil;
if ( ( ( pgnoSELastAdj + cpgSEMin ) > pgnoSEMaxAdj ) &&
( !fMayViolateMaxSize || ( pgnoSEMaxAdj >= pgnoSysMax ) ) )
{
AssertTrack( !fMayViolateMaxSize, "ExtendDbMaxSizeBeyondPgnoSysMax" );
SPReportMaxDbSizeExceeded( pfucbRoot->ifmp, (CPG)pgnoSELastAdj );
Error( ErrERRCheck( JET_errOutOfDatabaseSpace ) );
}
AssertTrack( !speiAEShelved.FIsSet() ||
( ( speiAEShelved.PgnoFirst() > pgnoSELastAdj ) &&
( (CPG)( speiAEShelved.PgnoFirst() - pgnoSELastAdj - 1 ) >= cpgSEMin ) ), "ExtendDbUnprocessedShelvedExt" );
Assert( cpgSEMaxAdj >= 0 );
Assert( cpgAdj >= 0 );
cpgSEMinAdj = cpgSEMin + cpgAdj;
cpgSEReqAdj = max( cpgSEMinAdj, min( cpgSEReq, cpgSEMaxAdj ) );
Assert( cpgSEMinAdj >= cpgSEMin );
Assert( cpgSEReqAdj >= cpgSEMinAdj );
if ( fPermitAsyncExtension && ( ( pgnoSELast + cpgSEReqAdj + cpgSEReq ) <= pgnoSEMaxAdj ) )
{
cpgAsyncExtension = cpgSEReq;
}
err = ErrSPINewSize( TcCurr(), pfucbRoot->ifmp, pgnoSELast, cpgSEReqAdj, cpgAsyncExtension );
if ( err < JET_errSuccess )
{
err = ErrSPINewSize( TcCurr(), pfucbRoot->ifmp, pgnoSELast, cpgSEMinAdj, 0 );
if( err < JET_errSuccess )
{
const CPG cpgExtend = 1;
CPG cpgT = 0;
do
{
cpgT += cpgExtend;
Call( ErrSPINewSize( TcCurr(), pfucbRoot->ifmp, pgnoSELast, cpgT, 0 ) );
}
while ( cpgT < cpgSEMinAdj );
}
cpgSEReqAdj = cpgSEMinAdj;
}
pgnoSELastAdj = pgnoSELast + cpgSEReqAdj;
*pcpgSEAvail = cpgSEReqAdj - cpgAdj;
*pcpgSEReq = cpgSEReqAdj;
*ppgnoSELast = pgnoSELastAdj;
Assert( ( *ppgnoSELast > pgnoSELast ) && ( ( *ppgnoSELast <= pgnoSEMaxAdj ) || fMayViolateMaxSize ) );
Assert( ( *pcpgSEAvail >= cpgSEMin ) && ( *pcpgSEAvail <= *pcpgSEReq ) );
Assert( (CPG)( *ppgnoSELast - pgnoSELast ) == ( cpgAdj + *pcpgSEAvail ) );
Assert( *pcpgSEReq == ( cpgAdj + *pcpgSEAvail ) );
HandleError:
if ( pfucbNil != pfucbOE )
{
BTClose( pfucbOE );
}
if ( pfucbNil != pfucbAE )
{
BTClose( pfucbAE );
}
return err;
}
ERR ErrSPExtendDB(
PIB * ppib,
const IFMP ifmp,
const CPG cpgSEMin,
PGNO *ppgnoSELast,
const BOOL fPermitAsyncExtension )
{
ERR err;
FUCB *pfucbDbRoot = pfucbNil;
FUCB *pfucbAE = pfucbNil;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortSpace );
tcScope->SetDwEngineObjid( objidSystemRoot );
CallR( ErrBTIOpenAndGotoRoot( ppib, pgnoSystemRoot, ifmp, &pfucbDbRoot ) );
tcScope->nParentObjectClass = TceFromFUCB( pfucbDbRoot );
Assert( objidSystemRoot == ObjidFDP( pfucbDbRoot ) );
Call( ErrSPIOpenAvailExt( pfucbDbRoot->ppib, pfucbDbRoot->u.pfcb, &pfucbAE ) );
tcScope->nParentObjectClass = TceFromFUCB( pfucbAE );
Assert( objidSystemRoot == ObjidFDP( pfucbAE ) );
BTUp( pfucbAE );
Assert( FSPIParentIsFs( pfucbDbRoot ) );
Call( ErrSPIGetFsSe(
pfucbDbRoot,
pfucbAE,
cpgSEMin,
cpgSEMin,
0,
fTrue,
fPermitAsyncExtension ) );
Assert( Pcsr( pfucbAE )->FLatched() );
BTUp( pfucbAE );
HandleError:
if ( pfucbNil != pfucbAE )
{
BTClose( pfucbAE );
}
if ( pfucbNil != pfucbDbRoot )
{
BTClose( pfucbDbRoot );
}
return err;
}
LOCAL ERR ErrSPISeekRootOELast( __in FUCB* const pfucbOE, __out CSPExtentInfo* const pspeiOE )
{
ERR err = JET_errSuccess;
DIB dib;
Assert( !Pcsr( pfucbOE )->FLatched() );
Assert( FFUCBOwnExt( pfucbOE ) );
Assert( pfucbOE->u.pfcb->PgnoFDP() == pgnoSystemRoot );
dib.pos = posLast;
dib.dirflag = fDIRNull;
dib.pbm = NULL;
err = ErrBTDown( pfucbOE, &dib, latchReadTouch );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
FireWall( "SeekOeLastNoOwned" );
Error( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
Call( err );
pspeiOE->Set( pfucbOE );
Call( pspeiOE->ErrCheckCorrupted() );
HandleError:
if ( err < JET_errSuccess )
{
BTUp( pfucbOE );
}
return err;
}
LOCAL ERR ErrSPISeekRootAE(
__in FUCB* const pfucbAE,
__in const PGNO pgno,
__in const SpacePool sppAvailPool,
__out CSPExtentInfo* const pspeiAE )
{
ERR err = JET_errSuccess;
Assert( !Pcsr( pfucbAE )->FLatched() );
Assert( FFUCBAvailExt( pfucbAE ) );
Assert( pfucbAE->u.pfcb->PgnoFDP() == pgnoSystemRoot );
err = ErrSPIFindExtAE( pfucbAE, pgno, sppAvailPool, pspeiAE );
if ( ( err == JET_errNoCurrentRecord ) || ( err == JET_errRecordNotFound ) )
{
err = JET_errSuccess;
BTUp( pfucbAE );
goto HandleError;
}
Call( err );
pspeiAE->Set( pfucbAE );
Call( pspeiAE->ErrCheckCorrupted() );
HandleError:
if ( err < JET_errSuccess )
{
BTUp( pfucbAE );
}
return err;
}
LOCAL ERR ErrSPICheckOEAELastConsistency( __in const CSPExtentInfo& speiLastOE, __in const CSPExtentInfo& speiLastAE )
{
ERR err = JET_errSuccess;
Call( speiLastOE.ErrCheckCorrupted() );
Call( speiLastAE.ErrCheckCorrupted() );
if ( speiLastAE.PgnoLast() > speiLastOE.PgnoLast() )
{
AssertTrack( fFalse, "ShrinkConsistencyAePgnoLastBeyondOePgnoLast" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( !speiLastOE.FContains( speiLastAE.PgnoFirst() ) && speiLastOE.FContains( speiLastAE.PgnoLast() ) )
{
AssertTrack( fFalse, "ShrinkConsistencyAeCrossesOeBoundary" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
HandleError:
return err;
}
ERR ErrSPShrinkTruncateLastExtent(
_In_ PIB* ppib,
_In_ const IFMP ifmp,
_In_ CPRINTF* const pcprintfShrinkTraceRaw,
_Inout_ HRT* const pdhrtExtMaint,
_Inout_ HRT* const pdhrtFileTruncation,
_Out_ PGNO* const ppgnoFirstFromLastExtentTruncated,
_Out_ ShrinkDoneReason* const psdr )
{
ERR err = JET_errSuccess;
BOOL fInTransaction = fFalse;
CSPExtentInfo speiLastOE, speiAE;
CSPExtentInfo speiLastAfterOE, speiLastAfterAE;
FMP* const pfmp = g_rgfmp + ifmp;
FUCB* pfucbRoot = pfucbNil;
FUCB* pfucbOE = pfucbNil;
FUCB* pfucbAE = pfucbNil;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope( );
tcScope->iorReason.SetIort( iortDbShrink );
tcScope->SetDwEngineObjid( objidSystemRoot );
BOOL fExtMaint = fFalse;
BOOL fFileTruncation = fFalse;
HRT hrtExtMaintStart = 0;
HRT hrtFileTruncationStart = 0;
Assert( pfmp->FShrinkIsRunning() );
Assert( pfmp->FExclusiveBySession( ppib ) );
*psdr = sdrNone;
*ppgnoFirstFromLastExtentTruncated = pgnoNull;
Call( ErrDIRBeginTransaction( ppib, 48584, NO_GRBIT ) );
fInTransaction = fTrue;
Call( ErrBTIOpen( ppib, ifmp, pgnoSystemRoot, objidNil, openNormal, &pfucbRoot, fFalse ) );
Call( ErrSPIOpenOwnExt( pfucbRoot->ppib, pfucbRoot->u.pfcb, &pfucbOE ) );
Call( ErrSPIOpenAvailExt( pfucbRoot->ppib, pfucbRoot->u.pfcb, &pfucbAE ) );
Call( ErrSPISeekRootOELast( pfucbOE, &speiLastOE ) );
*ppgnoFirstFromLastExtentTruncated = speiLastOE.PgnoFirst();
if ( speiLastOE.PgnoFirst() == pgnoSystemRoot )
{
*psdr = sdrNoLowAvailSpace;
goto HandleError;
}
pfmp->SetPgnoShrinkTarget( speiLastOE.PgnoFirst() - 1 );
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast() + 1, spp::AvailExtLegacyGeneralPool, &speiAE ) );
if ( speiAE.FIsSet() )
{
AssertTrack( fFalse, "ShrinkExtAeBeyondOe" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( ( speiLastOE.PgnoLast() + (PGNO)cpgDBReserved ) <= (PGNO)pfmp->CpgShrinkDatabaseSizeLimit() )
{
*psdr = sdrReachedSizeLimit;
goto HandleError;
}
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast(), spp::AvailExtLegacyGeneralPool, &speiAE ) );
if ( !speiAE.FIsSet() )
{
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast(), spp::ShelvedPool, &speiAE ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() != speiLastOE.PgnoLast() ) )
{
Assert( !speiAE.FIsSet() || ( speiAE.PgnoLast() > speiLastOE.PgnoLast() ) );
Error( ErrERRCheck( JET_wrnShrinkNotPossible ) );
}
}
Call( ErrSPICheckOEAELastConsistency( speiLastOE, speiAE ) );
fExtMaint = fTrue;
hrtExtMaintStart = HrtHRTCount();
PGNO pgnoLastAEExpected = speiLastOE.PgnoLast();
while ( fTrue )
{
if ( speiAE.CpgExtent() == 0 )
{
FireWall( "ShrinkExtZeroedAe" );
*psdr = sdrUnexpected;
goto HandleError;
}
Assert( speiAE.PgnoLast() == pgnoLastAEExpected );
if ( speiAE.PgnoFirst() < speiLastOE.PgnoFirst() )
{
AssertTrack( fFalse, "ShrinkExtAeCrossesOeBoundary" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( speiAE.PgnoFirst() == speiLastOE.PgnoFirst() )
{
break;
}
pgnoLastAEExpected = speiAE.PgnoFirst() - 1;
BTUp( pfucbAE );
Call( ErrSPISeekRootAE( pfucbAE, pgnoLastAEExpected, spp::AvailExtLegacyGeneralPool, &speiAE ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() != pgnoLastAEExpected ) )
{
BTUp( pfucbAE );
Call( ErrSPISeekRootAE( pfucbAE, pgnoLastAEExpected, spp::ShelvedPool, &speiAE ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() != pgnoLastAEExpected ) )
{
Error( ErrERRCheck( JET_wrnShrinkNotPossible ) );
}
}
}
if ( !pfmp->FShrinkIsActive() )
{
AssertTrack( fFalse, "ShrinkExtShrinkInactiveBeforeTruncation" );
Error( ErrERRCheck( errSPNoSpaceBelowShrinkTarget ) );
}
Call( PverFromPpib( ppib )->ErrVERRCEClean( ifmp ) );
if ( err != JET_errSuccess )
{
AssertTrack( fFalse, OSFormat( "ShrinkExtVerCleanWrn:%d", err ) );
*psdr = sdrUnexpected;
goto HandleError;
}
pfmp->WaitForTasksToComplete();
PGNO pgnoLastFileSystem = pgnoNull;
Call( pfmp->ErrPgnoLastFileSystem( &pgnoLastFileSystem ) );
const CPG cpgShrunk = pgnoLastFileSystem - ( speiLastOE.PgnoFirst() - 1 );
Assert( cpgShrunk > 0 );
BTUp( pfucbAE );
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast(), spp::AvailExtLegacyGeneralPool, &speiAE ) );
if ( !speiAE.FIsSet() )
{
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast(), spp::ShelvedPool, &speiAE ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() != speiLastOE.PgnoLast() ) )
{
AssertTrack( fFalse, "ShrinkExtNoLongerAvailableLast" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
}
Call( ErrSPICheckOEAELastConsistency( speiLastOE, speiAE ) );
ULONG cAeExtDeleted = 0, cAeExtShelved = 0;
pgnoLastAEExpected = speiLastOE.PgnoLast();
while ( fTrue )
{
if ( speiAE.CpgExtent() == 0 )
{
AssertTrack( fFalse, "ShrinkExtZeroedAeNew" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
Assert( speiAE.PgnoLast() == pgnoLastAEExpected );
if ( speiAE.PgnoFirst() < speiLastOE.PgnoFirst() )
{
AssertTrack( fFalse, "ShrinkExtAeCrossesOeBoundaryNew" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
if ( speiAE.SppPool() == spp::AvailExtLegacyGeneralPool )
{
if ( !pfmp->FShrinkIsActive() )
{
AssertTrack( fFalse, "ShrinkExtShrinkInactiveBeforeAeDeletion" );
Error( ErrERRCheck( errSPNoSpaceBelowShrinkTarget ) );
}
Expected( !pfucbAE->u.pfcb->FDontLogSpaceOps() );
Call( ErrBTFlagDelete(
pfucbAE,
fDIRNoVersion | ( pfucbAE->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) ) );
Assert( latchWrite == Pcsr( pfucbAE )->Latch() );
Pcsr( pfucbAE )->Downgrade( latchReadTouch );
cAeExtDeleted++;
Call( ErrFaultInjection( 49736 ) );
}
else
{
Assert( speiAE.SppPool() == spp::ShelvedPool );
Call( ErrSPCaptureSnapshot( pfucbRoot, speiAE.PgnoFirst(), speiAE.CpgExtent() ) );
cAeExtShelved++;
}
if ( speiAE.PgnoFirst() == speiLastOE.PgnoFirst() )
{
err = JET_errSuccess;
break;
}
pgnoLastAEExpected = speiAE.PgnoFirst() - 1;
BTUp( pfucbAE );
Call( ErrSPISeekRootAE( pfucbAE, pgnoLastAEExpected, spp::AvailExtLegacyGeneralPool, &speiAE ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() != pgnoLastAEExpected ) )
{
BTUp( pfucbAE );
Call( ErrSPISeekRootAE( pfucbAE, pgnoLastAEExpected, spp::ShelvedPool, &speiAE ) );
if ( !speiAE.FIsSet() || ( speiAE.PgnoLast() != pgnoLastAEExpected ) )
{
AssertTrack( fFalse, "ShrinkExtNoLongerAvailableNew" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
}
}
BTUp( pfucbAE );
BTUp( pfucbOE );
Call( ErrSPISeekRootOELast( pfucbOE, &speiLastAfterOE ) );
if ( speiLastAfterOE.PgnoLast() != speiLastOE.PgnoLast() )
{
Assert( speiLastAfterOE.PgnoLast() > speiLastOE.PgnoLast() );
FireWall( "ShrinkNewSpaceOwnedWhileShrinking" );
*psdr = sdrUnexpected;
goto HandleError;
}
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast(), spp::AvailExtLegacyGeneralPool, &speiLastAfterAE ) );
BTUp( pfucbAE );
if ( speiLastAfterAE.FIsSet() )
{
Call( ErrSPICheckOEAELastConsistency( speiLastAfterOE, speiLastAfterAE ) );
if ( speiLastAfterAE.PgnoLast() >= speiLastOE.PgnoFirst() )
{
FireWall( "ShrinkNewSpaceAvailWhileShrinking" );
*psdr = sdrUnexpected;
goto HandleError;
}
}
if ( ( cAeExtDeleted > 0 ) && ( cAeExtShelved > 0 ) )
{
Call( ErrFaultInjection( 50114 ) );
}
{
const QWORD cbOwnedFileSizeBefore = pfmp->CbOwnedFileSize();
pfmp->SetOwnedFileSize( CbFileSizeOfPgnoLast( speiLastAfterOE.PgnoFirst() - 1 ) );
if ( !pfmp->FShrinkIsActive() )
{
AssertTrack( fFalse, "ShrinkExtShrinkInactiveBeforeOeDeletion" );
Error( ErrERRCheck( errSPNoSpaceBelowShrinkTarget ) );
}
Expected( !pfucbOE->u.pfcb->FDontLogSpaceOps() );
err = ErrBTFlagDelete(
pfucbOE,
fDIRNoVersion | ( pfucbOE->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ) );
if ( err < JET_errSuccess )
{
pfmp->SetOwnedFileSize( cbOwnedFileSizeBefore );
}
Call( err );
Assert( latchWrite == Pcsr( pfucbOE )->Latch() );
BTUp( pfucbOE );
(*pcprintfShrinkTraceRaw)( "ShrinkTruncate[%I32u:%I32u]\r\n", speiLastAfterOE.PgnoFirst(), speiLastAfterOE.PgnoLast() );
if ( !pfmp->FShrinkIsActive() )
{
AssertTrack( fFalse, "ShrinkExtShrinkInactiveAfterTruncation" );
Error( ErrERRCheck( errSPNoSpaceBelowShrinkTarget ) );
}
}
Call( ErrSPISeekRootOELast( pfucbOE, &speiLastAfterOE ) );
BTUp( pfucbOE );
Assert( speiLastAfterOE.PgnoLast() == pfmp->PgnoLast() );
Call( ErrSPISeekRootAE( pfucbAE, speiLastOE.PgnoLast(), spp::AvailExtLegacyGeneralPool, &speiLastAfterAE ) );
BTUp( pfucbAE );
if ( speiLastAfterOE.PgnoLast() >= speiLastOE.PgnoFirst() )
{
AssertTrack( fFalse, "ShrinkNewSpaceOwnedPostOeDeleteWhileShrinking" );
Error( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
if ( speiLastAfterAE.FIsSet() )
{
Call( ErrSPICheckOEAELastConsistency( speiLastAfterOE, speiLastAfterAE ) );
if ( speiLastAfterAE.PgnoLast() >= speiLastOE.PgnoFirst() )
{
AssertTrack( fFalse, "ShrinkNewSpaceAvailPostOeDeleteWhileShrinking" );
Error( ErrERRCheck( JET_errSPAvailExtCorrupted ) );
}
}
if ( speiLastAfterOE.PgnoLast() > pgnoLastFileSystem )
{
AssertTrack( fFalse, "ShrinkExtOePgnoLastBeyondFsPgnoLast" );
Error( ErrERRCheck( JET_errSPOwnExtCorrupted ) );
}
BTClose( pfucbAE );
pfucbAE = pfucbNil;
BTClose( pfucbOE );
pfucbOE = pfucbNil;
BTClose( pfucbRoot );
pfucbRoot = pfucbNil;
Call( ErrDIRCommitTransaction( ppib, NO_GRBIT ) );
fInTransaction = fFalse;
*pdhrtExtMaint += DhrtHRTElapsedFromHrtStart( hrtExtMaintStart );
fExtMaint = fFalse;
fFileTruncation = fTrue;
hrtFileTruncationStart = HrtHRTCount();
{
PIBTraceContextScope tcScopeT = ppib->InitTraceContextScope();
tcScopeT->iorReason.SetIorp( iorpDatabaseShrink );
Call( ErrFaultInjection( 40200 ) );
Call( ErrSPINewSize( TcCurr(), ifmp, pgnoLastFileSystem, -1 * cpgShrunk, 0 ) );
}
pfmp->ResetPgnoMaxTracking( speiLastAfterOE.PgnoLast() );
*pdhrtFileTruncation += DhrtHRTElapsedFromHrtStart( hrtFileTruncationStart );
fFileTruncation = fFalse;
HandleError:
Assert( !( fExtMaint && fFileTruncation ) );
if ( fExtMaint )
{
*pdhrtExtMaint += DhrtHRTElapsedFromHrtStart( hrtExtMaintStart );
fExtMaint = fFalse;
}
if ( fFileTruncation )
{
*pdhrtFileTruncation += DhrtHRTElapsedFromHrtStart( hrtFileTruncationStart );
fFileTruncation = fFalse;
}
if ( pfucbAE != pfucbNil )
{
BTUp( pfucbAE );
BTClose( pfucbAE );
pfucbAE = pfucbNil;
}
if ( pfucbOE != pfucbNil )
{
BTUp( pfucbOE );
BTClose( pfucbOE );
pfucbOE = pfucbNil;
}
if ( pfucbRoot != pfucbNil )
{
BTClose( pfucbRoot );
pfucbRoot = pfucbNil;
}
if ( fInTransaction )
{
CallSx( ErrDIRRollback( ppib ), JET_errRollbackError );
fInTransaction = fFalse;
}
return err;
}
LOCAL CPG CpgSPICpgPrefFromCpgRequired( const CPG cpgRequired, const CPG cpgMinForSplit )
{
CPG cpgPref = 0;
if ( cpgMinForSplit <= cpgMaxRootPageSplit )
{
cpgPref = cpgPrefRootPageSplit;
}
else if ( cpgMinForSplit <= cpgMaxParentOfLeafRootSplit )
{
cpgPref = cpgPrefParentOfLeafRootSplit;
}
else
{
cpgPref = cpgPrefSpaceTreeSplit;
}
if ( cpgRequired > cpgPref )
{
cpgPref = LNextPowerOf2( cpgRequired );
}
#ifndef ENABLE_JET_UNIT_TEST
Expected( ( cpgPref <= 16 ) || ( UlConfigOverrideInjection( 46030, 0 ) != 0 ) );
#endif
return cpgPref;
}
#ifdef ENABLE_JET_UNIT_TEST
JETUNITTEST( SPACE, CpgSPICpgPrefFromCpgRequired )
{
CHECK( 2 == CpgSPICpgPrefFromCpgRequired( 0, 0 ) );
CHECK( 2 == CpgSPICpgPrefFromCpgRequired( 2, 0 ) );
CHECK( 4 == CpgSPICpgPrefFromCpgRequired( 3, 0 ) );
CHECK( 4 == CpgSPICpgPrefFromCpgRequired( 4, 0 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 5, 0 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 8, 0 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 9, 0 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 16, 0 ) );
CHECK( 32 == CpgSPICpgPrefFromCpgRequired( 17, 0 ) );
CHECK( 2 == CpgSPICpgPrefFromCpgRequired( 2, 2 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 3, 3 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 4, 4 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 5, 5 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 16, 16 ) );
CHECK( 32 == CpgSPICpgPrefFromCpgRequired( 17, 17 ) );
CHECK( 4 == CpgSPICpgPrefFromCpgRequired( 3, 2 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 4, 3 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 5, 4 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 6, 5 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 16, 15 ) );
CHECK( 32 == CpgSPICpgPrefFromCpgRequired( 17, 16 ) );
CHECK( 4 == CpgSPICpgPrefFromCpgRequired( 4, 2 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 6, 3 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 8, 4 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 10, 5 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 16, 8 ) );
CHECK( 32 == CpgSPICpgPrefFromCpgRequired( 18, 9 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 5, 2 ) );
CHECK( 8 == CpgSPICpgPrefFromCpgRequired( 7, 3 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 9, 4 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 11, 5 ) );
CHECK( 16 == CpgSPICpgPrefFromCpgRequired( 15, 7 ) );
CHECK( 32 == CpgSPICpgPrefFromCpgRequired( 17, 8 ) );
}
#endif
LOCAL ERR ErrSPIReserveSPBufPagesForSpaceTree(
FUCB* const pfucb,
FUCB* const pfucbSpace,
FUCB* const pfucbParent,
CArray<EXTENTINFO>* const parreiReleased = NULL,
const CPG cpgAddlReserve = 0,
const PGNO pgnoReplace = pgnoNull )
{
ERR err = JET_errSuccess;
ERR wrn = JET_errSuccess;
SPLIT_BUFFER *pspbuf = NULL;
CPG cpgMinForSplit = 0;
FMP* pfmp = g_rgfmp + pfucb->ifmp;
OnDebug( ULONG crepeat = 0 );
Assert( pfmp != NULL );
Assert( ( pfucb != pfucbNil ) && !FFUCBSpace( pfucb ) );
Assert( ( pfucbSpace != pfucbNil ) && FFUCBSpace( pfucbSpace ) );
Assert( ( pfucbParent == pfucbNil ) || !FFUCBSpace( pfucbParent ) );
Assert( !Pcsr( pfucbSpace )->FLatched() );
Assert( pfucb->u.pfcb == pfucbSpace->u.pfcb );
Assert( pfucb->u.pfcb->FSpaceInitialized() );
Assert( !FSPIIsSmall( pfucb->u.pfcb ) );
Assert( ( pgnoReplace == pgnoNull ) || pfmp->FShrinkIsRunning() );
const BOOL fUpdatingDbRoot = ( pfucbParent == pfucbNil );
const BOOL fMayViolateMaxSize = ( pgnoReplace == pgnoNull );
const BOOL fAvailExt = FFUCBAvailExt( pfucbSpace );
const BOOL fOwnExt = FFUCBOwnExt( pfucbSpace );
Assert( !!fAvailExt ^ !!fOwnExt );
rtlconst BOOL fForceRefillDbgOnly = fFalse;
OnDebug( fForceRefillDbgOnly = ( ErrFaultInjection( 47594 ) < JET_errSuccess ) && !g_fRepair );
rtlconst BOOL fForcePostAddToOwnExtDbgOnly = fFalse;
rtlconst ERR errFaultAddToOe = JET_errSuccess;
#ifdef DEBUG
errFaultAddToOe = fUpdatingDbRoot ? ErrFaultInjection( 60394 ) : ErrFaultInjection( 35818 );
OnDebug( fForcePostAddToOwnExtDbgOnly = ( ( errFaultAddToOe == JET_errSuccess ) && ( rand() % 4 ) == 0 ) );
#endif
forever
{
BOOL fSingleAndAvailableEnough = fFalse;
SPLIT_BUFFER spbufBefore;
Assert( crepeat < 3 );
OnDebug( crepeat++ );
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRootOrNull( pfucbParent );
Call( ErrBTIGotoRoot( pfucbSpace, latchRIW ) );
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
Call( ErrSPIGetSPBuf( pfucbSpace, &pspbuf ) );
UtilMemCpy( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) );
if ( pfucbSpace->csr.Cpage().FLeafPage() )
{
fSingleAndAvailableEnough = pfucbSpace->csr.Cpage().CbPageFree() >= 80;
Expected( fSingleAndAvailableEnough || ( ( pspbuf->CpgBuffer1() + pspbuf->CpgBuffer2() ) >= cpgMinForSplit ) );
if ( pfucbSpace->csr.Cpage().CbPageFree() < 100 )
{
cpgMinForSplit = cpgMaxRootPageSplit;
}
else
{
cpgMinForSplit = 0;
}
}
else if ( pfucbSpace->csr.Cpage().FParentOfLeaf() )
{
cpgMinForSplit = cpgMaxParentOfLeafRootSplit;
}
else
{
cpgMinForSplit = cpgMaxSpaceTreeSplit;
}
CPG cpgRequired;
CPG cpgRequest;
CPG cpgAvailable;
CPG cpgNewSpace;
BYTE ispbufReplace;
BOOL fSpBuffersAvailableEnough;
BOOL fSpBufRefilled;
BOOL fAlreadyOwn;
BOOL fAddedToOwnExt;
PGNO pgnoLast;
const ERR wrnT = wrn;
forever
{
wrn = wrnT;
cpgRequired = 0;
cpgRequest = 0;
cpgAvailable = 0;
cpgNewSpace = 0;
ispbufReplace = 0;
fSpBuffersAvailableEnough = fFalse;
fSpBufRefilled = fFalse;
fAlreadyOwn = fFalse;
fAddedToOwnExt = fFalse;
pgnoLast = pgnoNull;
cpgRequired = fOwnExt ? ( 2 * cpgMinForSplit ) : cpgMinForSplit;
cpgRequired += ( cpgAddlReserve + (CPG)UlConfigOverrideInjection( 46030, 0 ) );
OnDebug( fForceRefillDbgOnly = fForceRefillDbgOnly && ( cpgRequired > 0 ) );
if ( pspbuf->PgnoLastBuffer1() > pfmp->PgnoLast() )
{
ispbufReplace = 1;
}
else if ( pspbuf->PgnoLastBuffer2() > pfmp->PgnoLast() )
{
ispbufReplace = 2;
}
if ( ( pgnoReplace != pgnoNull ) && ( ispbufReplace == 0 ) )
{
if ( pspbuf->FBuffer1ContainsPgno( pgnoReplace ) )
{
Assert( !pspbuf->FBuffer2ContainsPgno( pgnoReplace ) );
ispbufReplace = 1;
}
else if ( pspbuf->FBuffer2ContainsPgno( pgnoReplace ) )
{
ispbufReplace = 2;
}
}
if ( pfmp->FShrinkIsActive() && ( ispbufReplace == 0 ) )
{
if ( pfmp->FBeyondPgnoShrinkTarget( pspbuf->PgnoFirstBuffer1(), pspbuf->CpgBuffer1() ) )
{
ispbufReplace = 1;
}
else if ( pfmp->FBeyondPgnoShrinkTarget( pspbuf->PgnoFirstBuffer2(), pspbuf->CpgBuffer2() ) )
{
ispbufReplace = 2;
}
}
const CPG cpgSpBuffer1Available = ( pfmp->FBeyondPgnoShrinkTarget( pspbuf->PgnoFirstBuffer1(), pspbuf->CpgBuffer1() ) ||
( pspbuf->PgnoLastBuffer1() > pfmp->PgnoLast() ) ) ? 0 : pspbuf->CpgBuffer1();
const CPG cpgSpBuffer2Available = ( pfmp->FBeyondPgnoShrinkTarget( pspbuf->PgnoFirstBuffer2(), pspbuf->CpgBuffer2() ) ||
( pspbuf->PgnoLastBuffer2() > pfmp->PgnoLast() ) ) ? 0 : pspbuf->CpgBuffer2();
fSpBuffersAvailableEnough = ( ( cpgSpBuffer1Available + cpgSpBuffer2Available ) >= cpgMinForSplit );
if ( ispbufReplace != 0 )
{
OnDebug( const PGNO pgnoLastSpBuf = ( ispbufReplace == 1 ) ? pspbuf->PgnoLastBuffer1() : pspbuf->PgnoLastBuffer2() );
OnDebug( const PGNO cpgExt = ( ispbufReplace == 1 ) ? pspbuf->CpgBuffer1() : pspbuf->CpgBuffer2() );
Expected( pfmp->FShrinkIsRunning() || ( pgnoLastSpBuf > pfmp->PgnoLast() ) );
wrn = ErrERRCheck( wrnSPRequestSpBufRefill );
const CPG cpgNewSpBuf = cpgRequired - ( ( ispbufReplace == 1 ) ? cpgSpBuffer2Available : cpgSpBuffer1Available );
cpgRequired = max( cpgNewSpBuf, cpgMaxRootPageSplit );
}
if ( ( ( cpgSpBuffer1Available + cpgSpBuffer2Available ) >= cpgRequired ) &&
( ispbufReplace == 0 ) &&
!fForceRefillDbgOnly )
{
fSpBufRefilled = fTrue;
break;
}
Assert( cpgRequired > 0 );
cpgRequest = CpgSPICpgPrefFromCpgRequired( cpgRequired, cpgMinForSplit );
if ( pfmp->FShrinkIsRunning() && fUpdatingDbRoot )
{
BTUp( pfucbSpace );
pspbuf = NULL;
PGNO pgnoFirst = pgnoNull;
cpgNewSpace = cpgRequest;
err = ErrSPIGetExt(
pfucb->u.pfcb,
pfucb,
&cpgNewSpace,
cpgRequired,
&pgnoFirst,
fSPSelfReserveExtent );
AssertSPIPfucbOnRoot( pfucb );
if ( err >= JET_errSuccess )
{
cpgAvailable = cpgNewSpace;
pgnoLast = pgnoFirst + cpgNewSpace - 1;
fAlreadyOwn = fTrue;
}
else if ( err == errSPNoSpaceForYou )
{
err = JET_errSuccess;
}
Call( err );
Call( ErrBTIGotoRoot( pfucbSpace, latchRIW ) );
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
Call( ErrSPIGetSPBuf( pfucbSpace, &pspbuf ) );
Assert( 0 == memcmp( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) ) );
UtilMemCpy( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) );
}
Assert( !!fAlreadyOwn ^ !!( pgnoLast == pgnoNull ) );
if ( fForcePostAddToOwnExtDbgOnly ||
fAlreadyOwn || !fOwnExt ||
!fUpdatingDbRoot ||
fSpBuffersAvailableEnough || fSingleAndAvailableEnough )
{
break;
}
AssertTrack( pfmp->FShrinkIsActive(), "SpBufUnexpectedShrinkInactive" );
if ( !pfmp->FShrinkIsActive() )
{
break;
}
pfmp->ResetPgnoShrinkTarget();
Assert( !pfmp->FShrinkIsActive() );
}
if ( fSpBufRefilled )
{
break;
}
if ( !fAlreadyOwn )
{
if ( !fUpdatingDbRoot )
{
PGNO pgnoFirst = pgnoNull;
cpgNewSpace = cpgRequest;
err = ErrSPIGetExt(
pfucb->u.pfcb,
pfucbParent,
&cpgNewSpace,
cpgRequired,
&pgnoFirst,
0,
0,
NULL,
fMayViolateMaxSize );
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRoot( pfucbParent );
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
Call( err );
cpgAvailable = cpgNewSpace;
pgnoLast = pgnoFirst + cpgNewSpace - 1;
}
else
{
Assert( pgnoSystemRoot == pfucb->u.pfcb->PgnoFDP() );
cpgRequired = max( cpgRequired, cpgMaxSpaceTreeSplit );
cpgRequest = CpgSPICpgPrefFromCpgRequired( cpgRequired, cpgMinForSplit );
AssertTrack( NULL == pfucbSpace->u.pfcb->Psplitbuf( fAvailExt ), "NonNullRootAvailSplitBuff" );
BTUp( pfucbSpace );
pspbuf = NULL;
cpgNewSpace = cpgRequest;
Call( ErrSPIExtendDB(
pfucb,
cpgRequired,
&cpgNewSpace,
&pgnoLast,
fFalse,
fMayViolateMaxSize,
parreiReleased,
&cpgAvailable ) );
Call( ErrBTIGotoRoot( pfucbSpace, latchRIW ) );
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
Call( ErrSPIGetSPBuf( pfucbSpace, &pspbuf ) );
Assert( 0 == memcmp( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) ) );
UtilMemCpy( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) );
}
}
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
Assert( cpgRequest >= cpgRequired );
Assert( cpgAvailable >= cpgRequired );
Assert( cpgNewSpace >= cpgAvailable );
if ( !fAlreadyOwn &&
( !fOwnExt ||
( !fForcePostAddToOwnExtDbgOnly &&
( fSpBuffersAvailableEnough || fSingleAndAvailableEnough ) ) ) )
{
BTUp( pfucbSpace );
pspbuf = NULL;
Call( errFaultAddToOe );
Call( ErrSPIAddToOwnExt( pfucbSpace, pgnoLast, cpgNewSpace, NULL ) );
fAddedToOwnExt = fTrue;
if ( fUpdatingDbRoot )
{
pfmp->SetOwnedFileSize( CbFileSizeOfPgnoLast( pgnoLast ) );
}
wrn = ErrERRCheck( wrnSPRequestSpBufRefill );
Call( ErrBTIGotoRoot( pfucbSpace, latchRIW ) );
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
Call( ErrSPIGetSPBuf( pfucbSpace, &pspbuf ) );
Assert( fOwnExt || ( 0 == memcmp( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) ) ) );
UtilMemCpy( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) );
}
AssertSPIPfucbOnSpaceTreeRoot( pfucbSpace, Pcsr( pfucbSpace ) );
BYTE ispbuf = 0;
if ( NULL == pfucbSpace->u.pfcb->Psplitbuf( fAvailExt ) )
{
pfucbSpace->csr.UpgradeFromRIWLatch();
Assert( 0 == memcmp( &spbufBefore,
PspbufSPISpaceTreeRootPage( pfucbSpace, Pcsr( pfucbSpace ) ),
sizeof(SPLIT_BUFFER) ) );
Assert( sizeof( SPLIT_BUFFER ) == pfucbSpace->kdfCurr.data.Cb() );
UtilMemCpy( &spbufBefore, PspbufSPISpaceTreeRootPage( pfucbSpace, Pcsr( pfucbSpace ) ), sizeof(SPLIT_BUFFER) );
SPLIT_BUFFER spbuf;
DATA data;
UtilMemCpy( &spbuf, &spbufBefore, sizeof(SPLIT_BUFFER) );
ispbuf = spbuf.AddPages( pgnoLast, cpgAvailable, ispbufReplace );
Assert( ( ispbufReplace == 0 ) || ( ispbuf == ispbufReplace ) );
data.SetPv( &spbuf );
data.SetCb( sizeof(spbuf) );
Call( ErrNDSetExternalHeader(
pfucbSpace,
&data,
( pfucbSpace->u.pfcb->FDontLogSpaceOps() ? fDIRNoLog : fDIRNull ),
noderfWhole ) );
}
else
{
Assert( pspbuf == pfucbSpace->u.pfcb->Psplitbuf( fAvailExt ) );
Assert( 0 == memcmp( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) ) );
UtilMemCpy( &spbufBefore, pspbuf, sizeof(SPLIT_BUFFER) );
ispbuf = pspbuf->AddPages( pgnoLast, cpgAvailable, ispbufReplace );
Assert( ( ispbufReplace == 0 ) || ( ispbuf == ispbufReplace ) );
SPITraceSplitBufferMsg( pfucbSpace, "Added pages to" );
}
BTUp( pfucbSpace );
pspbuf = NULL;
EXTENTINFO extinfoReleased;
Assert( ( ispbuf == 1 ) || ( ispbuf == 2 ) );
extinfoReleased.pgnoLastInExtent = ( ispbuf == 1 ) ? spbufBefore.PgnoLastBuffer1() : spbufBefore.PgnoLastBuffer2();
extinfoReleased.cpgExtent = ( ispbuf == 1 ) ? spbufBefore.CpgBuffer1() : spbufBefore.CpgBuffer2();
Assert( extinfoReleased.FValid() );
if ( extinfoReleased.CpgExtent() > 0 )
{
if ( parreiReleased != NULL )
{
Call( ( parreiReleased->ErrSetEntry( parreiReleased->Size(), extinfoReleased ) == CArray<EXTENTINFO>::ERR::errSuccess ) ?
JET_errSuccess :
ErrERRCheck( JET_errOutOfMemory ) );
}
else
{
FireWall( "SpBufDroppedReleased" );
}
}
Assert( !fAddedToOwnExt || ( wrn == wrnSPRequestSpBufRefill ) );
if ( !fAlreadyOwn && !fAddedToOwnExt )
{
Assert( fOwnExt );
AssertTrack( fForcePostAddToOwnExtDbgOnly || ( !fSpBuffersAvailableEnough && !fUpdatingDbRoot ), "SpBufPostAddToOe" );
if ( fUpdatingDbRoot )
{
pfmp->SetOwnedFileSize( CbFileSizeOfPgnoLast( pgnoLast ) );
}
Call( ErrSPIAddToOwnExt( pfucb, pgnoLast, cpgNewSpace, NULL ) );
fAddedToOwnExt = fTrue;
wrn = ErrERRCheck( wrnSPRequestSpBufRefill );
}
Assert( !fAddedToOwnExt || ( wrn == wrnSPRequestSpBufRefill ) );
if ( !fOwnExt || !fAddedToOwnExt )
{
break;
}
OnDebug( fForceRefillDbgOnly = fFalse );
}
CallS( err );
err = wrn;
HandleError:
BTUp( pfucbSpace );
pspbuf = NULL;
AssertSPIPfucbOnRoot( pfucb );
AssertSPIPfucbOnRootOrNull( pfucbParent );
return err;
}
ERR ErrSPReserveSPBufPagesForSpaceTree( FUCB *pfucb, FUCB *pfucbSpace, FUCB *pfucbParent )
{
ERR err = JET_errSuccess;
PIBTraceContextScope tcScope = pfucbSpace->ppib->InitTraceContextScope();
tcScope->nParentObjectClass = TceFromFUCB( pfucbSpace );
tcScope->SetDwEngineObjid( ObjidFDP( pfucbSpace ) );
tcScope->iorReason.SetIort( iortSpace );
Expected( g_fRepair );
Assert( !Pcsr( pfucb )->FLatched() );
Assert( pcsrNil == pfucb->pcsrRoot );
Assert( !Pcsr( pfucbParent )->FLatched() );
Assert( pcsrNil == pfucbParent->pcsrRoot );
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
Call( ErrBTIGotoRoot( pfucbParent, latchRIW ) );
pfucbParent->pcsrRoot = Pcsr( pfucbParent );
Call( ErrSPIReserveSPBufPagesForSpaceTree( pfucb, pfucbSpace, pfucbParent ) );
HandleError:
BTUp( pfucbParent );
pfucbParent->pcsrRoot = pcsrNil;
BTUp( pfucb );
pfucb->pcsrRoot = pcsrNil;
return err;
}
ERR ErrSPReserveSPBufPages(
FUCB* const pfucb,
const BOOL fAddlReserveForPageMoveOE,
const BOOL fAddlReserveForPageMoveAE )
{
ERR err = JET_errSuccess;
FUCB* pfucbOwningTree = pfucbNil;
Call( ErrBTIOpenAndGotoRoot(
pfucb->ppib,
pfucb->u.pfcb->PgnoFDP(),
pfucb->ifmp,
&pfucbOwningTree ) );
Assert( pfucbOwningTree->u.pfcb == pfucb->u.pfcb );
Call( ErrSPIReserveSPBufPages(
pfucbOwningTree,
pfucbNil,
fAddlReserveForPageMoveOE ? 1 : 0,
fAddlReserveForPageMoveAE ? 1 : 0 ) );
HandleError:
if ( pfucbOwningTree != pfucbNil )
{
pfucbOwningTree->pcsrRoot->ReleasePage();
pfucbOwningTree->pcsrRoot = pcsrNil;
BTClose( pfucbOwningTree );
pfucbOwningTree = pfucbNil;
}
return err;
}
ERR ErrSPReplaceSPBuf(
FUCB* const pfucb,
FUCB* const pfucbParent,
const PGNO pgnoReplace )
{
ERR err = JET_errSuccess;
Assert( pfucb != pfucbNil );
Call( ErrBTIGotoRoot( pfucb, latchRIW ) );
pfucb->pcsrRoot = Pcsr( pfucb );
if ( pfucbParent != pfucbNil )
{
Call( ErrBTIGotoRoot( pfucbParent, latchRIW ) );
pfucbParent->pcsrRoot = Pcsr( pfucbParent );
}
Call( ErrSPIReserveSPBufPages(
pfucb,
pfucbParent,
0,
0,
pgnoReplace ) );
HandleError:
if ( ( pfucbParent != pfucbNil ) && ( pfucbParent->pcsrRoot != pcsrNil ) )
{
pfucbParent->pcsrRoot->ReleasePage();
pfucbParent->pcsrRoot = pcsrNil;
}
if ( pfucb->pcsrRoot != pcsrNil )
{
pfucb->pcsrRoot->ReleasePage();
pfucb->pcsrRoot = pcsrNil;
}
return err;
}
LOCAL ERR ErrSPIReserveSPBufPages(
FUCB* const pfucb,
FUCB* const pfucbParent,
const CPG cpgAddlReserveOE,
const CPG cpgAddlReserveAE,
const PGNO pgnoReplace )
{
ERR err = JET_errSuccess;
FCB* const pfcb = pfucb->u.pfcb;
FUCB* pfucbParentLocal = pfucbParent;
FUCB* pfucbOE = pfucbNil;
FUCB* pfucbAE = pfucbNil;
BOOL fNeedRefill = fTrue;
CArray<EXTENTINFO> arreiReleased( 10 );
const PGNO pgnoParentFDP = PsphSPIRootPage( pfucb )->PgnoParent();
const PGNO pgnoLastBefore = g_rgfmp[ pfucb->ifmp ].PgnoLast();
Assert( ( pgnoParentFDP != pgnoNull ) || ( pfucbParent == pfucbNil ) );
if ( ( pfucbParentLocal == pfucbNil ) && ( pgnoParentFDP != pgnoNull ) )
{
Call( ErrBTIOpenAndGotoRoot( pfucb->ppib, pgnoParentFDP, pfucb->ifmp, &pfucbParentLocal ) );
}
Call( ErrSPIOpenOwnExt( pfucb->ppib, pfcb, &pfucbOE ) );
Call( ErrSPIOpenAvailExt( pfucb->ppib, pfcb, &pfucbAE ) );
while ( fNeedRefill )
{
fNeedRefill = fFalse;
Call( ErrSPIReserveSPBufPagesForSpaceTree(
pfucb,
pfucbOE,
pfucbParentLocal,
&arreiReleased,
cpgAddlReserveOE,
pgnoReplace ) );
fNeedRefill = ( err == wrnSPRequestSpBufRefill );
Call( ErrSPIReserveSPBufPagesForSpaceTree(
pfucb,
pfucbAE,
pfucbParentLocal,
&arreiReleased,
cpgAddlReserveAE,
pgnoReplace ) );
fNeedRefill = fNeedRefill || ( err == wrnSPRequestSpBufRefill );
if ( arreiReleased.Size() > 0 )
{
const EXTENTINFO& extinfoReleased = arreiReleased[ arreiReleased.Size() - 1 ];
Assert( extinfoReleased.FValid() && ( extinfoReleased.CpgExtent() > 0 ) );
Call( ErrSPIAEFreeExt( pfucb, extinfoReleased.PgnoFirst(), extinfoReleased.CpgExtent(), pfucbParentLocal ) );
CallS( ( arreiReleased.ErrSetSize( arreiReleased.Size() - 1 ) == CArray<EXTENTINFO>::ERR::errSuccess ) ?
JET_errSuccess :
ErrERRCheck( JET_errOutOfMemory ) );
fNeedRefill = fTrue;
}
}
const PGNO pgnoLastAfter = g_rgfmp[ pfucb->ifmp ].PgnoLast();
if ( !g_rgfmp[ pfucb->ifmp ].FIsTempDB() && ( pfcb->PgnoFDP() == pgnoSystemRoot ) && ( pgnoLastAfter > pgnoLastBefore ) )
{
Call( ErrSPIUnshelvePagesInRange( pfucb, pgnoLastBefore + 1, pgnoLastAfter ) );
Call( ErrSPIReserveSPBufPages( pfucb, pfucbParentLocal, cpgAddlReserveOE, cpgAddlReserveAE, pgnoReplace ) );
}
HandleError:
if ( pfucbNil != pfucbOE )
{
BTClose( pfucbOE );
}
if ( pfucbNil != pfucbAE )
{
BTClose( pfucbAE );
}
if ( ( pfucbParentLocal != pfucbNil ) && ( pfucbParentLocal != pfucbParent ) )
{
Expected( pfucbParent == pfucbNil );
AssertSPIPfucbOnRoot( pfucbParentLocal );
pfucbParentLocal->pcsrRoot->ReleasePage();
pfucbParentLocal->pcsrRoot = pcsrNil;
BTClose( pfucbParentLocal );
pfucbParentLocal = pfucbNil;
}
Assert( ( err < JET_errSuccess ) || ( arreiReleased.Size() == 0 ) );
for ( size_t iext = 0; iext < arreiReleased.Size(); iext++ )
{
const EXTENTINFO& extinfoLeaked = arreiReleased[ iext ];
SPIReportSpaceLeak( pfucb, err, extinfoLeaked.PgnoFirst(), (CPG)extinfoLeaked.CpgExtent(), "SpBuffer" );
}
return err;
}
LOCAL ERR ErrSPIAllocatePagesSlowlyIfSparse(
_In_ IFMP ifmp,
_In_ const PGNO pgnoFirstImportant,
_In_ const PGNO pgnoLastImportant,
_In_ const CPG cpgReq,
_In_ const TraceContext& tc )
{
ERR err = JET_errSuccess;
Expected( cpgReq == (CPG)( pgnoLastImportant - pgnoFirstImportant + 1 ) );
Enforce( pgnoFirstImportant <= pgnoLastImportant );
FMP* const pfmp = &g_rgfmp[ ifmp ];
const QWORD ibFirstRangeImportant = OffsetOfPgno( pgnoFirstImportant );
const QWORD ibLastRangeImportant = OffsetOfPgno( pgnoLastImportant + 1 ) - 1;
CArray<SparseFileSegment> arrsparseseg;
Enforce( ibFirstRangeImportant >= OffsetOfPgno( pgnoSystemRoot + 3 ) );
if ( !pfmp->FTrimSupported() )
{
goto HandleError;
}
Call( ErrIORetrieveSparseSegmentsInRegion( pfmp->Pfapi(),
ibFirstRangeImportant,
ibLastRangeImportant,
&arrsparseseg ) );
for ( size_t isparseseg = 0; isparseseg < arrsparseseg.Size(); isparseseg++ )
{
const SparseFileSegment& sparseseg = arrsparseseg[isparseseg];
Enforce( sparseseg.ibFirst <= sparseseg.ibLast );
Enforce( sparseseg.ibFirst >= OffsetOfPgno( pgnoSystemRoot + 3 ) );
Enforce( sparseseg.ibFirst >= ibFirstRangeImportant );
Enforce( sparseseg.ibLast <= ibLastRangeImportant );
const QWORD cbToWrite = sparseseg.ibLast - sparseseg.ibFirst + 1;
Enforce( ( cbToWrite % g_cbPage ) == 0 );
Call( ErrSPIWriteZeroesDatabase( ifmp, sparseseg.ibFirst, cbToWrite, tc ) );
}
HandleError:
return err;
}
LOCAL ERR FSPIParentIsFs( FUCB * const pfucb )
{
AssertSPIPfucbOnRoot( pfucb );
Assert( pfucb->u.pfcb->FSpaceInitialized() );
const SPACE_HEADER * const psph = PsphSPIRootPage( pfucb );
const PGNO pgnoParentFDP = psph->PgnoParent();
return pgnoNull == pgnoParentFDP;
}
LOCAL ERR ErrSPIGetSe(
FUCB * const pfucb,
FUCB * const pfucbAE,
const CPG cpgReq,
const CPG cpgMin,
const ULONG fSPFlags,
const SpacePool sppPool,
const BOOL fMayViolateMaxSize )
{
ERR err;
PIB *ppib = pfucb->ppib;
FUCB *pfucbParent = pfucbNil;
CPG cpgSEReq;
CPG cpgSEMin;
PGNO pgnoSELast;
FMP *pfmp = &g_rgfmp[ pfucb->ifmp ];
const BOOL fSplitting = BoolSetFlag( fSPFlags, fSPSplitting );
AssertSPIPfucbOnRoot( pfucb );
Assert( !pfmp->FReadOnlyAttach() );
Assert( pfucbNil != pfucbAE );
Assert( !Pcsr( pfucbAE )->FLatched() );
Assert( pfucb->u.pfcb->FSpaceInitialized() );
Assert( !FSPIParentIsFs( pfucb ) );
const SPACE_HEADER * const psph = PsphSPIRootPage( pfucb );
const PGNO pgnoParentFDP = psph->PgnoParent();
Assert( pgnoNull != pgnoParentFDP );
PGNO pgnoSEFirst = pgnoNull;
BOOL fSmallFDP = fFalse;
cpgSEMin = cpgMin;
if ( fSPFlags & fSPOriginatingRequest )
{
if ( fSPFlags & fSPExactExtent )
{
cpgSEReq = cpgReq;
}
else
{
if ( psph->Fv1() &&
( psph->CpgPrimary() < cpgSmallFDP ) )
{
const CPAGE& cpage = pfucb->pcsrRoot->Cpage();
if ( cpage.FLeafPage()
|| ( cpage.FParentOfLeaf() && cpage.Clines() < cpgSmallFDP ) )
{
Call( ErrSPICheckSmallFDP( pfucb, &fSmallFDP ) );
}
}
if ( fSmallFDP )
{
cpgSEReq = max( cpgReq, cpgSmallGrow );
}
else
{
const CPG cpgSEReqDefault = ( pfmp->FIsTempDB()
&& ppib->FBatchIndexCreation() ?
cpageDbExtensionDefault :
cpageSEDefault );
Assert( cpageDbExtensionDefault != cpgSEReqDefault
|| pgnoSystemRoot == pgnoParentFDP );
const CPG cpgNextLeast = psph->Fv1() ? ( psph->CpgPrimary() / cSecFrac ) : psph->CpgLastAlloc();
cpgSEReq = max( cpgReq, max( cpgNextLeast, cpgSEReqDefault ) );
}
}
Assert( psph->FMultipleExtent() );
const CPG cpgLastAlloc = psph->Fv1() ? psph->CpgPrimary() : psph->CpgLastAlloc();
cpgSEReq = max( cpgSEReq, CpgSPIGetNextAlloc( pfucb->u.pfcb->Pfcbspacehints(), cpgLastAlloc ) );
if ( cpgSEReq != cpgLastAlloc )
{
(void)ErrSPIImproveLastAlloc( pfucb, psph, cpgSEReq );
}
if ( fSPFlags & fSPExactExtent )
{
cpgSEMin = cpgSEReq;
}
}
else
{
cpgSEReq = cpgReq;
}
Call( ErrBTIOpenAndGotoRoot( pfucb->ppib, pgnoParentFDP, pfucb->ifmp, &pfucbParent ) );
Call( ErrSPIReserveSPBufPages( pfucb, pfucbParent ) );
err = ErrSPIGetExt(
pfucb->u.pfcb,
pfucbParent,
&cpgSEReq,
cpgSEMin,
&pgnoSEFirst,
fSPFlags & ( fSplitting | fSPExactExtent ),
0,
NULL,
fMayViolateMaxSize );
AssertSPIPfucbOnRoot( pfucbParent );
AssertSPIPfucbOnRoot( pfucb );
Call( err );
Assert( cpgSEReq >= cpgSEMin );
pgnoSELast = pgnoSEFirst + cpgSEReq - 1;
BTUp( pfucbAE );
if ( pgnoSystemRoot == pgnoParentFDP )
{
if ( pfmp->Pdbfilehdr()->le_ulTrimCount > 0 )
{
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Allocating Root Extent( %d - %d, %d )\n", pgnoSEFirst, pgnoSELast, cpgSEReq ) );
PIBTraceContextScope tcScope = pfucb->ppib->InitTraceContextScope();
Call( ErrSPIAllocatePagesSlowlyIfSparse( pfucb->ifmp, pgnoSEFirst, pgnoSELast, cpgSEReq, *tcScope ) );
}
}
err = ErrSPIAddSecondaryExtent(
pfucb,
pfucbAE,
pgnoSELast,
cpgSEReq,
cpgSEReq,
NULL,
sppPool );
Assert( errSPOutOfOwnExtCacheSpace != err );
Assert( errSPOutOfAvailExtCacheSpace != err );
Call( err );
AssertSPIPfucbOnRoot( pfucb );
Assert( Pcsr( pfucbAE )->FLatched() );
Assert( cpgSEReq >= cpgSEMin );
HandleError:
if ( pfucbNil != pfucbParent )
{
if ( pcsrNil != pfucbParent->pcsrRoot )
{
pfucbParent->pcsrRoot->ReleasePage();
pfucbParent->pcsrRoot = pcsrNil;
}
Assert( !Pcsr( pfucbParent )->FLatched() );
BTClose( pfucbParent );
}
return err;
}
LOCAL ERR ErrSPIGetFsSe(
FUCB * const pfucb,
FUCB * const pfucbAE,
const CPG cpgReq,
const CPG cpgMin,
const ULONG fSPFlags,
const BOOL fExact,
const BOOL fPermitAsyncExtension,
const BOOL fMayViolateMaxSize )
{
ERR err = JET_errSuccess;
PIB *ppib = pfucb->ppib;
CPG cpgSEReq = cpgReq;
CPG cpgSEMin = cpgMin;
CPG cpgSEAvail = 0;
PGNO pgnoSELast = pgnoNull;
FMP *pfmp = &g_rgfmp[ pfucb->ifmp ];
PGNO pgnoParentFDP = pgnoNull;
CArray<EXTENTINFO> arreiReleased;
AssertSPIPfucbOnRoot( pfucb );
Assert( !pfmp->FReadOnlyAttach() );
Assert( pfucbNil != pfucbAE );
Assert( !Pcsr( pfucbAE )->FLatched() );
Assert( pfucb->u.pfcb->FSpaceInitialized() );
Assert( FSPIParentIsFs( pfucb ) );
Assert( cpgMin > 0 );
Assert( cpgReq >= cpgMin );
const SPACE_HEADER * const psph = PsphSPIRootPage( pfucb );
pgnoParentFDP = psph->PgnoParent();
Assert( pgnoNull == pgnoParentFDP );
const CPG cpgDbExtensionSize = (CPG)UlParam( PinstFromPpib( ppib ), JET_paramDbExtensionSize );
PGNO pgnoPreLast = 0;
if ( fExact )
{
Expected( cpgSEMin == cpgSEReq );
Expected( 0 == cpgSEReq % cpgDbExtensionSize );
cpgSEMin = cpgSEReq;
}
else
{
if ( pfmp->FIsTempDB() && !ppib->FBatchIndexCreation() )
{
cpgSEReq = max( cpgReq, cpageSEDefault );
}
else
{
cpgSEReq = max( cpgReq, cpgDbExtensionSize );
}
Assert( psph->Fv1() );
cpgSEReq = max( cpgSEReq, psph->Fv1() ? ( psph->CpgPrimary() / cSecFrac ) : psph->CpgLastAlloc() );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal, OSFormat( "GetFsSe[%d] - %d ? %d : %d, %d -> %d",
(ULONG)pfucb->ifmp, psph->Fv1(), psph->Fv1() ? ( psph->CpgPrimary() / cSecFrac ) : -1,
psph->Fv1() ? -1 : psph->CpgLastAlloc(), cpgSEMin, cpgSEReq ) );
if ( !pfmp->FIsTempDB() )
{
cpgSEReq = roundup( cpgSEReq, cpgDbExtensionSize );
Assert( cpgSEMin >= cpgMin );
Assert( cpgSEReq >= cpgReq );
Assert( cpgSEReq >= cpgSEMin );
Expected( FBFLatched( pfucb->ifmp, pgnoSystemRoot ) );
pgnoPreLast = g_rgfmp[pfucb->ifmp].PgnoLast();
const CPG cpgLogicalFileSize = pgnoPreLast + cpgDBReserved;
Enforce( pgnoPreLast < 0x100000000 );
Enforce( g_rgfmp[pfucb->ifmp].CbOwnedFileSize() / g_cbPage < 0x100000000 );
#ifdef DEBUG
{
PGNO pgnoPreLastCheck = 0;
if ( ErrSPGetLastPgno( ppib, pfucb->ifmp, &pgnoPreLastCheck ) >= JET_errSuccess )
{
Assert( pgnoPreLastCheck == pgnoPreLast || g_fRepair );
}
const CPG cpgFullFileSize = pfmp->CpgOfCb( g_rgfmp[pfucb->ifmp].CbOwnedFileSize() );
const CPG cpgDbExt = (CPG)UlParam( PinstFromPfucb( pfucb ), JET_paramDbExtensionSize );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal, OSFormat( "( %d + 2 [ + %d ] == %d )\n", pgnoPreLast, cpgDbExt, cpgFullFileSize ) );
}
#endif
const CPG cpgOverage = cpgLogicalFileSize % cpgDbExtensionSize;
if ( cpgOverage )
{
const CPG cpgReduction = cpgSEReq - cpgOverage;
if ( cpgReduction >= cpgSEMin )
{
cpgSEReq = cpgReduction;
}
else
{
Assert( cpgDbExtensionSize - cpgOverage > 0 );
cpgSEReq += ( cpgDbExtensionSize - cpgOverage );
}
}
}
}
Assert( cpgSEMin >= cpgMin );
Assert( cpgSEReq >= cpgSEMin );
Assert( !Ptls()->fNoExtendingDuringCreateDB );
Call( ErrSPIReserveSPBufPages( pfucb, pfucbNil ) );
Assert( pgnoPreLast <= g_rgfmp[pfucb->ifmp].PgnoLast() || g_fRepair );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Pre-extend stats: %I64u bytes (pgnoLast %I32u) ... %d unaligned overage",
g_rgfmp[pfucb->ifmp].CbOwnedFileSize(),
g_rgfmp[pfucb->ifmp].PgnoLast(),
g_rgfmp[pfucb->ifmp].CpgOfCb( g_rgfmp[pfucb->ifmp].CbOwnedFileSize() ) % cpgDbExtensionSize ) );
Assert( cpgSEMin >= cpgMin );
Assert( cpgSEReq >= cpgSEMin );
Call( ErrSPIExtendDB(
pfucb,
cpgSEMin,
&cpgSEReq,
&pgnoSELast,
fPermitAsyncExtension,
fMayViolateMaxSize,
&arreiReleased,
&cpgSEAvail ) );
Assert( pgnoPreLast <= g_rgfmp[pfucb->ifmp].PgnoLast() || g_fRepair );
BTUp( pfucbAE );
err = ErrSPIAddSecondaryExtent(
pfucb,
pfucbAE,
pgnoSELast,
cpgSEReq,
cpgSEAvail,
&arreiReleased,
spp::AvailExtLegacyGeneralPool );
Assert( errSPOutOfOwnExtCacheSpace != err );
Assert( errSPOutOfAvailExtCacheSpace != err );
Call( err );
Assert( pgnoPreLast < g_rgfmp[pfucb->ifmp].PgnoLast() || g_fRepair );
Assert( arreiReleased.Size() == 0 );
OSTraceFMP( pfucb->ifmp, JET_tracetagSpaceInternal,
OSFormat( "Post-extend stats: %I64u bytes (pgnoLast %I32u) ... %d unaligned overage",
g_rgfmp[pfucb->ifmp].CbOwnedFileSize(),
g_rgfmp[pfucb->ifmp].PgnoLast(),
g_rgfmp[pfucb->ifmp].CpgOfCb( g_rgfmp[pfucb->ifmp].CbOwnedFileSize() ) % cpgDbExtensionSize ) );
#ifdef DEBUG
Assert( FBFLatched( pfucb->ifmp, pgnoSystemRoot ) );
#endif
if ( pfmp->FCacheAvail() )
{
pfmp->AdjustCpgAvail( cpgSEAvail );
}
AssertSPIPfucbOnRoot( pfucb );
Assert( Pcsr( pfucbAE )->FLatched() );
Assert( cpgSEAvail >= cpgSEMin );
HandleError:
return err;
}
LOCAL ERR ErrSPIGetSparseInfoRange(
_In_ FMP* const pfmp,
_In_ const PGNO pgnoStart,
_In_ const PGNO pgnoEnd,
_Out_ CPG* pcpgSparse
)
{
ERR err = JET_errSuccess;
CPG cpgSparseTotal = 0;
CPG cpgAllocatedTotal = 0;
const QWORD ibEndRange = OffsetOfPgno( pgnoEnd + 1 );
CPG cpgRegionPrevious = 0;
*pcpgSparse = 0;
Assert( pgnoStart <= pgnoEnd );
for ( PGNO pgnoQuery = pgnoStart; pgnoQuery < pgnoEnd + 1; pgnoQuery += cpgRegionPrevious )
{
const QWORD ibOffsetToQuery = OffsetOfPgno( pgnoQuery );
QWORD ibStartAllocatedRegion;
QWORD cbAllocated;
Assert( ibOffsetToQuery < ibEndRange );
cpgRegionPrevious = 0;
Call( pfmp->Pfapi()->ErrRetrieveAllocatedRegion( ibOffsetToQuery, &ibStartAllocatedRegion, &cbAllocated ) );
Assert( ibStartAllocatedRegion >= ibOffsetToQuery || 0 == ibStartAllocatedRegion );
if ( ibStartAllocatedRegion > ibOffsetToQuery )
{
const QWORD ibEndSparse = min( ibEndRange, ibStartAllocatedRegion );
const CPG cpgSparseThisQuery = pfmp->CpgOfCb( ibEndSparse - ibOffsetToQuery );
cpgSparseTotal += cpgSparseThisQuery;
cpgRegionPrevious += cpgSparseThisQuery;
}
else if ( 0 == ibStartAllocatedRegion )
{
const QWORD ibEndSparse = ibEndRange;
const CPG cpgSparseThisQuery = pfmp->CpgOfCb( ibEndSparse - ibOffsetToQuery );
cpgSparseTotal += cpgSparseThisQuery;
cpgRegionPrevious += cpgSparseThisQuery;
}
const QWORD ibEndAllocated = min( ibEndRange, ibStartAllocatedRegion + cbAllocated );
if ( ibEndAllocated > 0 && ibEndAllocated <= ibEndRange )
{
const QWORD ibStartAllocated = min( ibEndRange, ibStartAllocatedRegion );
Assert( ibEndAllocated >= ibStartAllocated );
const CPG cpgAllocatedThisQuery = pfmp->CpgOfCb( ibEndAllocated - ibStartAllocated );
cpgAllocatedTotal += cpgAllocatedThisQuery;
cpgRegionPrevious += cpgAllocatedThisQuery;
}
Assert( cpgRegionPrevious > 0 );
Assert( pgnoQuery + cpgRegionPrevious <= pgnoEnd + 1 );
}
Assert( ( (CPG) ( pgnoEnd - pgnoStart + 1 ) ) == ( cpgAllocatedTotal + cpgSparseTotal ) );
*pcpgSparse = cpgSparseTotal;
HandleError:
return err;
}
LOCAL ERR ErrSPITrimRegion(
_In_ const IFMP ifmp,
_In_ PIB* const ppib,
_In_ const PGNO pgnoLast,
_In_ const CPG cpgRequestedToTrim,
_Out_ CPG* pcpgSparseBeforeThisExtent,
_Out_ CPG* pcpgSparseAfterThisExtent
)
{
ERR err;
*pcpgSparseBeforeThisExtent = 0;
*pcpgSparseAfterThisExtent = 0;
const PGNO pgnoStartZeroes = pgnoLast - cpgRequestedToTrim + 1;
PGNO pgnoStartZeroesAligned = 0;
PGNO pgnoEndZeroesAligned = 0;
CPG cpgZeroesAligned = 0;
Assert( cpgRequestedToTrim > 0 );
if ( ( UlParam(PinstFromIfmp ( ifmp ), JET_paramWaypointLatency ) > 0 ) ||
g_rgfmp[ ifmp ].FDBMScanOn() )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Skipping Trim for ifmp %d because either LLR or DBScan is on (cpgRequested=%d).", ifmp, cpgRequestedToTrim ) );
err = JET_errSuccess;
goto HandleError;
}
QWORD ibStartZeroes = 0;
QWORD cbZeroLength = 0;
Call( ErrIOTrimNormalizeOffsetsAndPgnos(
ifmp,
pgnoStartZeroes,
cpgRequestedToTrim,
&ibStartZeroes,
&cbZeroLength,
&pgnoStartZeroesAligned,
&cpgZeroesAligned ) );
Assert( cpgZeroesAligned <= cpgRequestedToTrim );
const CPG cpgNotZeroedDueToAlignment = cpgRequestedToTrim - cpgZeroesAligned;
pgnoEndZeroesAligned = pgnoStartZeroesAligned + cpgZeroesAligned - 1;
if ( cpgNotZeroedDueToAlignment > 0 )
{
PERFOpt( cSPPagesNotTrimmedUnalignedPage.Add( PinstFromIfmp( ifmp ), cpgNotZeroedDueToAlignment ) );
}
if ( cbZeroLength > 0 )
{
Assert( pgnoStartZeroesAligned > 0 );
Assert( pgnoEndZeroesAligned >= pgnoStartZeroesAligned );
const PGNO pgnoEndRegionAligned = pgnoStartZeroesAligned + cpgZeroesAligned - 1;
Call( ErrSPIGetSparseInfoRange( &g_rgfmp[ ifmp ], pgnoStartZeroesAligned, pgnoEndRegionAligned, pcpgSparseBeforeThisExtent ) );
*pcpgSparseAfterThisExtent = *pcpgSparseBeforeThisExtent;
Assert( *pcpgSparseBeforeThisExtent <= cpgZeroesAligned );
if ( *pcpgSparseBeforeThisExtent >= cpgZeroesAligned )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Trimming ifmp %d for [start=%d,cpg=%d] is skipped because the region is already trimmed.",
ifmp, pgnoStartZeroesAligned, cpgZeroesAligned ) );
}
else
{
TraceContextScope tcScope( iorpDatabaseTrim );
if ( tcScope->nParentObjectClass == pocNone )
{
tcScope->nParentObjectClass = tceNone;
}
Call( ErrBFPreparePageRangeForExternalZeroing( ifmp, pgnoStartZeroesAligned, cpgZeroesAligned, *tcScope ) );
if ( g_rgfmp[ ifmp ].FLogOn() )
{
Call( ErrLGTrimDatabase( PinstFromIfmp( ifmp )->m_plog, ifmp, ppib, pgnoStartZeroesAligned, cpgZeroesAligned ) );
}
PERFOpt( cSPPagesTrimmed.Add( PinstFromIfmp( ifmp ), cpgZeroesAligned ) );
Call( ErrSPITrimUpdateDatabaseHeader( ifmp ) );
err = ErrIOTrim( ifmp, ibStartZeroes, cbZeroLength );
if( JET_errUnloadableOSFunctionality == err ||
JET_errFeatureNotAvailable == err )
{
*pcpgSparseAfterThisExtent = *pcpgSparseBeforeThisExtent;
err = JET_errSuccess;
goto HandleError;
}
Call( err );
CallS( err );
const ERR errT = ErrSPIGetSparseInfoRange( &g_rgfmp[ ifmp ], pgnoStartZeroesAligned, pgnoEndRegionAligned, pcpgSparseAfterThisExtent );
Assert( errT >= JET_errSuccess );
if ( errT >= JET_errSuccess )
{
Assert( *pcpgSparseAfterThisExtent >= 0 );
Assert( *pcpgSparseAfterThisExtent >= *pcpgSparseBeforeThisExtent );
}
}
}
HandleError:
Assert( *pcpgSparseAfterThisExtent >= *pcpgSparseBeforeThisExtent );
return err;
}
LOCAL ERR ErrSPIAddFreedExtent(
FUCB *pfucb,
FUCB *pfucbAE,
const PGNO pgnoLast,
const CPG cpgSize )
{
ERR err;
const IFMP ifmp = pfucbAE->ifmp;
AssertSPIPfucbOnRoot( pfucb );
Assert( !Pcsr( pfucbAE )->FLatched() );
const PGNO pgnoParentFDP = PsphSPIRootPage( pfucb )->PgnoParent();
Call( ErrSPIAddToAvailExt( pfucbAE, pgnoLast, cpgSize, spp::AvailExtLegacyGeneralPool ) );
Assert( Pcsr( pfucbAE )->FLatched() );
if ( ( pgnoParentFDP == pgnoSystemRoot ) &&
g_rgfmp[ ifmp ].FTrimSupported() &&
( ( GrbitParam( g_rgfmp[ ifmp ].Pinst(), JET_paramEnableShrinkDatabase ) & ( JET_bitShrinkDatabaseOn | JET_bitShrinkDatabaseRealtime ) ) ==
( JET_bitShrinkDatabaseOn | JET_bitShrinkDatabaseRealtime ) ) )
{
CPG cpgSparseBeforeThisExtent = 0;
CPG cpgSparseAfterThisExtent = 0;
(void) ErrSPITrimRegion( ifmp, pfucbAE->ppib, pgnoLast, cpgSize, &cpgSparseBeforeThisExtent, &cpgSparseAfterThisExtent );
}
HandleError:
AssertSPIPfucbOnRoot( pfucb );
return err;
}
INLINE ERR ErrSPCheckInfoBuf( const ULONG cbBufSize, const ULONG fSPExtents )
{
ULONG cbUnchecked = cbBufSize;
if ( FSPOwnedExtent( fSPExtents ) )
{
if ( cbUnchecked < sizeof(CPG) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
cbUnchecked -= sizeof(CPG);
if ( FSPExtentList( fSPExtents ) )
{
if ( cbUnchecked < sizeof(EXTENTINFO) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
cbUnchecked -= sizeof(EXTENTINFO);
}
}
if ( FSPAvailExtent( fSPExtents ) )
{
if ( cbUnchecked < sizeof(CPG) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
cbUnchecked -= sizeof(CPG);
if ( FSPExtentList( fSPExtents ) )
{
if ( cbUnchecked < sizeof(EXTENTINFO) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
cbUnchecked -= sizeof(EXTENTINFO);
}
}
if ( FSPReservedExtent( fSPExtents ) )
{
if ( cbUnchecked < sizeof(CPG) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
cbUnchecked -= sizeof(CPG);
}
if ( FSPShelvedExtent( fSPExtents ) )
{
if ( cbUnchecked < sizeof(CPG) )
{
return ErrERRCheck( JET_errBufferTooSmall );
}
cbUnchecked -= sizeof(CPG);
}
return JET_errSuccess;
}
_When_( (return >= 0), _Post_satisfies_( *pcextMac <= *pcextMax ))
LOCAL ERR ErrSPIAddExtentInfo(
_Inout_ BTREE_SPACE_EXTENT_INFO ** pprgext,
_Inout_ ULONG * pcextMax,
_Inout_ ULONG * pcextMac,
_In_ const SpacePool sppPool,
_In_ const PGNO pgnoLast,
_In_ const CPG cpgExtent,
_In_ const PGNO pgnoSpaceNode )
{
ERR err = JET_errSuccess;
Expected( cpgExtent || sppPool == spp::ContinuousPool );
if ( *pcextMac >= *pcextMax )
{
Assert( *pcextMac == *pcextMax );
BTREE_SPACE_EXTENT_INFO * prgextToFree = *pprgext;
const ULONG cextNewSize = (*pcextMax) * 2;
Alloc( *pprgext = new BTREE_SPACE_EXTENT_INFO[cextNewSize] );
*pcextMax = cextNewSize;
memset( *pprgext, 0, sizeof(BTREE_SPACE_EXTENT_INFO)*(*pcextMax) );
C_ASSERT( sizeof(**pprgext) == 16 );
memcpy( *pprgext, prgextToFree, *pcextMac * sizeof(**pprgext) );
delete [] prgextToFree;
}
Assert( *pcextMac < *pcextMax );
AssumePREFAST( *pcextMac < *pcextMax );
(*pprgext)[*pcextMac].iPool = (ULONG)sppPool;
(*pprgext)[*pcextMac].pgnoLast = pgnoLast;
(*pprgext)[*pcextMac].cpgExtent = cpgExtent;
(*pprgext)[*pcextMac].pgnoSpaceNode = pgnoSpaceNode;
(*pcextMac)++;
HandleError:
return err;
}
_Pre_satisfies_( *pcextMac <= *pcextMax )
_When_( (return >= 0), _Post_satisfies_( *pcextMac <= *pcextMax ))
LOCAL ERR ErrSPIExtGetExtentListInfo(
_Inout_ FUCB * pfucb,
_At_(*pprgext, _Out_writes_to_(*pcextMax, *pcextMac)) BTREE_SPACE_EXTENT_INFO ** pprgext,
_Inout_ ULONG * pcextMax,
_Inout_ ULONG * pcextMac )
{
ERR err;
DIB dib;
ULONG cRecords = 0;
ULONG cRecordsDeleted = 0;
FUCBSetSequential( pfucb );
FUCBSetPrereadForward( pfucb, cpgPrereadSequential );
dib.dirflag = fDIRNull;
dib.pos = posFirst;
Assert( FFUCBSpace( pfucb ) );
err = ErrBTDown( pfucb, &dib, latchReadNoTouch );
if ( err != JET_errRecordNotFound )
{
Call( err );
forever
{
const CSPExtentInfo cspext( pfucb );
++cRecords;
if( FNDDeleted( pfucb->kdfCurr ) )
{
++cRecordsDeleted;
}
else
{
Assert( ( cspext.SppPool() != spp::ShelvedPool ) || FFUCBAvailExt( pfucb ) );
Assert( ( cspext.SppPool() != spp::ShelvedPool ) || ( pfucb->u.pfcb->PgnoFDP() == pgnoSystemRoot ) );
Expected( ( cspext.SppPool() != spp::ShelvedPool ) || ( cspext.CpgExtent() == 1 ) );
Expected( FSPIValidExplicitSpacePool( cspext.SppPool() ) );
Expected( cspext.CpgExtent() != 0 || cspext.SppPool() == spp::ContinuousPool );
Call( ErrSPIAddExtentInfo( pprgext, pcextMax, pcextMac, (SpacePool)cspext.SppPool(), cspext.PgnoLast(), cspext.CpgExtent(), pfucb->csr.Pgno() ) );
}
err = ErrBTNext( pfucb, fDIRNull );
if ( err < 0 )
{
if ( err == JET_errNoCurrentRecord )
{
break;
}
Call( err );
}
}
}
Assert( err == JET_errNoCurrentRecord || err == JET_errRecordNotFound );
err = JET_errSuccess;
HandleError:
return err;
}
LOCAL ERR ErrSPIGetInfo(
FUCB *pfucb,
CPG *pcpgTotal,
CPG *pcpgReserved,
CPG *pcpgShelved,
INT *piext,
INT cext,
EXTENTINFO *rgext,
INT *pcextSentinelsRemaining,
CPRINTF * const pcprintf )
{
ERR err;
DIB dib;
INT iext = *piext;
const BOOL fExtentList = ( cext > 0 );
PGNO pgnoLastSeen = pgnoNull;
CPG cpgSeen = 0;
ULONG cRecords = 0;
ULONG cRecordsDeleted = 0;
Assert( !fExtentList || NULL != pcextSentinelsRemaining );
*pcpgTotal = 0;
if ( pcpgReserved )
{
*pcpgReserved = 0;
}
if ( pcpgShelved )
{
*pcpgShelved = 0;
}
FUCBSetSequential( pfucb );
FUCBSetPrereadForward( pfucb, cpgPrereadSequential );
dib.dirflag = fDIRNull;
dib.pos = posFirst;
Assert( FFUCBSpace( pfucb ) );
err = ErrBTDown( pfucb, &dib, latchReadNoTouch );
if ( err != JET_errRecordNotFound )
{
Call( err );
forever
{
const CSPExtentInfo cspext( pfucb );
if( pcprintf )
{
CPG cpgSparse = 0;
if ( !cspext.FEmptyExtent() )
{
(void) ErrSPIGetSparseInfoRange( &g_rgfmp[ pfucb->ifmp ], cspext.PgnoFirst(), cspext.PgnoLast(), &cpgSparse );
}
if( pgnoLastSeen != Pcsr( pfucb )->Pgno() )
{
pgnoLastSeen = Pcsr( pfucb )->Pgno();
++cpgSeen;
}
(*pcprintf)( "%30s: %s[%5d]:\t%6d-%6d (%3d) %s%s",
SzNameOfTable( pfucb ),
SzSpaceTreeType( pfucb ),
Pcsr( pfucb )->Pgno(),
cspext.FEmptyExtent() ? 0 : cspext.PgnoFirst(),
cspext.FEmptyExtent() ? cspext.PgnoMarker() : cspext.PgnoLast(),
cspext.CpgExtent(),
FNDDeleted( pfucb->kdfCurr ) ? " (DEL)" : "",
( cspext.ErrCheckCorrupted( ) < JET_errSuccess ) ? " (COR)" : ""
);
if ( cspext.FNewAvailFormat() )
{
(*pcprintf)( " Pool: %d %s",
cspext.SppPool(),
cspext.FNewAvailFormat() ? "(fNewAvailFormat)" : ""
);
}
if ( cpgSparse > 0 )
{
(*pcprintf)( " cpgSparse: %3d", cpgSparse );
}
(*pcprintf)( "\n" );
++cRecords;
if( FNDDeleted( pfucb->kdfCurr ) )
{
++cRecordsDeleted;
}
}
if ( cspext.SppPool() != spp::ShelvedPool )
{
*pcpgTotal += cspext.CpgExtent();
}
if ( pcpgReserved && cspext.FNewAvailFormat() &&
( cspext.SppPool() == spp::ContinuousPool ) )
{
*pcpgReserved += cspext.CpgExtent();
}
BOOL fSuppressExtent = fFalse;
if ( pcpgShelved && cspext.FNewAvailFormat() &&
( cspext.SppPool() == spp::ShelvedPool ) )
{
if ( cspext.PgnoLast() > g_rgfmp[ pfucb->ifmp ].PgnoLast() )
{
Assert( cspext.PgnoFirst() > g_rgfmp[ pfucb->ifmp ].PgnoLast() );
*pcpgShelved += cspext.CpgExtent();
}
else
{
fSuppressExtent = fTrue;
}
}
if ( fExtentList && !fSuppressExtent )
{
Assert( iext < cext );
Assert( iext + *pcextSentinelsRemaining <= cext );
if ( iext + *pcextSentinelsRemaining < cext )
{
rgext[iext].pgnoLastInExtent = cspext.PgnoLast();
rgext[iext].cpgExtent = cspext.CpgExtent();
iext++;
}
}
err = ErrBTNext( pfucb, fDIRNull );
if ( err < 0 )
{
if ( err != JET_errNoCurrentRecord )
goto HandleError;
break;
}
}
}
if ( fExtentList )
{
Assert( iext < cext );
rgext[iext].pgnoLastInExtent = pgnoNull;
rgext[iext].cpgExtent = 0;
iext++;
Assert( NULL != pcextSentinelsRemaining );
Assert( *pcextSentinelsRemaining > 0 );
(*pcextSentinelsRemaining)--;
}
*piext = iext;
Assert( *piext + *pcextSentinelsRemaining <= cext );
if( pcprintf )
{
(*pcprintf)( "%s:\t%d pages, %d nodes, %d deleted nodes\n",
SzNameOfTable( pfucb ),
cpgSeen,
cRecords,
cRecordsDeleted );
}
err = JET_errSuccess;
HandleError:
return err;
}
VOID SPDumpSplitBufExtent(
CPRINTF * const pcprintf,
__in const CHAR * szTable,
__in const CHAR * szSpaceTree,
__in const PGNO pgnoSpaceFDP,
__in const SPLIT_BUFFER * pspbuf
)
{
if ( pcprintf )
{
if ( pspbuf->CpgBuffer1() )
{
(*pcprintf)( "%30s: AE[%5d]:\t%6d-%6d (%3d) Pool: (%s Split Buffer)\n",
szTable,
pgnoSpaceFDP,
( pspbuf->CpgBuffer1() <= 0 ) ? 0 : pspbuf->PgnoLastBuffer1() - pspbuf->CpgBuffer1() + 1,
pspbuf->PgnoLastBuffer1(),
pspbuf->CpgBuffer1(),
szSpaceTree
);
}
if ( pspbuf->CpgBuffer2() )
{
(*pcprintf)( "%30s: AE[%5d]:\t%6d-%6d (%3d) Pool: (%s Split Buffer)\n",
szTable,
pgnoSpaceFDP,
( pspbuf->CpgBuffer2() <= 0 ) ? 0 : pspbuf->PgnoLastBuffer2() - pspbuf->CpgBuffer2() + 1,
pspbuf->PgnoLastBuffer2(),
pspbuf->CpgBuffer2(),
szSpaceTree
);
}
}
}
ERR ErrSPGetDatabaseInfo(
PIB *ppib,
const IFMP ifmp,
__out_bcount(cbMax) BYTE *pbResult,
const ULONG cbMax,
const ULONG fSPExtents,
bool fUseCachedResult,
CPRINTF * const pcprintf )
{
ERR err = JET_errSuccess;
CPG *pcpgT = (CPG *)pbResult;
ULONG cbMaxReq = 0;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortSpace );
if ( ( fSPExtents & ( fSPOwnedExtent | fSPAvailExtent | fSPShelvedExtent ) ) == 0 )
{
return ErrERRCheck( JET_errInvalidParameter );
}
if ( ( fSPExtents & ~( fSPOwnedExtent | fSPAvailExtent | fSPShelvedExtent ) ) != 0 )
{
return ErrERRCheck( JET_errInvalidParameter );
}
Assert( FSPOwnedExtent( fSPExtents ) || FSPAvailExtent( fSPExtents ) || FSPShelvedExtent( fSPExtents ) );
if ( FSPShelvedExtent( fSPExtents ) )
{
Assert( FSPAvailExtent( fSPExtents ) );
if ( fUseCachedResult )
{
return ErrERRCheck( JET_errInvalidParameter );
}
}
if ( FSPOwnedExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( FSPAvailExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( FSPShelvedExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( cbMax < cbMaxReq )
{
AssertSz( fFalse, "Called without the necessary buffer allocated for extents." );
return ErrERRCheck( JET_errInvalidParameter );
}
CallR( ErrSPCheckInfoBuf( cbMax, fSPExtents ) );
memset( pbResult, 0, cbMax );
int ipg = 0;
const int ipgOwned = FSPOwnedExtent( fSPExtents ) ? ipg++ : -1;
const int ipgAvail = FSPAvailExtent( fSPExtents ) ? ipg++ : -1;
const int ipgShelved = FSPShelvedExtent( fSPExtents ) ? ipg++ : -1;
if ( !fUseCachedResult ||
( FSPAvailExtent( fSPExtents ) && !g_rgfmp[ifmp].FCacheAvail() ) )
{
Call( ErrSPGetInfo( ppib, ifmp, pfucbNil, pbResult, cbMax, fSPExtents, pcprintf ) );
if ( FSPAvailExtent( fSPExtents ) )
{
Assert( ipgAvail >= 0 );
g_rgfmp[ifmp].SetCpgAvail( *( pcpgT + ipgAvail ) );
}
}
else
{
if ( ipgOwned >= 0 )
{
*( pcpgT + ipgOwned ) = g_rgfmp[ifmp].PgnoLast();
}
if ( ipgAvail >= 0 )
{
*( pcpgT + ipgAvail ) = g_rgfmp[ifmp].CpgAvail();
}
Assert( ipgShelved < 0 );
}
HandleError:
return err;
}
ERR ErrSPGetInfo(
PIB *ppib,
const IFMP ifmp,
FUCB *pfucb,
__out_bcount(cbMax) BYTE *pbResult,
const ULONG cbMax,
const ULONG fSPExtents,
CPRINTF * const pcprintf )
{
ERR err;
CPG *pcpgOwnExtTotal;
CPG *pcpgAvailExtTotal;
CPG *pcpgReservedExtTotal;
CPG *pcpgShelvedExtTotal;
EXTENTINFO *rgext;
FUCB *pfucbT = pfucbNil;
INT iext;
SPLIT_BUFFER spbufOnOE;
SPLIT_BUFFER spbufOnAE;
ULONG cbMaxReq = 0;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortSpace );
Assert( ( fSPExtents & fSPExtentList ) == 0 );
if ( !( FSPOwnedExtent( fSPExtents ) || FSPAvailExtent( fSPExtents ) ) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
if ( FSPReservedExtent( fSPExtents ) && !FSPAvailExtent( fSPExtents ) )
{
ExpectedSz( fFalse, "initially we won't support getting reserved w/o avail." );
return ErrERRCheck( JET_errInvalidParameter );
}
if ( FSPShelvedExtent( fSPExtents ) && !FSPAvailExtent( fSPExtents ) )
{
ExpectedSz( fFalse, "initially we won't support getting shelved w/o avail." );
return ErrERRCheck( JET_errInvalidParameter );
}
if ( FSPOwnedExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( FSPAvailExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( FSPReservedExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( FSPShelvedExtent( fSPExtents ) )
{
cbMaxReq += sizeof( CPG );
}
if ( cbMax < cbMaxReq )
{
AssertSz( fFalse, "Called without the necessary buffer allocated for extents." );
return ErrERRCheck( JET_errInvalidParameter );
}
CallR( ErrSPCheckInfoBuf( cbMax, fSPExtents ) );
memset( pbResult, '\0', cbMax );
memset( (void*)&spbufOnOE, 0, sizeof(spbufOnOE) );
memset( (void*)&spbufOnAE, 0, sizeof(spbufOnAE) );
CPG * pcpgT = (CPG *)pbResult;
pcpgOwnExtTotal = NULL;
pcpgAvailExtTotal = NULL;
pcpgReservedExtTotal = NULL;
pcpgShelvedExtTotal = NULL;
if ( FSPOwnedExtent( fSPExtents ) )
{
pcpgOwnExtTotal = pcpgT;
pcpgT++;
}
if ( FSPAvailExtent( fSPExtents ) )
{
pcpgAvailExtTotal = pcpgT;
pcpgT++;
}
if ( FSPReservedExtent( fSPExtents ) )
{
pcpgReservedExtTotal = pcpgT;
pcpgT++;
}
if ( FSPShelvedExtent( fSPExtents ) )
{
pcpgShelvedExtTotal = pcpgT;
pcpgT++;
}
rgext = (EXTENTINFO *)pcpgT;
if ( pcpgOwnExtTotal )
{
*pcpgOwnExtTotal = 0;
}
if ( pcpgAvailExtTotal )
{
*pcpgAvailExtTotal = 0;
}
if ( pcpgReservedExtTotal )
{
*pcpgReservedExtTotal = 0;
}
if ( pcpgShelvedExtTotal )
{
*pcpgShelvedExtTotal = 0;
}
const BOOL fExtentList = FSPExtentList( fSPExtents );
const INT cext = fExtentList ? ( ( pbResult + cbMax ) - ( (BYTE *)rgext ) ) / sizeof(EXTENTINFO) : 0;
INT cextSentinelsRemaining;
cextSentinelsRemaining = 0;
if ( fExtentList )
{
cextSentinelsRemaining += FSPOwnedExtent( fSPExtents ) ? 1 : 0;
cextSentinelsRemaining += FSPAvailExtent( fSPExtents ) ? 1 : 0;
Assert( cext >= cextSentinelsRemaining );
}
if ( pfucbNil == pfucb )
{
err = ErrBTOpen( ppib, pgnoSystemRoot, ifmp, &pfucbT );
}
else
{
err = ErrBTOpen( ppib, pfucb->u.pfcb, &pfucbT );
}
CallR( err );
Assert( pfucbNil != pfucbT );
tcScope->nParentObjectClass = TceFromFUCB( pfucbT );
tcScope->SetDwEngineObjid( ObjidFDP( pfucbT ) );
Call( ErrBTIGotoRoot( pfucbT, latchReadTouch ) );
Assert( pcsrNil == pfucbT->pcsrRoot );
pfucbT->pcsrRoot = Pcsr( pfucbT );
if ( !pfucbT->u.pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucbT, fTrue );
if( !FSPIIsSmall( pfucbT->u.pfcb ) )
{
BFPrereadPageRange( pfucbT->ifmp, pfucbT->u.pfcb->PgnoOE(), 2, NULL, NULL, bfprfDefault, ppib->BfpriPriority( pfucbT->ifmp ), *tcScope );
}
}
iext = 0;
if ( FSPOwnedExtent( fSPExtents ) )
{
Assert( NULL != pcpgOwnExtTotal );
if ( FSPIIsSmall( pfucbT->u.pfcb ) )
{
SPACE_HEADER *psph;
if( pcprintf )
{
(*pcprintf)( "\n%s: OWNEXT: single extent\n", SzNameOfTable( pfucbT ) );
}
Assert( pfucbT->pcsrRoot != pcsrNil );
Assert( pfucbT->pcsrRoot->Pgno() == PgnoFDP( pfucb ) );
Assert( pfucbT->pcsrRoot->FLatched() );
Assert( !FFUCBSpace( pfucbT ) );
NDGetExternalHeader( pfucbT, pfucbT->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucbT->kdfCurr.data.Cb() );
psph = reinterpret_cast <SPACE_HEADER *> ( pfucbT->kdfCurr.data.Pv() );
*pcpgOwnExtTotal = psph->CpgPrimary();
if ( fExtentList )
{
Assert( iext + cextSentinelsRemaining <= cext );
if ( iext + cextSentinelsRemaining < cext )
{
rgext[iext].pgnoLastInExtent = PgnoFDP( pfucbT ) + psph->CpgPrimary() - 1;
rgext[iext].cpgExtent = psph->CpgPrimary();
iext++;
}
Assert( iext + cextSentinelsRemaining <= cext );
rgext[iext].pgnoLastInExtent = pgnoNull;
rgext[iext].cpgExtent = 0;
iext++;
Assert( cextSentinelsRemaining > 0 );
cextSentinelsRemaining--;
if ( iext == cext )
{
Assert( !FSPAvailExtent( fSPExtents ) );
Assert( 0 == cextSentinelsRemaining );
}
else
{
Assert( iext < cext );
Assert( iext + cextSentinelsRemaining <= cext );
}
}
}
else
{
FUCB *pfucbOE = pfucbNil;
Call( ErrSPIOpenOwnExt( ppib, pfucbT->u.pfcb, &pfucbOE ) );
if( pcprintf )
{
(*pcprintf)( "\n%s: OWNEXT\n", SzNameOfTable( pfucbT ) );
}
err = ErrSPIGetInfo(
pfucbOE,
pcpgOwnExtTotal,
NULL,
NULL,
&iext,
cext,
rgext,
&cextSentinelsRemaining,
pcprintf );
Assert( pfucbOE != pfucbNil );
BTClose( pfucbOE );
Call( err );
}
}
if ( FSPAvailExtent( fSPExtents ) )
{
Assert( NULL != pcpgAvailExtTotal );
Assert( !fExtentList || 1 == cextSentinelsRemaining );
if ( FSPIIsSmall( pfucbT->u.pfcb ) )
{
SPACE_HEADER *psph;
if( pcprintf )
{
(*pcprintf)( "\n%s: AVAILEXT: single extent\n", SzNameOfTable( pfucbT ) );
}
Assert( pfucbT->pcsrRoot != pcsrNil );
Assert( pfucbT->pcsrRoot->Pgno() == PgnoFDP( pfucb ) );
Assert( pfucbT->pcsrRoot->FLatched() );
Assert( !FFUCBSpace( pfucbT ) );
NDGetExternalHeader( pfucbT, pfucbT->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucbT->kdfCurr.data.Cb() );
psph = reinterpret_cast <SPACE_HEADER *> ( pfucbT->kdfCurr.data.Pv() );
*pcpgAvailExtTotal = 0;
PGNO pgnoT = PgnoFDP( pfucbT ) + 1;
CPG cpgPrimarySeen = 1;
PGNO pgnoPrevAvail = pgnoNull;
UINT rgbitT;
for ( rgbitT = 0x00000001;
rgbitT != 0 && cpgPrimarySeen < psph->CpgPrimary();
cpgPrimarySeen++, pgnoT++, rgbitT <<= 1 )
{
Assert( pgnoT <= PgnoFDP( pfucbT ) + cpgSmallSpaceAvailMost );
if ( rgbitT & psph->RgbitAvail() )
{
(*pcpgAvailExtTotal)++;
if ( fExtentList )
{
Assert( iext + cextSentinelsRemaining <= cext );
if ( pgnoT == pgnoPrevAvail + 1 )
{
Assert( iext > 0 );
const INT iextPrev = iext - 1;
Assert( pgnoNull != pgnoPrevAvail );
Assert( pgnoPrevAvail == rgext[iextPrev].PgnoLast() );
rgext[iextPrev].pgnoLastInExtent = pgnoT;
rgext[iextPrev].cpgExtent++;
Assert( rgext[iextPrev].PgnoLast() - rgext[iextPrev].CpgExtent()
>= PgnoFDP( pfucbT ) );
pgnoPrevAvail = pgnoT;
}
else if ( iext + cextSentinelsRemaining < cext )
{
rgext[iext].pgnoLastInExtent = pgnoT;
rgext[iext].cpgExtent = 1;
iext++;
Assert( iext + cextSentinelsRemaining <= cext );
pgnoPrevAvail = pgnoT;
}
}
}
}
if ( psph->CpgPrimary() > cpgSmallSpaceAvailMost + 1 )
{
Assert( cpgSmallSpaceAvailMost + 1 == cpgPrimarySeen );
const CPG cpgRemaining = psph->CpgPrimary() - ( cpgSmallSpaceAvailMost + 1 );
(*pcpgAvailExtTotal) += cpgRemaining;
if ( fExtentList )
{
Assert( iext + cextSentinelsRemaining <= cext );
const PGNO pgnoLastOfRemaining = PgnoFDP( pfucbT ) + psph->CpgPrimary() - 1;
if ( pgnoLastOfRemaining - cpgRemaining == pgnoPrevAvail )
{
Assert( iext > 0 );
const INT iextPrev = iext - 1;
Assert( pgnoNull != pgnoPrevAvail );
Assert( pgnoPrevAvail == rgext[iextPrev].PgnoLast() );
rgext[iextPrev].pgnoLastInExtent = pgnoLastOfRemaining;
rgext[iextPrev].cpgExtent += cpgRemaining;
Assert( rgext[iextPrev].PgnoLast() - rgext[iextPrev].CpgExtent()
>= PgnoFDP( pfucbT ) );
}
else if ( iext + cextSentinelsRemaining < cext )
{
rgext[iext].pgnoLastInExtent = pgnoLastOfRemaining;
rgext[iext].cpgExtent = cpgRemaining;
iext++;
Assert( iext + cextSentinelsRemaining <= cext );
}
}
}
if ( fExtentList )
{
Assert( iext < cext );
rgext[iext].pgnoLastInExtent = pgnoNull;
rgext[iext].cpgExtent = 0;
iext++;
Assert( cextSentinelsRemaining > 0 );
cextSentinelsRemaining--;
Assert( iext + cextSentinelsRemaining <= cext );
}
}
else
{
FUCB *pfucbAE = pfucbNil;
Call( ErrSPIOpenAvailExt( ppib, pfucbT->u.pfcb, &pfucbAE ) );
if( pcprintf )
{
(*pcprintf)( "\n%s: AVAILEXT\n", SzNameOfTable( pfucbT ) );
}
FUCB *pfucbOE = pfucbNil;
err = ErrSPIOpenOwnExt( ppib, pfucbT->u.pfcb, &pfucbOE );
if ( err >= JET_errSuccess )
{
err = ErrSPIGetSPBufUnlatched( pfucbOE, &spbufOnOE );
}
if ( pfucbOE != pfucbNil )
{
BTClose( pfucbOE );
}
if ( err >= JET_errSuccess )
{
err = ErrSPIGetSPBufUnlatched( pfucbAE, &spbufOnAE );
}
SPDumpSplitBufExtent( pcprintf, SzNameOfTable( pfucbAE ), "OE", pfucbAE->u.pfcb->PgnoOE(), &spbufOnOE );
SPDumpSplitBufExtent( pcprintf, SzNameOfTable( pfucbAE ), "AE", pfucbAE->u.pfcb->PgnoAE(), &spbufOnAE );
if ( err >= JET_errSuccess )
{
err = ErrSPIGetInfo(
pfucbAE,
pcpgAvailExtTotal,
pcpgReservedExtTotal,
pcpgShelvedExtTotal,
&iext,
cext,
rgext,
&cextSentinelsRemaining,
pcprintf );
const CPG cpgSplitBufferReserved = spbufOnOE.CpgBuffer1() +
spbufOnOE.CpgBuffer2() +
spbufOnAE.CpgBuffer1() +
spbufOnAE.CpgBuffer2();
if ( FSPAvailExtent( fSPExtents ) )
{
Assert( NULL != pcpgAvailExtTotal );
*pcpgAvailExtTotal += cpgSplitBufferReserved;
}
if ( FSPReservedExtent( fSPExtents ) )
{
Assert( NULL != pcpgReservedExtTotal );
*pcpgReservedExtTotal += cpgSplitBufferReserved;
}
}
Assert( pfucbAE != pfucbNil );
BTClose( pfucbAE );
Call( err );
}
Assert( !FSPOwnedExtent( fSPExtents )
|| ( *pcpgAvailExtTotal <= *pcpgOwnExtTotal ) );
Assert( !FSPReservedExtent( fSPExtents )
|| ( *pcpgReservedExtTotal <= *pcpgAvailExtTotal ) );
}
Assert( 0 == cextSentinelsRemaining );
HandleError:
Expected( pfucbNil != pfucbT );
if ( pfucbT != pfucbNil )
{
pfucbT->pcsrRoot = pcsrNil;
BTClose( pfucbT );
}
return err;
}
ERR ErrSPGetExtentInfo(
_Inout_ PIB * ppib,
_In_ const IFMP ifmp,
_Inout_ FUCB * pfucb,
_In_ const ULONG fSPExtents,
_Out_ ULONG * pulExtentList,
_Deref_post_cap_(*pulExtentList) BTREE_SPACE_EXTENT_INFO ** pprgExtentList )
{
ERR err = JET_errSuccess;
BTREE_SPACE_EXTENT_INFO * prgext = NULL;
FUCB * pfucbT = pfucbNil;
if ( !( FSPOwnedExtent( fSPExtents ) || FSPAvailExtent( fSPExtents ) ) )
{
return ErrERRCheck( JET_errInvalidParameter );
}
Assert( ( fSPExtents & ~( fSPOwnedExtent | fSPAvailExtent ) ) == 0 );
if ( pfucbNil == pfucb )
{
err = ErrBTOpen( ppib, pgnoSystemRoot, ifmp, &pfucbT );
}
else
{
err = ErrBTOpen( ppib, pfucb->u.pfcb, &pfucbT );
}
CallR( err );
Assert( pfucbNil != pfucbT );
PIBTraceContextScope tcScope = ppib->InitTraceContextScope( );
tcScope->nParentObjectClass = TceFromFUCB( pfucbT );
tcScope->SetDwEngineObjid( ObjidFDP( pfucbT ) );
tcScope->iorReason.SetIort( iortSpace );
Call( ErrBTIGotoRoot( pfucbT, latchReadTouch ) );
Assert( pcsrNil == pfucbT->pcsrRoot );
pfucbT->pcsrRoot = Pcsr( pfucbT );
if ( !pfucbT->u.pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucbT, fTrue );
if( !FSPIIsSmall( pfucbT->u.pfcb ) )
{
BFPrereadPageRange( pfucbT->ifmp, pfucbT->u.pfcb->PgnoOE(), 2, bfprfDefault, ppib->BfpriPriority( pfucbT->ifmp ), *tcScope );
}
}
ULONG cextMax = 10;
ULONG cextMac = 0;
Alloc( prgext = new BTREE_SPACE_EXTENT_INFO[cextMax] );
memset( prgext, 0, sizeof(BTREE_SPACE_EXTENT_INFO)*cextMax );
if ( FSPOwnedExtent( fSPExtents ) )
{
Assert( !FSPAvailExtent( fSPExtents ) );
if ( FSPIIsSmall( pfucbT->u.pfcb ) )
{
SPACE_HEADER *psph;
Assert( pfucbT->pcsrRoot != pcsrNil );
Assert( pfucbT->pcsrRoot->Pgno() == PgnoFDP( pfucb ) );
Assert( pfucbT->pcsrRoot->FLatched() );
Assert( !FFUCBSpace( pfucbT ) );
NDGetExternalHeader( pfucbT, pfucbT->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucbT->kdfCurr.data.Cb() );
psph = reinterpret_cast <SPACE_HEADER *> ( pfucbT->kdfCurr.data.Pv() );
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::PrimaryExt, PgnoFDP( pfucb ) + psph->CpgPrimary() - 1, psph->CpgPrimary(), PgnoFDP( pfucb ) ) );
}
else
{
FUCB *pfucbOE = pfucbNil;
Call( ErrSPIOpenOwnExt( ppib, pfucbT->u.pfcb, &pfucbOE ) );
Call( ErrSPIExtGetExtentListInfo( pfucbOE, &prgext, &cextMax, &cextMac ) );
Assert( pfucbOE != pfucbNil );
BTClose( pfucbOE );
Call( err );
}
*pulExtentList = cextMac;
*pprgExtentList = prgext;
}
if ( FSPAvailExtent( fSPExtents ) )
{
Assert( !FSPOwnedExtent( fSPExtents ) );
SPLIT_BUFFER spbufOnOE;
SPLIT_BUFFER spbufOnAE;
memset( (void*)&spbufOnOE, 0, sizeof(spbufOnOE) );
memset( (void*)&spbufOnAE, 0, sizeof(spbufOnAE) );
if ( FSPIIsSmall( pfucbT->u.pfcb ) )
{
SPACE_HEADER *psph;
Assert( pfucbT->pcsrRoot != pcsrNil );
Assert( pfucbT->pcsrRoot->Pgno() == PgnoFDP( pfucb ) );
Assert( pfucbT->pcsrRoot->FLatched() );
Assert( !FFUCBSpace( pfucbT ) );
NDGetExternalHeader( pfucbT, pfucbT->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucbT->kdfCurr.data.Cb() );
psph = reinterpret_cast <SPACE_HEADER *> ( pfucbT->kdfCurr.data.Pv() );
PGNO pgnoT = PgnoFDP( pfucbT ) + 1;
CPG cpgPrimarySeen = 1;
UINT rgbitT;
CPG cpgAccum = 0;
ULONG pgnoLastAccum = 0;
for ( rgbitT = 0x00000001;
rgbitT != 0 && cpgPrimarySeen < psph->CpgPrimary();
cpgPrimarySeen++, pgnoT++, rgbitT <<= 1 )
{
Assert( pgnoT <= PgnoFDP( pfucbT ) + cpgSmallSpaceAvailMost );
if ( rgbitT & psph->RgbitAvail() )
{
Assert( pgnoNull != pgnoT );
Assert( cextMac == 0 || prgext[cextMac-1].pgnoLast - prgext[cextMac-1].cpgExtent >= PgnoFDP( pfucbT ) );
Assert( cpgAccum < cpgPrimarySeen );
Assert( pgnoLastAccum == 0 || pgnoLastAccum + 1 == pgnoT );
cpgAccum++;
pgnoLastAccum = pgnoT;
}
else
{
if ( cpgAccum )
{
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::PrimaryExt, pgnoLastAccum, cpgAccum, PgnoFDP( pfucb ) ) );
}
cpgAccum = 0;
pgnoLastAccum = 0;
}
}
if ( psph->CpgPrimary() > cpgSmallSpaceAvailMost + 1 )
{
Assert( cpgSmallSpaceAvailMost + 1 == cpgPrimarySeen );
const CPG cpgRemaining = psph->CpgPrimary() - ( cpgSmallSpaceAvailMost + 1 );
const PGNO pgnoLastOfRemaining = PgnoFDP( pfucbT ) + psph->CpgPrimary() - 1;
if ( cextMac > 0 )
{
Assert( pgnoLastAccum == prgext[cextMac-1].pgnoLast );
Assert( prgext[cextMac-1].pgnoLast - prgext[cextMac-1].cpgExtent >= PgnoFDP( pfucbT ) );
}
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::PrimaryExt, pgnoLastOfRemaining, cpgRemaining, PgnoFDP( pfucb ) ) );
}
else if ( cpgAccum )
{
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::PrimaryExt, pgnoLastAccum, cpgAccum, PgnoFDP( pfucb ) ) );
}
}
else
{
FUCB *pfucbAE = pfucbNil;
Call( ErrSPIOpenAvailExt( ppib, pfucbT->u.pfcb, &pfucbAE ) );
FUCB *pfucbOE = pfucbNil;
err = ErrSPIOpenOwnExt( ppib, pfucbT->u.pfcb, &pfucbOE );
if ( err >= JET_errSuccess )
{
err = ErrSPIGetSPBufUnlatched( pfucbOE, &spbufOnOE );
}
if ( pfucbOE != pfucbNil )
{
BTClose( pfucbOE );
}
if ( err >= JET_errSuccess )
{
err = ErrSPIGetSPBufUnlatched( pfucbAE, &spbufOnAE );
}
if ( spbufOnOE.CpgBuffer1() )
{
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::OwnedTreeAvail, spbufOnOE.PgnoLastBuffer1(), spbufOnOE.CpgBuffer1(), pfucbAE->u.pfcb->PgnoOE() ) );
}
if ( spbufOnOE.CpgBuffer2() )
{
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::OwnedTreeAvail, spbufOnOE.PgnoLastBuffer2(), spbufOnOE.CpgBuffer2(), pfucbAE->u.pfcb->PgnoOE() ) );
}
if ( spbufOnAE.CpgBuffer1() )
{
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::AvailTreeAvail, spbufOnAE.PgnoLastBuffer1(), spbufOnAE.CpgBuffer1(), pfucbAE->u.pfcb->PgnoAE() ) );
}
if ( spbufOnAE.CpgBuffer2() )
{
Call( ErrSPIAddExtentInfo( &prgext, &cextMax, &cextMac, spp::AvailTreeAvail, spbufOnAE.PgnoLastBuffer2(), spbufOnAE.CpgBuffer2(), pfucbAE->u.pfcb->PgnoAE() ) );
}
if ( err >= JET_errSuccess )
{
Call( ErrSPIExtGetExtentListInfo( pfucbAE, &prgext, &cextMax, &cextMac ) );
}
Assert( pfucbAE != pfucbNil );
BTClose( pfucbAE );
Call( err );
for( ULONG iext = 0; iext < cextMac; iext++ )
{
BTREE_SPACE_EXTENT_INFO * pext = &prgext[iext];
Assert( pext->iPool != (ULONG)spp::OwnedTreeAvail || iext <= 4 );
Assert( pext->iPool != (ULONG)spp::AvailTreeAvail || iext <= 4 );
if ( pext->iPool == (ULONG)spp::PrimaryExt )
{
Assert( iext == 0 || prgext[iext-1].iPool != (ULONG)spp::AvailExtLegacyGeneralPool );
Assert( iext == 0 || prgext[iext-1].iPool != (ULONG)spp::ContinuousPool );
Assert( prgext[iext-1].iPool != (ULONG)spp::ShelvedPool );
}
}
}
*pulExtentList = cextMac;
*pprgExtentList = prgext;
}
HandleError:
Expected( pfucbNil != pfucbT );
if ( pfucbT != pfucbNil )
{
pfucbT->pcsrRoot = pcsrNil;
BTClose( pfucbT );
}
return err;
}
LOCAL ERR ErrSPITrimOneAvailableExtent(
_In_ FUCB* pfucb,
_Out_ CPG* pcpgTotalAvail,
_Out_ CPG* pcpgTotalAvailSparseBefore,
_Out_ CPG* pcpgTotalAvailSparseAfter,
_In_ CPRINTF* const pcprintf )
{
ERR err;
DIB dib;
Assert( pcprintf );
CPG cpgAvailTotal = 0;
CPG cpgAvailSparseBefore = 0;
CPG cpgAvailSparseAfter = 0;
*pcpgTotalAvail = 0;
*pcpgTotalAvailSparseBefore = 0;
*pcpgTotalAvailSparseAfter = 0;
FUCBSetSequential( pfucb );
FUCBSetPrereadForward( pfucb, cpgPrereadSequential );
dib.dirflag = fDIRNull;
dib.pos = posFirst;
Assert( FFUCBSpace( pfucb ) );
err = ErrBTDown( pfucb, &dib, latchReadNoTouch );
if ( err != JET_errRecordNotFound )
{
Call( err );
forever
{
const CSPExtentInfo cspext( pfucb );
Expected( ( cspext.SppPool() == spp::AvailExtLegacyGeneralPool ) || ( cspext.SppPool() == spp::ShelvedPool ) );
if ( cspext.SppPool() != spp::ShelvedPool )
{
CPG cpgSparseBeforeThisExtent = 0;
CPG cpgSparseAfterThisExtent = 0;
QWORD ibStartZeroes = 0;
QWORD cbZeroLength = 0;
PGNO pgnoStartRegionAligned = 0;
CPG cpgRegionAligned = 0;
if ( !cspext.FEmptyExtent() )
{
Call( ErrIOTrimNormalizeOffsetsAndPgnos(
pfucb->ifmp,
cspext.PgnoFirst(),
cspext.CpgExtent(),
&ibStartZeroes,
&cbZeroLength,
&pgnoStartRegionAligned,
&cpgRegionAligned ) );
}
if ( cpgRegionAligned != 0 )
{
Assert( !cspext.FEmptyExtent() );
const PGNO pgnoEndRegionAligned = cspext.FEmptyExtent() ? 0 : pgnoStartRegionAligned + cpgRegionAligned - 1;
if ( !cspext.FEmptyExtent() )
{
}
(*pcprintf)( "%30s: %s[%5d]:\t%6d-%6d (%3d);\tA%6d-%6d (%3d) %s%s",
SzNameOfTable( pfucb ),
SzSpaceTreeType( pfucb ),
Pcsr( pfucb )->Pgno(),
cspext.FEmptyExtent() ? 0 : cspext.PgnoFirst(),
cspext.FEmptyExtent() ? cspext.PgnoMarker() : cspext.PgnoLast(),
cspext.CpgExtent(),
pgnoStartRegionAligned,
pgnoEndRegionAligned,
cpgRegionAligned,
FNDDeleted( pfucb->kdfCurr ) ? " (DEL)" : "",
( cspext.ErrCheckCorrupted( ) < JET_errSuccess ) ? " (COR)" : ""
);
(*pcprintf)( " cpgSparseBefore: %3d", cpgSparseBeforeThisExtent );
{
PIB pibFake;
pibFake.m_pinst = g_rgfmp[ pfucb->ifmp ].Pinst();
Call( ErrSPITrimRegion( pfucb->ifmp, &pibFake, pgnoEndRegionAligned, cpgRegionAligned, &cpgSparseBeforeThisExtent, &cpgSparseAfterThisExtent ) );
const CPG cpgSparseNewlyTrimmed = cpgSparseAfterThisExtent - cpgSparseBeforeThisExtent;
(*pcprintf)( " cpgSparseAfter: %3d cpgSparseNew: %3d", cpgSparseAfterThisExtent, cpgSparseNewlyTrimmed );
cpgAvailSparseBefore += cpgSparseBeforeThisExtent;
cpgAvailSparseAfter += cpgSparseAfterThisExtent;
}
(*pcprintf)( "\n" );
}
cpgAvailTotal += cspext.CpgExtent();
}
err = ErrBTNext( pfucb, fDIRNull );
if ( err < 0 )
{
if ( err != JET_errNoCurrentRecord )
{
goto HandleError;
}
break;
}
}
}
*pcpgTotalAvail += cpgAvailTotal;
*pcpgTotalAvailSparseBefore += cpgAvailSparseBefore;
*pcpgTotalAvailSparseAfter += cpgAvailSparseAfter;
if( pcprintf )
{
const CPG cpgSparseNewlyTrimmed = cpgAvailSparseAfter - cpgAvailSparseBefore;
(*pcprintf)( "%s:\t%d trimmed (before), %d trimmed (after), %d pages newly trimmed.\n",
SzNameOfTable( pfucb ),
cpgAvailSparseBefore,
cpgAvailSparseAfter,
cpgSparseNewlyTrimmed );
}
err = JET_errSuccess;
HandleError:
return err;
}
ERR ErrSPTrimRootAvail(
_In_ PIB *ppib,
_In_ const IFMP ifmp,
_In_ CPRINTF * const pcprintf,
_Out_opt_ CPG * const pcpgTrimmed )
{
ERR err;
CPG cpgAvailExtTotal = 0;
CPG cpgAvailExtTotalSparseBefore = 0;
CPG cpgAvailExtTotalSparseAfter = 0;
FUCB *pfucbT = pfucbNil;
FUCB *pfucbAE = pfucbNil;
PIBTraceContextScope tcScope = ppib->InitTraceContextScope();
tcScope->iorReason.SetIort( iortSpace );
SPLIT_BUFFER spbufOnAE;
memset( (void*)&spbufOnAE, 0, sizeof(spbufOnAE) );
Call( ErrBTIOpenAndGotoRoot( ppib, pgnoSystemRoot, ifmp, &pfucbT ) );
AssertSPIPfucbOnRoot( pfucbT );
if ( !pfucbT->u.pfcb->FSpaceInitialized() )
{
SPIInitFCB( pfucbT, fTrue );
if( !FSPIIsSmall( pfucbT->u.pfcb ) )
{
BFPrereadPageRange( pfucbT->ifmp, pfucbT->u.pfcb->PgnoAE(), 2, bfprfDefault, ppib->BfpriPriority( pfucbT->ifmp ), *tcScope );
}
}
AssertSz( !FSPIIsSmall( pfucbT->u.pfcb ), "Database root table should not be Small Space!" );
Call( ErrSPIOpenAvailExt( ppib, pfucbT->u.pfcb, &pfucbAE ) );
Call( ErrSPIGetSPBufUnlatched( pfucbAE, &spbufOnAE ) );
Call( ErrSPITrimOneAvailableExtent(
pfucbAE,
&cpgAvailExtTotal,
&cpgAvailExtTotalSparseBefore,
&cpgAvailExtTotalSparseAfter,
pcprintf ) );
Assert( cpgAvailExtTotalSparseBefore <= cpgAvailExtTotal );
Assert( cpgAvailExtTotalSparseBefore <= cpgAvailExtTotalSparseAfter );
Assert( cpgAvailExtTotalSparseAfter <= cpgAvailExtTotal );
HandleError:
if ( pfucbAE != pfucbNil )
{
BTClose( pfucbAE );
}
Assert( pfucbNil != pfucbT || err < JET_errSuccess );
if ( pfucbT != pfucbNil )
{
pfucbT->pcsrRoot = pcsrNil;
BTClose( pfucbT );
}
if ( pcpgTrimmed != NULL )
{
*pcpgTrimmed = 0;
if ( ( err >= JET_errSuccess ) &&
( cpgAvailExtTotalSparseBefore > cpgAvailExtTotalSparseAfter ) )
{
*pcpgTrimmed = cpgAvailExtTotalSparseBefore - cpgAvailExtTotalSparseAfter;
}
}
return err;
}
ERR ErrSPDummyUpdate( FUCB * pfucb )
{
ERR err;
SPACE_HEADER sph;
DATA data;
Assert( !Pcsr( pfucb )->FLatched() );
CallR( ErrBTIGotoRoot( pfucb, latchRIW ) );
NDGetExternalHeader( pfucb, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
UtilMemCpy( &sph, pfucb->kdfCurr.data.Pv(), sizeof(sph) );
Pcsr( pfucb )->UpgradeFromRIWLatch();
data.SetPv( &sph );
data.SetCb( sizeof(sph) );
err = ErrNDSetExternalHeader( pfucb, &data, fDIRNull, noderfSpaceHeader );
BTUp( pfucb );
return err;
}
#ifdef SPACECHECK
LOCAL ERR ErrSPIValidFDP( PIB *ppib, IFMP ifmp, PGNO pgnoFDP )
{
ERR err;
FUCB *pfucb = pfucbNil;
FUCB *pfucbOE = pfucbNil;
DIB dib;
Assert( pgnoFDP != pgnoNull );
Call( ErrBTOpen( ppib, pgnoFDP, ifmp, &pfucb ) );
Assert( pfucbNil != pfucb );
Assert( pfucb->u.pfcb->FInitialized() );
if ( !FSPIIsSmall( pfucb->u.pfcb ) )
{
Call( ErrSPIOpenOwnExt( ppib, pfucb->u.pfcb, &pfucbOE ) );
const CSPExtentKeyBM spFindOwnedExtOfFDP( SPEXTKEY::fSPExtentTypeOE, pgnoFDP );
dib.pos = posDown;
dib.pbm = spFindOwnedExtOfFDP.Pbm( pfucbOE ) ;
dib.dirflag = fDIRNull;
Call( ErrBTDown( pfucbOE, &dib, latchReadTouch ) );
if ( err == wrnNDFoundGreater )
{
Call( ErrBTGet( pfucbOE ) );
}
const CSPExtentInfo spOwnedExtOfFDP( pfucbOE );
Assert( spOwnedExtOfFDP.FValidExtent() );
Assert( pgnoFDP == spOwnedExtOfFDP.PgnoFirst() );
}
HandleError:
if ( pfucbOE != pfucbNil )
BTClose( pfucbOE );
if ( pfucb != pfucbNil )
BTClose( pfucb );
return err;
}
LOCAL ERR ErrSPIWasAlloc(
FUCB *pfucb,
PGNO pgnoFirst,
CPG cpgSize )
{
ERR err;
FUCB *pfucbOE = pfucbNil;
FUCB *pfucbAE = pfucbNil;
DIB dib;
CSPExtentKeyBM spFindExt;
CSPExtentInfo spExtInfo;
const PGNO pgnoLast = pgnoFirst + cpgSize - 1;
if ( FSPIIsSmall( pfucb->u.pfcb ) )
{
SPACE_HEADER *psph;
UINT rgbitT;
INT iT;
AssertSPIPfucbOnRoot( pfucb );
NDGetExternalHeader( pfucb, pfucb->pcsrRoot, noderfSpaceHeader );
Assert( sizeof( SPACE_HEADER ) == pfucb->kdfCurr.data.Cb() );
psph = reinterpret_cast <SPACE_HEADER *> ( pfucb->kdfCurr.data.Pv() );
for ( rgbitT = 1, iT = 1;
iT < cpgSize && iT < cpgSmallSpaceAvailMost;
iT++ )
rgbitT = (rgbitT<<1) + 1;
Assert( pgnoFirst - PgnoFDP( pfucb ) < cpgSmallSpaceAvailMost );
if ( pgnoFirst != PgnoFDP( pfucb ) )
{
rgbitT <<= (pgnoFirst - PgnoFDP( pfucb ) - 1);
Assert( ( psph->RgbitAvail() & rgbitT ) == 0 );
}
goto HandleError;
}
Call( ErrSPIOpenOwnExt( pfucb->ppib, pfucb->u.pfcb, &pfucbOE ) );
spFindExt.SPExtentMakeKeyBM( SPEXTKEY::fSPExtentTypeOE, pgnoLast );
dib.pos = posDown;
dib.pbm = spFindExt.Pbm( pfucbOE );
dib.dirflag = fDIRNull;
Call( ErrBTDown( pfucbOE, &dib, latchReadNoTouch ) );
if ( err == wrnNDFoundLess )
{
Assert( fFalse );
Assert( Pcsr( pfucbOE )->Cpage().Clines() - 1 ==
Pcsr( pfucbOE )->ILine() );
Assert( pgnoNull != Pcsr( pfucbOE )->Cpage().PgnoNext() );
Call( ErrBTNext( pfucbOE, fDIRNull ) );
err = ErrERRCheck( wrnNDFoundGreater );
#ifdef DEBUG
const CSPExtentInfo spExt( pfucbOE );
Assert( spExt.PgnoLast() > pgnoLast );
#endif
}
if ( err == wrnNDFoundGreater )
{
Call( ErrBTGet( pfucbOE ) );
}
spExtInfo.Set( pfucbOE );
Assert( pgnoFirst >= spExtInfo.PgnoFirst() );
BTUp( pfucbOE );
EnforceSz( fFalse, "SpaceCheckNeedsFixingForPools" );
spFindExt.SPExtentMakeKeyBM( SPEXTKEY::fSPExtentTypeAE, pgnoLast );
dib.pos = posDown;
dib.pbm = spFindExt.Pbm( pfucbOE );
dib.dirflag = fDIRNull;
Call( ErrSPIOpenAvailExt( pfucb->ppib, pfucb->u.pfcb, &pfucbAE ) );
if ( ( err = ErrBTDown( pfucbAE, &dib, latchReadNoTouch ) ) < 0 )
{
if ( err == JET_errNoCurrentRecord )
{
err = JET_errSuccess;
goto HandleError;
}
goto HandleError;
}
Assert( err != JET_errSuccess );
if ( err == wrnNDFoundGreater )
{
Call( ErrBTNext( pfucbAE, fDIRNull ) );
const CSPExtentInfo spavailextNext( pfucbAE );
Assert( spavailextNext.CpgExtent() != 0 );
Assert( pgnoLast < spavailextNext.PgnoFirst() );
}
else
{
Assert( err == wrnNDFoundLess );
Call( ErrBTPrev( pfucbAE, fDIRNull ) );
const CSPExtentInfo spavailextPrev( pfucbAE );
Assert( pgnoFirst > spavailextPrev.PgnoLast() );
}
HandleError:
if ( pfucbOE != pfucbNil )
BTClose( pfucbOE );
if ( pfucbAE != pfucbNil )
BTClose( pfucbAE );
return JET_errSuccess;
}
#endif
const ULONG pctDoublingGrowth = 200;
CPG CpgSPIGetNextAlloc(
__in const FCB_SPACE_HINTS * const pfcbsh,
__in const CPG cpgPrevious
)
{
if ( pfcbsh->m_cpgMaxExtent != 0 &&
pfcbsh->m_cpgMinExtent == pfcbsh->m_cpgMaxExtent )
{
return pfcbsh->m_cpgMaxExtent;
}
CPG cpgNextExtent = cpgPrevious;
if ( pfcbsh->m_pctGrowth )
{
cpgNextExtent = max( cpgPrevious + 1, ( cpgPrevious * pfcbsh->m_pctGrowth ) / 100 );
Assert( cpgNextExtent != cpgPrevious );
}
cpgNextExtent = (CPG)UlBound( (ULONG)cpgNextExtent,
(ULONG)( pfcbsh->m_cpgMinExtent ? pfcbsh->m_cpgMinExtent : cpgNextExtent ),
(ULONG)( pfcbsh->m_cpgMaxExtent ? pfcbsh->m_cpgMaxExtent : cpgNextExtent ) );
Assert( cpgNextExtent >= 0 );
return cpgNextExtent;
}
#ifdef SPACECHECK
void SPCheckPrintMaxNumAllocs( const LONG cbPageSize )
{
JET_SPACEHINTS jsph = {
sizeof(JET_SPACEHINTS),
80,
0 ,
0x0, 0x0, 0x0, 0x0, 0x0,
80,
0 ,
0,
1 * 1024 * 1024 * 1024
};
FCB_SPACE_HINTS fcbshCheck = { 0 };
ULONG iLastAllocs = 0;
ULONG pct = 200;
for( ULONG cpg = 1; cpg < (ULONG) ( 16 * 1024 * 1024 / cbPageSize ); cpg++ )
{
jsph.cbInitial = cpg * cbPageSize;
for( ; pct >= 100; pct-- )
{
ULONG cpgNext = ( ( jsph.cbInitial / cbPageSize ) * ( pct ) ) / 100;
if ( cpgNext == ( jsph.cbInitial / cbPageSize ) )
{
pct++;
break;
}
}
jsph.ulGrowth = pct;
fcbshCheck.SetSpaceHints( &jsph, cbPageSize );
CPG cpgLast = fcbshCheck.m_cpgInitial;
ULONG iAlloc = 1;
for( ; iAlloc < (1024 * 1024 * 1024 + 1) ; )
{
iAlloc++;
cpgLast = CpgSPIGetNextAlloc( &fcbshCheck, cpgLast );
if ( cpgLast >= fcbshCheck.m_cpgMaxExtent )
{
break;
}
}
wprintf(L"\tCpgInit: %09d Min:%03d%% -> %d iAllocs\n", (ULONG)fcbshCheck.m_cpgInitial, (ULONG)fcbshCheck.m_pctGrowth, iAlloc );
if( fcbshCheck.m_cpgInitial > 104 )
{
wprintf( L" reached the turning point, bailing.\n" );
break;
}
iLastAllocs = iAlloc;
}
}
#endif
#if ( ESENT || !DEBUG )
static const TICK g_dtickTrimDBPeriod = 1000 * 60 * 60 * 24;
#else
static const TICK g_dtickTrimDBPeriod = 1 * 1000;
#endif
static TICK g_tickLastPeriodicTrimDB = 0;
static BOOL g_fSPTrimDBTaskScheduled = fFalse;
LOCAL ERR ErrSPITrimDBITaskPerIFMP( const IFMP ifmp )
{
ERR err = JET_errSuccess;
PIB* ppib = ppibNil;
WCHAR wsz[32];
const WCHAR* rgcwsz[] = { wsz };
CPG cpgTrimmed = 0;
#if DEBUG
static BOOL s_fLoggedStartEvent = fFalse;
static BOOL s_fLoggedStopNoActionEvent = fFalse;
#endif
OSTraceFMP( ifmp, JET_tracetagSpaceInternal, __FUNCTION__ );
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Running trim task for ifmp %d.", ifmp ) );
AssertSz( g_fPeriodicTrimEnabled, "Trim Task should never be run if the test hook wasn't enabled." );
AssertSz( !g_fRepair, "Trim Task should never be run during Repair." );
AssertSz( !g_rgfmp[ ifmp ].FReadOnlyAttach(), "Trim Task should not be run on a read-only database." );
AssertSz( !FFMPIsTempDB( ifmp ), "Trim task should not be run on temp databases." );
if ( PinstFromIfmp( ifmp )->FRecovering() )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trim will not run an in-recovery database." ) );
err = JET_errSuccess;
goto HandleError;
}
const ULONG dbstate = g_rgfmp[ ifmp ].Pdbfilehdr()->Dbstate();
if ( ( dbstate == JET_dbstateIncrementalReseedInProgress ) ||
( dbstate == JET_dbstateDirtyAndPatchedShutdown ) ||
( dbstate == JET_dbstateRevertInProgress ) )
{
AssertSz( fFalse, "Periodic trim should not take place during incremental reseed or revert." );
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trim will not run for a database in inc reseed or revert or dirty and patched shutdown status." ) );
err = JET_errSuccess;
goto HandleError;
}
#if DEBUG
if ( !s_fLoggedStartEvent )
#endif
{
UtilReportEvent(
eventInformation,
GENERAL_CATEGORY,
DB_TRIM_TASK_STARTED,
0,
NULL,
0,
NULL,
PinstFromIfmp( ifmp ) );
OnDebug( s_fLoggedStartEvent = fTrue );
}
if ( PinstFromIfmp( ifmp )->m_pbackup->FBKBackupInProgress() )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trim will not run when there is backup in progress." ) );
Error( ErrERRCheck( JET_errBackupInProgress ) );
}
Call( ErrPIBBeginSession( PinstFromIfmp( ifmp ), &ppib, procidNil, fFalse ) );
if ( ( ( GrbitParam( g_rgfmp[ ifmp ].Pinst(), JET_paramEnableShrinkDatabase ) & JET_bitShrinkDatabaseRealtime ) != 0 ) &&
g_rgfmp[ ifmp ].FTrimSupported() )
{
Call( ErrSPTrimRootAvail( ppib, ifmp, CPRINTFNULL::PcprintfInstance(), &cpgTrimmed ) );
}
HandleError:
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Trim task for ifmp %d finished with result %d (0x%x).", ifmp, err, err ) );
if ( ppibNil != ppib )
{
PIBEndSession( ppib );
}
if ( err < JET_errSuccess )
{
OSStrCbFormatW( wsz, sizeof(wsz), L"%d", err );
UtilReportEvent(
eventError,
GENERAL_CATEGORY,
DB_TRIM_TASK_FAILED,
_countof(rgcwsz),
rgcwsz,
0,
NULL,
PinstFromIfmp( ifmp ) );
}
else
{
if ( cpgTrimmed > 0 )
{
OSStrCbFormatW( wsz, sizeof(wsz), L"%d", cpgTrimmed );
UtilReportEvent(
eventInformation,
GENERAL_CATEGORY,
DB_TRIM_TASK_SUCCEEDED,
_countof(rgcwsz),
rgcwsz,
0,
NULL,
PinstFromIfmp( ifmp ) );
}
else
{
#if DEBUG
if ( !s_fLoggedStopNoActionEvent )
#endif
{
UtilReportEvent(
eventInformation,
GENERAL_CATEGORY,
DB_TRIM_TASK_NO_TRIM,
0,
NULL,
0,
NULL,
PinstFromIfmp( ifmp ) );
OnDebug( s_fLoggedStopNoActionEvent = fTrue );
}
}
}
return err;
}
LOCAL VOID SPITrimDBITask( VOID*, VOID* )
{
BOOL fReschedule = fFalse;
Assert( g_fSPTrimDBTaskScheduled );
OSTrace( JET_tracetagSpaceInternal, __FUNCTION__ );
g_tickLastPeriodicTrimDB = TickOSTimeCurrent();
if ( g_fRepair )
{
OSTrace( JET_tracetagSpaceInternal,
OSFormat( "We're in repair - JetDBUtilities is being executed. Aborting trim." ) );
goto FinishTask;
}
FMP::EnterFMPPoolAsWriter();
for ( IFMP ifmp = FMP::IfmpMinInUse(); ifmp <= FMP::IfmpMacInUse(); ifmp++ )
{
if ( FFMPIsTempDB( ifmp ) || !g_rgfmp[ifmp].FInUse() )
{
continue;
}
g_rgfmp[ ifmp ].GetPeriodicTrimmingDBLatch();
FMP::LeaveFMPPoolAsWriter();
if ( !g_rgfmp[ ifmp ].FScheduledPeriodicTrim() || g_rgfmp[ ifmp ].FDontStartTrimTask() )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trimming is off for this IFMP. Skipping." ) );
g_rgfmp[ ifmp ].ReleasePeriodicTrimmingDBLatch();
FMP::EnterFMPPoolAsWriter();
continue;
}
fReschedule = fTrue;
(void)ErrSPITrimDBITaskPerIFMP( ifmp );
g_rgfmp[ ifmp ].ReleasePeriodicTrimmingDBLatch();
FMP::EnterFMPPoolAsWriter();
}
FMP::LeaveFMPPoolAsWriter();
FinishTask:
if ( fReschedule )
{
OSTimerTaskScheduleTask( g_posttSPITrimDBITask, NULL, g_dtickTrimDBPeriod, g_dtickTrimDBPeriod );
}
else
{
g_semSPTrimDBScheduleCancel.Acquire();
g_fSPTrimDBTaskScheduled = fFalse;
g_semSPTrimDBScheduleCancel.Release();
}
Assert( !FMP::FWriterFMPPool() );
}
VOID SPTrimDBTaskStop( INST * pinst, const WCHAR * cwszDatabaseFullName )
{
Assert( g_fPeriodicTrimEnabled );
FMP::EnterFMPPoolAsWriter();
for ( DBID dbid = dbidUserLeast; dbid < dbidMax; dbid++ )
{
const IFMP ifmp = pinst->m_mpdbidifmp[ dbid ];
if ( ifmp >= g_ifmpMax ||
!g_rgfmp[ifmp].FInUse() )
{
continue;
}
if ( NULL != cwszDatabaseFullName &&
( g_rgfmp[ifmp].Pinst() != pinst || UtilCmpFileName( cwszDatabaseFullName, g_rgfmp[ifmp].WszDatabaseName() ) != 0 ) )
{
continue;
}
FMP::LeaveFMPPoolAsWriter();
g_rgfmp[ifmp].GetPeriodicTrimmingDBLatch();
g_rgfmp[ifmp].SetFDontStartTrimTask();
g_rgfmp[ifmp].ResetScheduledPeriodicTrim();
g_rgfmp[ifmp].ReleasePeriodicTrimmingDBLatch();
FMP::EnterFMPPoolAsWriter();
}
FMP::LeaveFMPPoolAsWriter();
}
ERR ErrSPTrimDBTaskInit( const IFMP ifmp )
{
ERR err = JET_errSuccess;
Assert( g_fPeriodicTrimEnabled );
if ( g_rgfmp[ ifmp ].FReadOnlyAttach() )
{
AssertSz( fFalse, "Periodic trim should not be set up for read-only databases." );
Error( ErrERRCheck( JET_errDatabaseFileReadOnly ) );
}
if ( g_fRepair || FFMPIsTempDB( ifmp ) )
{
AssertSz( fFalse, "Periodic trim should not be set up for a database in repair or for the temp db." );
Error( ErrERRCheck( JET_errInvalidDatabaseId ) );
}
if ( ( GrbitParam( g_rgfmp[ ifmp ].Pinst(), JET_paramEnableShrinkDatabase ) & JET_bitShrinkDatabasePeriodically ) == 0 )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trim is not enabled. Will not schedule the trim task." ) );
err = JET_errSuccess;
goto HandleError;
}
if ( BoolParam( JET_paramEnableViewCache ) )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trimming cannot be enabled for view cache. Will not schedule the trimming task." ) );
err = JET_errSuccess;
goto HandleError;
}
#ifdef MINIMAL_FUNCTIONALITY
#else
g_rgfmp[ ifmp ].GetPeriodicTrimmingDBLatch();
if ( g_rgfmp[ ifmp ].FDontStartTrimTask() )
{
OSTraceFMP( ifmp, JET_tracetagSpaceInternal,
OSFormat( "Periodic trimming is set so it should not start. Will not schedule the trim task." ) );
err = JET_errSuccess;
g_rgfmp[ ifmp ].ReleasePeriodicTrimmingDBLatch();
goto HandleError;
}
g_rgfmp[ ifmp ].SetScheduledPeriodicTrim();
g_rgfmp[ ifmp ].ReleasePeriodicTrimmingDBLatch();
g_semSPTrimDBScheduleCancel.Acquire();
Assert( g_semSPTrimDBScheduleCancel.CAvail() == 0 );
if ( !g_fSPTrimDBTaskScheduled )
{
g_fSPTrimDBTaskScheduled = fTrue;
OSTimerTaskScheduleTask( g_posttSPITrimDBITask, NULL, g_dtickTrimDBPeriod, g_dtickTrimDBPeriod );
}
Assert( g_semSPTrimDBScheduleCancel.CAvail() == 0 );
g_semSPTrimDBScheduleCancel.Release();
#endif
HandleError:
return err;
}
| 30.788451 | 206 | 0.548501 | [
"3d"
] |
5cc671535f7be9922ff5ef9760a30eb0e24b3c73 | 5,378 | cpp | C++ | test/conversion.cpp | ChasonTang/N-API | 4ab22f6b72e94c818673e536bf4cbb69409a643b | [
"Apache-2.0"
] | 20 | 2021-02-25T06:14:48.000Z | 2022-03-10T10:09:08.000Z | test/conversion.cpp | ChasonTang/N-API | 4ab22f6b72e94c818673e536bf4cbb69409a643b | [
"Apache-2.0"
] | 2 | 2021-08-06T11:12:32.000Z | 2021-09-09T10:03:03.000Z | test/conversion.cpp | ChasonTang/N-API | 4ab22f6b72e94c818673e536bf4cbb69409a643b | [
"Apache-2.0"
] | 2 | 2022-02-14T09:15:16.000Z | 2022-03-28T02:54:07.000Z | #include <test.h>
EXTERN_C_START
static NAPIValue toBool(NAPIEnv env, NAPICallbackInfo info)
{
size_t argc = 1;
NAPIValue args[1];
assert(napi_get_cb_info(env, info, &argc, args, nullptr, nullptr) == NAPICommonOK);
NAPIValue output;
assert(napi_coerce_to_bool(env, args[0], &output) == NAPIExceptionOK);
return output;
}
static NAPIValue toNumber(NAPIEnv env, NAPICallbackInfo info)
{
size_t argc = 1;
NAPIValue args[1];
assert(napi_get_cb_info(env, info, &argc, args, nullptr, nullptr) == NAPICommonOK);
NAPIValue output;
assert(napi_coerce_to_number(env, args[0], &output) == NAPIExceptionOK);
return output;
}
static NAPIValue toString(NAPIEnv env, NAPICallbackInfo info)
{
size_t argc = 1;
NAPIValue args[1];
assert(napi_get_cb_info(env, info, &argc, args, nullptr, nullptr) == NAPICommonOK);
NAPIValue output;
assert(napi_coerce_to_string(env, args[0], &output) == NAPIExceptionOK);
return output;
}
EXTERN_C_END
TEST_F(Test, Conversion)
{
NAPIValue toBoolValue, toNumberValue, toStringValue;
ASSERT_EQ(napi_create_function(globalEnv, nullptr, toBool, nullptr, &toBoolValue), NAPIExceptionOK);
ASSERT_EQ(napi_create_function(globalEnv, nullptr, toNumber, nullptr, &toNumberValue), NAPIExceptionOK);
ASSERT_EQ(napi_create_function(globalEnv, nullptr, toString, nullptr, &toStringValue), NAPIExceptionOK);
NAPIValue stringValue;
ASSERT_EQ(napi_create_string_utf8(globalEnv, "toBool", &stringValue), NAPIExceptionOK);
ASSERT_EQ(napi_set_property(globalEnv, addonValue, stringValue, toBoolValue), NAPIExceptionOK);
ASSERT_EQ(napi_create_string_utf8(globalEnv, "toNumber", &stringValue), NAPIExceptionOK);
ASSERT_EQ(napi_set_property(globalEnv, addonValue, stringValue, toNumberValue), NAPIExceptionOK);
ASSERT_EQ(napi_create_string_utf8(globalEnv, "toString", &stringValue), NAPIExceptionOK);
ASSERT_EQ(napi_set_property(globalEnv, addonValue, stringValue, toStringValue), NAPIExceptionOK);
ASSERT_EQ(
NAPIRunScript(
globalEnv,
"(()=>{\"use "
"strict\";globalThis.assert(Object.is(globalThis.addon.toBool(!0),!0)),globalThis.assert(Object.is("
"globalThis.addon.toBool(1),!0)),globalThis.assert(Object.is(globalThis.addon.toBool(-1),!0)),globalThis."
"assert(Object.is(globalThis.addon.toBool(\"true\"),!0)),globalThis.assert(Object.is(globalThis.addon."
"toBool(\"false\"),!0)),globalThis.assert(Object.is(globalThis.addon.toBool({}),!0)),globalThis.assert("
"Object.is(globalThis.addon.toBool([]),!0)),globalThis.assert(Object.is(globalThis.addon.toBool(!1),!1)),"
"globalThis.assert(Object.is(globalThis.addon.toBool(void "
"0),!1)),globalThis.assert(Object.is(globalThis.addon.toBool(null),!1)),globalThis.assert(Object.is("
"globalThis.addon.toBool(0),!1)),globalThis.assert(Object.is(globalThis.addon.toBool(Number.NaN),!1)),"
"globalThis.assert(Object.is(globalThis.addon.toBool(\"\"),!1)),globalThis.assert(Object.is(globalThis."
"addon.toNumber(0),0)),globalThis.assert(Object.is(globalThis.addon.toNumber(1),1)),globalThis.assert("
"Object.is(globalThis.addon.toNumber(1.1),1.1)),globalThis.assert(Object.is(globalThis.addon.toNumber(-1),-"
"1)),globalThis.assert(Object.is(globalThis.addon.toNumber(\"0\"),0)),globalThis.assert(Object.is("
"globalThis.addon.toNumber(\"1\"),1)),globalThis.assert(Object.is(globalThis.addon.toNumber(\"1.1\"),1.1)),"
"globalThis.assert(Object.is(globalThis.addon.toNumber([]),0)),globalThis.assert(Object.is(globalThis."
"addon.toNumber(!1),0)),globalThis.assert(Object.is(globalThis.addon.toNumber(null),0)),globalThis.assert("
"Object.is(globalThis.addon.toNumber(\"\"),0)),globalThis.assert(Number.isNaN(globalThis.addon.toNumber("
"Number.NaN))),globalThis.assert(Number.isNaN(globalThis.addon.toNumber({}))),globalThis.assert(Number."
"isNaN(globalThis.addon.toNumber(void "
"0))),globalThis.assert(Object.is(globalThis.addon.toString(\"\"),\"\")),globalThis.assert(Object.is("
"globalThis.addon.toString(\"globalThis.addon\"),\"globalThis.addon\")),globalThis.assert(Object.is("
"globalThis.addon.toString(void "
"0),\"undefined\")),globalThis.assert(Object.is(globalThis.addon.toString(null),\"null\")),globalThis."
"assert(Object.is(globalThis.addon.toString(!1),\"false\")),globalThis.assert(Object.is(globalThis.addon."
"toString(!0),\"true\")),globalThis.assert(Object.is(globalThis.addon.toString(0),\"0\")),globalThis."
"assert(Object.is(globalThis.addon.toString(1.1),\"1.1\")),globalThis.assert(Object.is(globalThis.addon."
"toString(Number.NaN),\"NaN\")),globalThis.assert(Object.is(globalThis.addon.toString({}),\"[object "
"Object]\")),globalThis.assert(Object.is(globalThis.addon.toString({toString:function(){return\"globalThis."
"addon\"}}),\"globalThis.addon\")),globalThis.assert(Object.is(globalThis.addon.toString([]),\"\")),"
"globalThis.assert(Object.is(globalThis.addon.toString([1,2,3]),\"1,2,3\"))})();",
"https://www.napi.com/conversion.js", nullptr),
NAPIExceptionOK);
} | 59.098901 | 120 | 0.690591 | [
"object"
] |
5cccaefe13baebc25fafe3cdb1484b549162dd63 | 21,223 | hpp | C++ | external/openglcts/modules/glesext/geometry_shader/esextcGeometryShaderRendering.hpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 354 | 2017-01-24T17:12:38.000Z | 2022-03-30T07:40:19.000Z | external/openglcts/modules/glesext/geometry_shader/esextcGeometryShaderRendering.hpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 275 | 2017-01-24T20:10:36.000Z | 2022-03-24T16:24:50.000Z | external/openglcts/modules/glesext/geometry_shader/esextcGeometryShaderRendering.hpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 190 | 2017-01-24T18:02:04.000Z | 2022-03-27T13:11:23.000Z | #ifndef _ESEXTCGEOMETRYSHADERRENDERING_HPP
#define _ESEXTCGEOMETRYSHADERRENDERING_HPP
/*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2014-2016 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/ /*!
* \file
* \brief
*/ /*-------------------------------------------------------------------*/
#include "../esextcTestCaseBase.hpp"
namespace glcts
{
/** Supported geometry shader output layout qualifiers */
typedef enum {
/* points */
SHADER_OUTPUT_TYPE_POINTS,
/* lines */
SHADER_OUTPUT_TYPE_LINE_STRIP,
/* triangles */
SHADER_OUTPUT_TYPE_TRIANGLE_STRIP,
/* Always last */
SHADER_OUTPUT_TYPE_COUNT
} _shader_output_type;
/** Implements Geometry Shader conformance test group 1.
*
* Note that actual testing is handled by classes implementing GeometryShaderRenderingCase
* interface. This class implements DEQP CTS test case interface, meaning it is only
* responsible for executing the test and reporting the results back to CTS.
*
**/
class GeometryShaderRendering : public TestCaseGroupBase
{
public:
/* Public methods */
GeometryShaderRendering(Context& context, const ExtParameters& extParams, const char* name,
const char* description);
virtual ~GeometryShaderRendering()
{
}
virtual void init(void);
private:
/* Private type definitions */
typedef enum {
/* points */
SHADER_INPUT_POINTS,
/* lines */
SHADER_INPUT_LINES,
/* lines_with_adjacency */
SHADER_INPUT_LINES_WITH_ADJACENCY,
/* triangles */
SHADER_INPUT_TRIANGLES,
/* triangles_with_adjacency */
SHADER_INPUT_TRIANGLES_WITH_ADJACENCY,
/* Always last */
SHADER_INPUT_UNKNOWN
} _shader_input;
/* Private methods */
const char* getTestName(_shader_input input, _shader_output_type output_type, glw::GLenum drawcall_mode);
};
/* Defines an interface that all test case classes must implement.
*
* Base implementation initializes GLES objects later used in the specific test
* and fills them with content, as reported by actual test case implementations.
*
* Instances matching this interface are used by GeometryShaderRendering class
* to execute a set of all the tests as defined in the test specification.
*/
class GeometryShaderRenderingCase : public TestCaseBase
{
public:
/* Public type definitions */
/** Supported draw call types. */
typedef enum {
/* glDrawArrays() */
DRAW_CALL_TYPE_GL_DRAW_ARRAYS,
/* glDrawArraysInstanced() */
DRAW_CALL_TYPE_GL_DRAW_ARRAYS_INSTANCED,
/* glDrawElements() */
DRAW_CALL_TYPE_GL_DRAW_ELEMENTS,
/* glDrawElementsInstanced() */
DRAW_CALL_TYPE_GL_DRAW_ELEMENTS_INSTANCED,
/* glDrawRangeElements() */
DRAW_CALL_TYPE_GL_DRAW_RANGE_ELEMENTS
} _draw_call_type;
/* Public methods */
GeometryShaderRenderingCase(Context& Context, const ExtParameters& extParams, const char* name,
const char* description);
virtual ~GeometryShaderRenderingCase()
{
}
virtual void deinit();
void executeTest(_draw_call_type type);
virtual IterateResult iterate();
protected:
/* Protected methods */
void initTest();
virtual unsigned int getAmountOfDrawInstances() = 0;
virtual unsigned int getAmountOfElementsPerInstance() = 0;
virtual unsigned int getAmountOfVerticesPerInstance() = 0;
virtual glw::GLenum getDrawCallMode() = 0;
virtual std::string getFragmentShaderCode() = 0;
virtual std::string getGeometryShaderCode() = 0;
virtual glw::GLuint getRawArraysDataBufferSize(bool instanced) = 0;
virtual const void* getRawArraysDataBuffer(bool instanced) = 0;
virtual void getRenderTargetSize(unsigned int n_instances, unsigned int* out_width, unsigned int* out_height) = 0;
virtual glw::GLuint getUnorderedArraysDataBufferSize(bool instanced) = 0;
virtual const void* getUnorderedArraysDataBuffer(bool instanced) = 0;
virtual glw::GLuint getUnorderedElementsDataBufferSize(bool instanced) = 0;
virtual const void* getUnorderedElementsDataBuffer(bool instanced) = 0;
virtual glw::GLenum getUnorderedElementsDataType() = 0;
virtual glw::GLubyte getUnorderedElementsMaxIndex() = 0;
virtual glw::GLubyte getUnorderedElementsMinIndex() = 0;
virtual std::string getVertexShaderCode() = 0;
virtual void verify(_draw_call_type drawcall_type, unsigned int instance_id, const unsigned char* data) = 0;
virtual void setUniformsBeforeDrawCall(_draw_call_type /*drawcall_type*/)
{
}
/* Protected variables */
deqp::Context& m_context;
glw::GLuint m_instanced_raw_arrays_bo_id;
glw::GLuint m_instanced_unordered_arrays_bo_id;
glw::GLuint m_instanced_unordered_elements_bo_id;
glw::GLuint m_noninstanced_raw_arrays_bo_id;
glw::GLuint m_noninstanced_unordered_arrays_bo_id;
glw::GLuint m_noninstanced_unordered_elements_bo_id;
glw::GLuint m_fs_id;
glw::GLuint m_gs_id;
glw::GLuint m_po_id;
glw::GLuint m_renderingTargetSize_uniform_location;
glw::GLuint m_singleRenderingTargetSize_uniform_location;
glw::GLuint m_vao_id;
glw::GLuint m_vs_id;
glw::GLuint m_fbo_id;
glw::GLuint m_read_fbo_id;
glw::GLuint m_to_id;
glw::GLuint m_instanced_fbo_id;
glw::GLuint m_instanced_read_fbo_id;
glw::GLuint m_instanced_to_id;
};
/** Implements Geometry Shader conformance test group 1, 'points' input primitive type case.
* Test specification for this case follows:
*
* All sub-tests assume point size & line width of 1 pixel, which is the
* minimum maximum value for both properties in GLES 3.0.
*
* Let (R, G, B, A) be the color of the input point that is to be amplified.
* Color buffer should be cleared with (0, 0, 0, 0) prior to executing each
* of the scenarios.
*
* 1.1. If "points" output primitive type is used:
*
* The geometry shader should emit 9 points in total for a single input.
* Each point should be assigned a size of 1. The points should be
* positioned, so that they tightly surround the "input" point from left /
* right / top / left sides, as well as from top-left / top-right /
* bottom-left / bottom-right corners but do *not* overlap in screen-space.
*
* Additional points should also use (R, G, B, A) color.
*
* The test should draw 8 points (one after another, assume a horizontal
* delta of 2 pixels) of varying colors to a 2D texture of resolution 38x3.
* Test succeeds if centers of all emitted points have colors different than
* the background color.
*
* 1.2. If "lines" output primitive type is used:
*
* The geometry shader should draw outlines (built of line segments) of
* three quads nested within each other, as depicted below:
*
* 1 1 1 1 1 1 1
* 1 2 2 2 2 2 1
* 1 2 3 3 3 2 1
* 1 2 3 * 3 2 1
* 1 2 3 3 3 2 1
* 1 2 2 2 2 2 1
* 1 1 1 1 1 1 1
*
* where each number corresponds to index of the quad and * indicates
* position of the input point which is not drawn.
*
* Each quad should be drawn with (R, G, B, A) color.
* The test should draw 8 points (one after another) of varying colors to
* a 2D texture of resolution 54x7. Test succeeds if all pixels making up
* the central quad 2 have valid colors.
*
* 1.3. If "triangles" output primitive type is used:
*
* The geometry shader should generate 2 triangle primitives for a single
* input point:
*
* * A) (Bottom-left corner, top-left corner, bottom-right corner), use
* (R, 0, 0, 0) color;
* * B) (Bottom-right corner, top-left corner, top-right corner), use
* (0, G, 0, 0) color;
*
* The test should draw 8 points (one after another) of varying colors to
* a 2D texture of resolution of resolution 48x6. Test succeeds if centers
* of the rendered triangles have valid colors.
*
**/
class GeometryShaderRenderingPointsCase : public GeometryShaderRenderingCase
{
public:
/* Public methods */
GeometryShaderRenderingPointsCase(Context& context, const ExtParameters& extParams, const char* name,
glw::GLenum drawcall_mode, _shader_output_type output_type);
virtual ~GeometryShaderRenderingPointsCase();
protected:
/* GeometryShaderRenderingCase interface implementation */
unsigned int getAmountOfDrawInstances();
unsigned int getAmountOfElementsPerInstance();
unsigned int getAmountOfVerticesPerInstance();
glw::GLenum getDrawCallMode();
std::string getFragmentShaderCode();
std::string getGeometryShaderCode();
glw::GLuint getRawArraysDataBufferSize(bool instanced);
const void* getRawArraysDataBuffer(bool instanced);
void getRenderTargetSize(unsigned int n_instances, unsigned int* out_width, unsigned int* out_height);
glw::GLuint getUnorderedArraysDataBufferSize(bool instanced);
const void* getUnorderedArraysDataBuffer(bool instanced);
glw::GLuint getUnorderedElementsDataBufferSize(bool instanced);
const void* getUnorderedElementsDataBuffer(bool instanced);
glw::GLenum getUnorderedElementsDataType();
glw::GLubyte getUnorderedElementsMaxIndex();
glw::GLubyte getUnorderedElementsMinIndex();
std::string getVertexShaderCode();
void verify(_draw_call_type drawcall_type, unsigned int instance_id, const unsigned char* data);
private:
/* Private variables */
_shader_output_type m_output_type;
float* m_raw_array_data;
float* m_unordered_array_data;
unsigned char* m_unordered_elements_data;
};
/** Implements Geometry Shader conformance test group 1, 'lines' and
* 'lines_adjacency' input primitive type cases.
*
* Test specification for this case follows:
*
* Assume a point size of 1 pixel and line width of 1 pixel, where
* appropriate.
* Let (R, G, B, A) be the color of start point of the input line and
* (R', G', B', A') be the color of end point of the input line.
*
* 2.1. If "points" output primitive type is used:
*
* The geometry shader should generate 8 points for a single input line segment,
* where each point consists of 9 sub-points tightly forming a quad (with
* the actual point located in the center) in order to emulate larger point
* size. The points should be uniformly distributed over the primitive
* (first point positioned at the start point and the last one located at
* the end point) and their color should linearly interpolate from the
* (R, G, B, A) to (R', G', B', A'). All sub-points should use the same
* color as the parent point.
*
* The test should draw the points over a square outline. Each instance should
* draw a set of points occupying a separate outline. Each rectangle should
* occupy a block of 45x45.
*
* Test succeeds if centers of generated points have valid colors.
*
* 2.2. If "lines" output primitive type is used:
*
* Expanding on the idea presenting in 2.1, for each line segment the GS
* should generate three line segments, as presented below:
*
* Upper/left helper line segment
* Line segment
* Bottom/right helper line segment
*
* This is to emulate a larger line width than the minimum maximum line
* width all GLES implementations must support.
*
* Upper helper line segment should use start point's color;
* Middle line segment should take mix(start_color, end_color, 0.5) color;
* Bottom helper line segment should use end point's color;
*
* Test succeeds if all pixels of generated middle line segments have valid
* colors. Do not test corners.
*
* 2.3. If "triangles" output primitive type is used:
*
* Expanding on the idea presented in 2.1: for each input line segment,
* the GS should generate a triangle, using two vertices provided and
* (0, 0, 0, 1). By drawing a quad outline, whole screen-space should be
* covered with four triangles.
* The test passes if centroids of the generated triangles carry valid colors.
*
**/
class GeometryShaderRenderingLinesCase : public GeometryShaderRenderingCase
{
public:
/* Public methods */
GeometryShaderRenderingLinesCase(Context& context, const ExtParameters& extParams, const char* name,
bool use_adjacency_data, glw::GLenum drawcall_mode,
_shader_output_type output_type);
virtual ~GeometryShaderRenderingLinesCase();
protected:
/* GeometryShaderRenderingCase interface implementation */
unsigned int getAmountOfDrawInstances();
unsigned int getAmountOfElementsPerInstance();
unsigned int getAmountOfVerticesPerInstance();
glw::GLenum getDrawCallMode();
std::string getFragmentShaderCode();
std::string getGeometryShaderCode();
glw::GLuint getRawArraysDataBufferSize(bool instanced);
const void* getRawArraysDataBuffer(bool instanced);
void getRenderTargetSize(unsigned int n_instances, unsigned int* out_width, unsigned int* out_height);
glw::GLuint getUnorderedArraysDataBufferSize(bool instanced);
const void* getUnorderedArraysDataBuffer(bool instanced);
glw::GLuint getUnorderedElementsDataBufferSize(bool instanced);
const void* getUnorderedElementsDataBuffer(bool instanced);
glw::GLenum getUnorderedElementsDataType();
glw::GLubyte getUnorderedElementsMaxIndex();
glw::GLubyte getUnorderedElementsMinIndex();
std::string getVertexShaderCode();
void setUniformsBeforeDrawCall(_draw_call_type drawcall_type);
void verify(_draw_call_type drawcall_type, unsigned int instance_id, const unsigned char* data);
private:
/* Private variables */
_shader_output_type m_output_type;
glw::GLenum m_drawcall_mode;
bool m_use_adjacency_data;
float* m_raw_array_instanced_data;
unsigned int m_raw_array_instanced_data_size;
float* m_raw_array_noninstanced_data;
unsigned int m_raw_array_noninstanced_data_size;
float* m_unordered_array_instanced_data;
unsigned int m_unordered_array_instanced_data_size;
float* m_unordered_array_noninstanced_data;
unsigned int m_unordered_array_noninstanced_data_size;
unsigned char* m_unordered_elements_instanced_data;
unsigned int m_unordered_elements_instanced_data_size;
unsigned char* m_unordered_elements_noninstanced_data;
unsigned int m_unordered_elements_noninstanced_data_size;
unsigned char m_unordered_elements_max_index;
unsigned char m_unordered_elements_min_index;
};
/** Implements Geometry Shader conformance test group 1, 'triangles' and
* 'triangles_adjacency' input primitive type cases. Test specification
* for this case follows:
*
* All tests should draw a 45-degree rotated square shape consisting of four
* separate triangles, as depicted in the picture below:
*
*
* C
* / \
* / \
* B--A--D
* \ /
* \_/
* E
*
* For GL_TRIANGLES data, the rendering order is: ABC, ACD, ADE, AEB;
* For GL_TRIANGLE_FAN, the rendering order is: ABCDEB;
* For GL_TRIANGLE_STRIP, the rendering order is: BACDAEB;
*
* Note that for triangle strips, a degenerate triangle will be rendered.
* Test implementation should not test the first triangle rendered in the
* top-right quarter, as it will be overwritten by the triangle that follows
* right after.
*
* Subsequent draw call instances should draw the geometry one after another,
* in vertical direction.
*
* Each of the tests should use 29x(29 * number of instances) resolution for
* the rendertarget.
*
* 3.1. If "points" output primitive type is used:
*
* The geometry shader should generate 3 points for a single input triangle.
* These points should be emitted for each of the triangle's vertex
* locations and:
*
* * First vertex should be of (R, G, B, A) color;
* * Second vertex should be of (R', G', B', A') color;
* * Third vertex should be of (R'', G'', B'', A'') color;
*
* Each point should actually consist of 9 emitted points of size 1 (as
* described in test scenario 1.1), with the middle point being positioned
* at exact vertex location. This is to emulate larger point size than the
* minimum maximum allows. All emitted points should use the same color as
* parent point's.
*
* Test succeeds if centers of the rendered points have valid colors.
*
* 3.2. If "lines" output primitive type is used:
*
* Let:
*
* * TL represent top-left corner of the triangle's bounding box;
* * TR represent top-right corner of the triangle's bounding box;
* * BL represent bottom-left corner of the triangle's bounding box;
* * BR represent bottom-right corner of the triangle's bounding box;
*
* The geometry shader should draw 4 line segments for a single input
* triangle:
*
* * First line segment should start at BL and end at TL and use a static
* (R, G, B, A) color;
* * Second line segment should start at TL and end at TR and use a static
* (R', G', B', A') color;
* * Third line segment should start at TR and end at BR and use a static
* (R'', G'', B'', A'') color;
* * Fourth line segment should start at BR and end at BL and use a static
* (R, G', B'', A) color;
*
* Each line segment should actually consist of 3 separate line segments
* "stacked" on top of each other, with the middle segment being positioned
* as described above (as described in test scenario 2.2). This is to
* emulate line width that is larger than the minimum maximum allows. All
* emitted line segments should use the same color as parent line segment's.
*
* Test succeeds if centers of the rendered line segments have valid colors.
*
* 3.3. If "triangles" output primitive type is used:
*
* Test should take incoming triangle vertex locations and order them in the
* following order:
*
* a) A - vertex in the origin;
* b) B - the other vertex located on the same height as A;
* c) C - remaining vertex;
*
* Let D = BC/2.
*
* The test should emit ABD and ACD triangles for input ABC triangle data.
* First triangle emitted should take color of the first input vertex
* (not necessarily A!).
* The second one should use third vertex's color (not necessarily C!),
* with the first channel being multiplied by two.
*
* Test succeeds if centers of the rendered triangles have valid colors;
*
**/
class GeometryShaderRenderingTrianglesCase : public GeometryShaderRenderingCase
{
public:
/* Public methods */
GeometryShaderRenderingTrianglesCase(Context& context, const ExtParameters& extParams, const char* name,
bool use_adjacency_data, glw::GLenum drawcall_mode,
_shader_output_type output_type);
virtual ~GeometryShaderRenderingTrianglesCase();
protected:
/* GeometryShaderRenderingCase interface implementation */
unsigned int getAmountOfDrawInstances();
unsigned int getAmountOfElementsPerInstance();
unsigned int getAmountOfVerticesPerInstance();
glw::GLenum getDrawCallMode();
std::string getFragmentShaderCode();
std::string getGeometryShaderCode();
glw::GLuint getRawArraysDataBufferSize(bool instanced);
const void* getRawArraysDataBuffer(bool instanced);
void getRenderTargetSize(unsigned int n_instances, unsigned int* out_width, unsigned int* out_height);
glw::GLuint getUnorderedArraysDataBufferSize(bool instanced);
const void* getUnorderedArraysDataBuffer(bool instanced);
glw::GLuint getUnorderedElementsDataBufferSize(bool instanced);
const void* getUnorderedElementsDataBuffer(bool instanced);
glw::GLenum getUnorderedElementsDataType();
glw::GLubyte getUnorderedElementsMaxIndex();
glw::GLubyte getUnorderedElementsMinIndex();
std::string getVertexShaderCode();
void setUniformsBeforeDrawCall(_draw_call_type drawcall_type);
void verify(_draw_call_type drawcall_type, unsigned int instance_id, const unsigned char* data);
private:
/* Private variables */
_shader_output_type m_output_type;
glw::GLenum m_drawcall_mode;
bool m_use_adjacency_data;
float* m_raw_array_instanced_data;
unsigned int m_raw_array_instanced_data_size;
float* m_raw_array_noninstanced_data;
unsigned int m_raw_array_noninstanced_data_size;
float* m_unordered_array_instanced_data;
unsigned int m_unordered_array_instanced_data_size;
float* m_unordered_array_noninstanced_data;
unsigned int m_unordered_array_noninstanced_data_size;
unsigned char* m_unordered_elements_instanced_data;
unsigned int m_unordered_elements_instanced_data_size;
unsigned char* m_unordered_elements_noninstanced_data;
unsigned int m_unordered_elements_noninstanced_data_size;
unsigned char m_unordered_elements_max_index;
unsigned char m_unordered_elements_min_index;
};
} // namespace glcts
#endif // _ESEXTCGEOMETRYSHADERRENDERING_HPP
| 38.170863 | 115 | 0.732413 | [
"geometry",
"shape"
] |
5ccffcbb1f03ee19cc23ae17d4c5350f35d61b30 | 3,013 | cpp | C++ | Razor/src/Razor/Animation/AnimationManager.cpp | 0zirix/Razor | b902d316da058caa636efce15da405beb73d9f73 | [
"MIT"
] | 2 | 2021-09-25T02:44:02.000Z | 2021-10-03T09:37:54.000Z | Razor/src/Razor/Animation/AnimationManager.cpp | 0zirix/Razor | b902d316da058caa636efce15da405beb73d9f73 | [
"MIT"
] | null | null | null | Razor/src/Razor/Animation/AnimationManager.cpp | 0zirix/Razor | b902d316da058caa636efce15da405beb73d9f73 | [
"MIT"
] | null | null | null | #include "rzpch.h"
#include "BoneTransform.h"
#include "Bone.h"
#include "AnimationManager.h"
#include "Animation.h"
#include "Razor/Geometry/SkeletalMesh.h"
namespace Razor
{
AnimationManager::AnimationManager(SkeletalMesh* mesh) :
mesh(mesh),
current_animation(nullptr),
delta(0.0f),
time(0.0f)
{
}
AnimationManager::~AnimationManager()
{
}
void AnimationManager::update(float dt)
{
delta = dt;
if (current_animation == nullptr)
return;
tick();
std::map<std::string, glm::mat4> current_pose = calcCurrentAnimationPose();
applyPoseToBone(current_pose, mesh->getRootBone(), glm::mat4(1.0f));
}
void AnimationManager::tick()
{
time += delta;
if (time > current_animation->getLength())
time = fmod(time, current_animation->getLength());
}
void AnimationManager::playAnimation(Animation* animation)
{
time = 0.0f;
current_animation = animation;
}
std::map<std::string, glm::mat4> AnimationManager::calcCurrentAnimationPose()
{
std::vector<Keyframe> frames = getPreviousAndNextFrames();
float progress = calculateProgress(frames[0], frames[1]);
return interpolatePoses(frames[0], frames[1], progress);
}
void AnimationManager::applyPoseToBone(const std::map<std::string, glm::mat4>& current_pose, std::shared_ptr<Bone> bone, glm::mat4 parent_transform)
{
glm::mat4 current_local_transform = current_pose.at(bone->getName());
glm::mat4 current_transform = parent_transform * current_local_transform;
for (auto child : bone->getChildren())
applyPoseToBone(current_pose, child, current_transform);
current_transform *= bone->getInverseTransform();
bone->setAnimatedTransform(current_transform);
}
std::vector<Keyframe> AnimationManager::getPreviousAndNextFrames()
{
std::vector<Keyframe> frames = current_animation->getKeyframes();
Keyframe previous = frames[0];
Keyframe next = frames[0];
for (int i = 1; i < frames.size(); i++)
{
next = frames[i];
if (next.getTimestamp() > time)
break;
previous = frames[i];
}
std::vector<Keyframe> f = { previous, next };
return f;
}
float AnimationManager::calculateProgress(Keyframe previous, Keyframe next)
{
float total = next.getTimestamp() - previous.getTimestamp();
float current = time - previous.getTimestamp();
return current / total;
}
std::map<std::string, glm::mat4> AnimationManager::interpolatePoses(Keyframe previous, Keyframe next, float progress)
{
std::map<std::string, glm::mat4> currentPose;
std::map<std::string, BoneTransform*>::iterator it;
std::map<std::string, BoneTransform*> keyframes = previous.getPose();
for (it = keyframes.begin(); it != keyframes.end(); it++)
{
BoneTransform* previousTransform = keyframes.at(it->first);
BoneTransform* nextTransform = next.getPose().at(it->first);
BoneTransform* currentTransform = BoneTransform::interpolate(previousTransform, nextTransform, progress);
currentPose[it->first] = currentTransform->getLocaltransform();
}
return currentPose;
}
} | 25.319328 | 149 | 0.715898 | [
"mesh",
"geometry",
"vector"
] |
5cd72ab727f82c8787a9d9c5522df125eaf735a7 | 15,476 | cpp | C++ | test/projective/direct_linear_transformation.cpp | Rookfighter/cv-eigen | 0387bf62e22e9d9fb86e6fa03e05bc8250c7d651 | [
"MIT"
] | 8 | 2019-10-02T04:21:46.000Z | 2020-12-08T07:56:04.000Z | test/projective/direct_linear_transformation.cpp | Rookfighter/cv-eigen | 0387bf62e22e9d9fb86e6fa03e05bc8250c7d651 | [
"MIT"
] | 8 | 2019-10-21T12:13:58.000Z | 2021-08-01T15:14:28.000Z | test/projective/direct_linear_transformation.cpp | Rookfighter/cv-eigen | 0387bf62e22e9d9fb86e6fa03e05bc8250c7d651 | [
"MIT"
] | 2 | 2019-10-02T04:17:24.000Z | 2020-12-08T07:56:11.000Z | /* direct_linear_transformation.cpp
*
* Author: Fabian Meyer
* Created On: 25 Sep 2019
*/
#include "assert/eigen_require.h"
#include <cve/projective/direct_linear_transformation.h>
using namespace cve;
typedef double Scalar;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix;
typedef Eigen::Matrix<Scalar, 3, 3> Matrix3;
TEST_CASE("direct_linear_transformation")
{
Matrix data1(2, 64);
data1 <<
63.43921044061905, 116.28035530429925, 170.832696837639, 226.86846784643092, 284.39049681092564, 342.94734878624087, 402.3786597601738, 462.1274425133204, 65.23122858749674, 118.03455996929435, 172.4001628011494, 228.3763298691328, 285.9599818293802, 344.4946104549276, 403.8459777399356, 463.4920805680829, 67.41852441860404, 119.9797486243428, 174.3238625443077, 230.1838096287344, 287.5611603285242, 346.0130820428916, 405.0691571796657, 464.5704816546494, 70.14223570324233, 122.32352404284693, 176.46490664036455, 232.11481951556652, 289.2384705637213, 347.4351242513755, 406.2245843264435, 465.523092053566, 72.98910805171106, 125.08462582171373, 178.69793526089177, 234.15457949117916, 290.8999148937342, 348.6042810219786, 407.1003826281793, 465.97490215671394, 76.16710425446853, 127.84130625665146, 181.25563306460265, 236.23365624522017, 292.4588748930849, 349.69159518414097, 407.61257650834744, 465.9575137851354, 79.51086377384169, 130.72333248421154, 183.58843498593697, 238.07365326917147, 293.83525186897225, 350.4720860096607, 407.6771939926995, 465.4727459783836, 83.91124369483907, 134.6306229879343, 187.12492527401574, 240.9165999666756, 295.9948347437614, 351.92099001188586, 408.526106159246, 465.65621424059066,
405.57679766845445, 409.17858333240645, 412.46038130831136, 415.8660937726924, 418.52561560191134, 420.86862691813366, 423.0391036991514, 424.698227870397, 349.6907027733138, 352.3848197690597, 355.22103054344683, 357.91781697436124, 360.10319357751825, 362.0295359924154, 363.76076192996504, 365.13759047476947, 293.9966296559016, 295.99698063712265, 297.9337108902351, 299.78921796236745, 301.40750765891795, 302.8615772015612, 304.3961263202983, 305.55438512850714, 238.36941313466673, 239.49645820189613, 240.6218321347413, 241.93435972850207, 242.95729366739042, 244.16872583239353, 245.03205353779114, 246.1775260488285, 183.3229223758834, 183.7455308332811, 184.17588311789484, 184.67925083341942, 185.18321246496123, 185.89123718698139, 186.57807793920117, 187.31221128756985, 129.06339843948058, 128.69339578967518, 128.48382994356055, 128.40228658023835, 128.45043466848207, 128.56678071162221, 128.87175784461283, 129.54762183209073, 76.19294770503798, 74.89725312608094, 74.10334829270418, 73.31630178493887, 72.8290660404367, 72.61004387294248, 72.68022846248228, 72.99430375637395, 24.449609965519024, 22.615817432586987, 20.95504911622112, 19.803724782257063, 18.78111909293907, 18.26130021351024, 17.991288029486068, 18.207516413716252;
Matrix data2(2, 64);
data2 <<
74.95173767129486, 127.82252063924655, 181.84295543141715, 237.12102868837414, 293.18762081188373, 349.9194813487409, 406.99836748473933, 464.0038872204549, 71.29513562533573, 124.85876349944454, 179.86316734884443, 236.16730364497818, 293.27736544637816, 351.0824026293796, 409.237369470657, 467.22528388902015, 67.86990551193277, 122.24349452326419, 178.05244645201566, 235.25161840257564, 293.3421842610446, 352.244687578723, 411.28840290448835, 470.2577135508111, 64.75555278435645, 119.76637875562051, 176.42971625799623, 234.50709637791988, 293.509685485772, 353.26154729214403, 413.24709354626935, 473.2646573411307, 62.05888397044999, 117.73390592637882, 175.03678176202516, 233.843922785267, 293.7353783366339, 354.2987015865003, 415.07650445349185, 475.93976313131697, 59.42172685465347, 115.77372481183963, 173.7876505758194, 233.17777139665816, 293.83886263182103, 355.0451067222118, 416.52661520032, 478.0945516167279, 57.381598023792804, 114.06968575478231, 172.48640816024854, 232.5402874913855, 293.77480578263754, 355.60254590572043, 417.7098217713907, 479.76163911602845, 56.318999635465964, 113.57672948180384, 172.64025607990797, 233.0920953642154, 294.595375305751, 356.9130755447031, 419.55084342282595, 481.9960132940097,
409.09267757581756, 412.2041930215117, 414.98756134254074, 417.61764879300614, 419.83695853105417, 421.5926044159451, 422.9847167646322, 424.13271228547285, 357.6942633948015, 360.14700880628453, 362.63102501359486, 364.81259801424477, 366.85190781014205, 368.4938576438795, 369.89469625644654, 370.8611321393432, 304.15854104273126, 306.2762726445089, 308.2732746098075, 310.25100921872996, 311.8508340598895, 313.2272280064658, 314.50849735444723, 315.65909088057236, 249.00623198940218, 250.43888034309919, 251.97401222878347, 253.35502367526004, 254.65618927479554, 256.0041375953487, 257.07095581919504, 258.25170894636994, 192.35510221204711, 193.02538500590614, 193.94265924027135, 194.7555301320053, 195.803516382801, 196.78147138286732, 197.92445468093158, 198.98183996148856, 134.179092671166, 134.2042774623179, 134.43075359705995, 134.79815066776965, 135.48528605204007, 136.27656990753377, 137.15292513462248, 138.37478658889506, 75.06465950658283, 74.48587987763723, 74.1320277432348, 73.97411559857558, 74.14953797150977, 74.58162759095768, 75.50504947291813, 76.6873930120917, 15.145508059133235, 13.862934726294393, 12.56360906633607, 12.318481092420383, 11.997888025947153, 12.395678586510696, 13.012494018315612, 14.223576647359778;
Matrix data3(2, 64);
data3 <<
137.22826265754128, 180.16912538559387, 225.75104300713795, 274.06364553672006, 325.0825655137707, 378.98388879169886, 435.3672294584237, 494.4674585750879, 139.23128225352067, 182.0956177210248, 227.77183133008973, 276.0055916396826, 327.097679977267, 380.80323390705894, 437.3161307891978, 496.5259261096069, 141.46861683034936, 184.29973188639207, 229.8310926051587, 278.01506574164137, 329.0596770303812, 382.7568264528644, 439.1076523453959, 498.20319243576364, 144.02690053062062, 186.77027044489435, 231.9840600903537, 280.1539980943389, 331.0118139734911, 384.4956750345099, 440.6855471964129, 499.3795257678252, 146.62005436903283, 189.19997922929988, 234.47993108486497, 282.40479346925423, 332.8725536440233, 386.04522463062176, 441.98872926357933, 500.2881129514194, 149.54446166549693, 192.02698305909564, 236.82599989671436, 284.4659594003672, 334.5057948401551, 387.3688333267982, 442.62430145277176, 500.5166852013382, 152.6941041120487, 194.4685357560373, 239.10030401088463, 286.1734015784083, 335.89624139722815, 388.29937338446825, 443.04706241212943, 500.1510622911001, 155.5435287110069, 197.3847531971697, 241.7067121175821, 288.40151605688584, 337.76488292829356, 389.5822762790428, 443.87428361015714, 500.4966854081226,
394.36338179898917, 399.3808729240103, 404.3630066605049, 409.5082639415724, 414.4173174859092, 419.4444513141882, 424.3107037363906, 428.932852781578, 343.82883420371434, 347.34328675090325, 350.75951555377674, 354.34376925094153, 358.0025148055112, 361.3858374680148, 364.6838758307422, 368.1086909818487, 293.0742154572436, 295.09574730151354, 297.15398989000835, 299.2639193616573, 301.1764953193146, 303.2440789128329, 305.0927844274493, 306.9549946877856, 242.6718680818291, 243.14467479496832, 243.8498032983192, 244.45522572209077, 244.8505182769471, 245.32783257739558, 245.90994004685442, 246.37083852688656, 192.63570149359077, 191.81378016298464, 190.88652205812798, 190.16562891048716, 188.97316935994638, 188.21089480538737, 187.07929156095236, 186.29351513598155, 143.23993886908247, 140.9532635865463, 138.81359207082616, 136.5489122466196, 134.1289277694715, 131.66081409515422, 129.3503753046519, 127.09848842356901, 94.76135047288122, 91.27497856507841, 87.444925082216, 83.8750500079042, 80.30694821030578, 76.65330292365267, 72.98931424770032, 69.48749337226295, 47.17733319510865, 42.56321054309326, 37.593701930234246, 32.77894423415306, 27.740386011495826, 22.957895518479983, 18.171841356899918, 13.507183887278705;
Matrix data4(2, 64);
data4 <<
84.04443096693421, 141.72697580728473, 198.84160209514897, 255.29048125241334, 310.8563877944848, 365.14154221159794, 418.12334794462424, 469.44710399654394, 85.37953462163631, 142.7532108282927, 199.95031028127778, 256.34156128825185, 311.84877343792976, 366.12525672838075, 418.9949604588119, 470.1986100852902, 87.04076708049563, 144.21931172056645, 201.17687679253876, 257.42839689778856, 312.8184806124381, 366.9415531832442, 419.6441969265521, 470.7675811162934, 89.06173929681611, 145.96439095961492, 202.59943341937188, 258.6686748785791, 313.7390153168726, 367.7233746668972, 420.113032118686, 471.0576589443452, 91.45015936007158, 148.0457547322132, 204.28229364512413, 259.9922098463268, 314.7415031780298, 368.3041944424955, 420.40232294270123, 471.02419150718754, 94.22109692137786, 150.38300521582437, 206.02628128325355, 261.31965129541436, 315.51314998670256, 368.67232120839816, 420.43715162551564, 470.69111452804435, 97.09281156928235, 152.53290892825265, 207.78903737094635, 262.3885788772523, 316.226951361783, 368.8336445940755, 420.06460840397295, 469.81002562166196, 101.00970782167697, 155.89552189367052, 210.3982534058584, 264.16507192752834, 317.29261990558007, 369.2755474222269, 419.85385101377045, 469.08155005643766,
410.1275601822925, 411.0320047945014, 411.6115154837549, 411.76413178856507, 411.53170846505816, 410.8468994517686, 410.0749383223604, 408.82236579329094, 352.6911734612626, 353.88222801154996, 354.8418530581463, 355.46307001296077, 355.86636171875597, 355.9227752530399, 355.72307403893296, 355.32112770491875, 295.2717623705317, 296.71624962895044, 298.10851203004745, 299.1476476870004, 300.11760776718137, 300.7183058251445, 301.30253200591716, 301.80643590258603, 238.14258944451336, 239.86653197931125, 241.44571867066892, 242.9334839653305, 244.50985588031136, 245.96045515835198, 247.15602820342573, 248.43204055677325, 181.50862597428082, 183.50408392570867, 185.48891579397565, 187.5286338669944, 189.52704594808074, 191.56246710653886, 193.62240157124128, 195.60366374803445, 125.83800085780929, 128.0039309465524, 130.28172108604093, 132.64727749332698, 135.3265229245645, 138.04082049845894, 140.61661255146953, 143.51880260260336, 71.24292423931813, 73.7637828589439, 76.26360580901712, 79.26306974110837, 82.25464259975655, 85.58785180482208, 88.8609379105335, 92.32389867224812, 18.103363519108168, 20.719960397126016, 23.82758215460897, 27.051830520038266, 30.574770973198902, 34.33603808098457, 38.23308678448411, 42.382012370500085;
Matrix data5(2, 64);
data5 <<
78.69152413080967, 128.29439935441943, 177.63828694566752, 226.48313127424362, 274.5120681898539, 321.77684077639236, 368.00846360843946, 413.00920312893993, 87.2750900075558, 137.13560548427256, 186.71930701859588, 235.757047274741, 284.08995820462525, 331.47996676392114, 377.7901601525455, 422.95528530172487, 96.22722627556054, 146.3266757897717, 196.07660977250805, 245.3015525636926, 293.70515404531454, 341.27168011925556, 387.61397095150375, 432.85379725703115, 105.76987137759865, 155.90726182663596, 205.74754579084382, 255.01448793989965, 303.5249047584565, 351.1606006718723, 397.5246027866596, 442.6749445217156, 115.55515770161269, 165.7239651344489, 215.5811670509886, 264.8471636771777, 313.2797347183294, 360.92048234333413, 407.2747766363627, 452.4328355521711, 125.5000916587322, 175.75003948223736, 225.54837592523282, 274.81650943865327, 323.220998382946, 370.74171260986896, 416.95788441953715, 461.94249916671635, 135.59500108806986, 185.6240791490438, 235.34012260563037, 284.4691708117143, 332.833108988705, 380.1922222397722, 426.349378861027, 471.22500254530297, 146.81572231828488, 196.40807656079377, 245.61747263405593, 294.3435232270571, 342.2968085631704, 389.3648436325567, 435.31748654193984, 479.9683091718671,
361.274660727371, 369.9386524721016, 378.4916243402773, 386.64544523893477, 394.2401800907817, 401.6339307093484, 408.56230340859327, 415.05304633130703, 312.3582673315689, 321.4333060528775, 330.2996162749264, 338.8932021696882, 347.03871206962543, 354.8189011224688, 362.3469946965432, 369.5578590050164, 262.8284574907546, 272.1622311755597, 281.46178259575737, 290.51739617797705, 299.1425100185318, 307.5200377950307, 315.57312860649995, 323.3358006879324, 212.94380761429647, 222.5838684841567, 232.07514019977162, 241.45342474035775, 250.65898774180872, 259.63920826891535, 268.23107809439415, 276.60784060339756, 162.77631551896766, 172.68245133907658, 182.50929719856993, 192.255739265883, 201.9774639129238, 211.40237541849658, 220.57496933979866, 229.70137495840632, 112.39703788025982, 122.5925342852821, 132.81346283315006, 143.00174967590672, 153.10193278556466, 163.09280096297266, 172.93773537702012, 182.6272619160663, 62.45438144874405, 72.85382636689017, 83.37430640616488, 93.90734796651384, 104.50707669328405, 114.96845339129112, 125.44433125750037, 135.7352493232785, 12.912321760037827, 23.499184264817504, 34.31023015857057, 45.31418106954909, 56.3059646055059, 67.3109068705477, 78.14776640636657, 89.10713199270751;
Matrix model(2, 64);
model <<
0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222, 0, 0.888889, 1.77778, 2.66667, 3.55556, 4.44444, 5.33333, 6.22222,
-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -1.38889, -1.38889, -1.38889, -1.38889, -1.38889, -1.38889, -1.38889, -1.38889, -2.27778, -2.27778, -2.27778, -2.27778, -2.27778, -2.27778, -2.27778, -2.27778, -3.16667, -3.16667, -3.16667, -3.16667, -3.16667, -3.16667, -3.16667, -3.16667, -4.05556, -4.05556, -4.05556, -4.05556, -4.05556, -4.05556, -4.05556, -4.05556, -4.94444, -4.94444, -4.94444, -4.94444, -4.94444, -4.94444, -4.94444, -4.94444, -5.83333, -5.83333, -5.83333, -5.83333, -5.83333, -5.83333, -5.83333, -5.83333, -6.72222, -6.72222, -6.72222, -6.72222, -6.72222, -6.72222, -6.72222, -6.72222;
DirectLinearTransformation<Scalar> dlt;
SECTION("data1 <-> model")
{
Matrix3 H = dlt(model, data1);
Matrix dataAct = (H * model.colwise().homogeneous()).colwise().hnormalized();
REQUIRE_MATRIX_APPROX(data1, dataAct, 5);
}
SECTION("data2 <-> model")
{
Matrix3 H = dlt(model, data2);
Matrix dataAct = (H * model.colwise().homogeneous()).colwise().hnormalized();
REQUIRE_MATRIX_APPROX(data2, dataAct, 5);
}
SECTION("data3 <-> model")
{
Matrix3 H = dlt(model, data3);
Matrix dataAct = (H * model.colwise().homogeneous()).colwise().hnormalized();
REQUIRE_MATRIX_APPROX(data3, dataAct, 5);
}
SECTION("data4 <-> model")
{
Matrix3 H = dlt(model, data4);
Matrix dataAct = (H * model.colwise().homogeneous()).colwise().hnormalized();
REQUIRE_MATRIX_APPROX(data4, dataAct, 5);
}
SECTION("data5 <-> model")
{
Matrix3 H = dlt(model, data5);
Matrix dataAct = (H * model.colwise().homogeneous()).colwise().hnormalized();
REQUIRE_MATRIX_APPROX(data5, dataAct, 5);
}
}
| 171.955556 | 1,260 | 0.796976 | [
"model"
] |
5cd7e200e212086281f492cddf1ecacfdac1682a | 20,266 | cpp | C++ | glipf/src/processors/foreground-histogram-processor.cpp | cognitivesystems/smartcamera | 5374193260e6385becfe8086a70d21d650314beb | [
"BSD-2-Clause"
] | 1 | 2017-03-27T16:14:59.000Z | 2017-03-27T16:14:59.000Z | glipf/src/processors/foreground-histogram-processor.cpp | cognitivesystems/smartcamera | 5374193260e6385becfe8086a70d21d650314beb | [
"BSD-2-Clause"
] | null | null | null | glipf/src/processors/foreground-histogram-processor.cpp | cognitivesystems/smartcamera | 5374193260e6385becfe8086a70d21d650314beb | [
"BSD-2-Clause"
] | null | null | null | #include <glipf/processors/foreground-histogram-processor.h>
#include <glipf/gles-utils/shader-builder.h>
#include <glipf/gles-utils/glsl-program-builder.h>
#include <boost/variant/get.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <cstring>
#define BASE_TEXTURE_WIDTH 160
#define BASE_TEXTURE_HEIGHT 120
#define HISTOGRAM_TEXTURE_WIDTH 10
#define HISTOGRAM_TEXTURE_HEIGHT 10
#define HISTOGRAM_TEXTURE_AREA (HISTOGRAM_TEXTURE_WIDTH * HISTOGRAM_TEXTURE_HEIGHT)
#define MODEL_GRID_WIDTH 4
#define MODEL_GRID_HEIGHT 4
#define MODEL_GRID_AREA (MODEL_GRID_WIDTH * MODEL_GRID_HEIGHT)
#define MODELS_PER_GRID_CELL 2
#define MODEL_GRID_MODEL_COUNT (MODEL_GRID_AREA * MODELS_PER_GRID_CELL)
#define HALF_BASE_TEXEL_WIDTH (0.5f / (MODEL_GRID_WIDTH * BASE_TEXTURE_WIDTH))
#define HALF_BASE_TEXEL_HEIGHT (0.5f / (MODEL_GRID_HEIGHT * BASE_TEXTURE_HEIGHT))
using std::pair;
using std::string;
using std::tuple;
using std::vector;
namespace glipf {
namespace processors {
enum VertexAttributeLocations : GLuint {
kPosition = 0,
kColor = 1,
kCellOffset = 2
};
ForegroundHistogramProcessor::ForegroundHistogramProcessor(const sources::FrameProperties& frameProperties,
size_t maxModelCount,
const glm::mat4& mvpMatrix)
: GlesProcessor(frameProperties)
, mModelCount(0)
, mMaxModelCount(maxModelCount)
, mModelVertexBuffer(0)
, mModelIndexBuffer(0)
, mScatterPointsBuffer(0)
, mHistogramGlslProgram(0)
{
setupReductionGlslPrograms(mvpMatrix);
setupFbos(maxModelCount);
mHistogramGlslProgram = gles_utils::GlslProgramBuilder()
.attachShader(gles_utils::ShaderBuilder(GL_VERTEX_SHADER)
.appendSourceFile("glsl/histogram-scatter.vert")
.compile())
.attachShader(gles_utils::ShaderBuilder(GL_FRAGMENT_SHADER)
.appendSourceFile("glsl/unit-value.frag")
.compile())
.bindAttribLocation(VertexAttributeLocations::kPosition, "vertex")
.link();
glUseProgram(mHistogramGlslProgram);
glUniform1i(glGetUniformLocation(mHistogramGlslProgram, "tex"), 2);
glUniform3i(glGetUniformLocation(mHistogramGlslProgram, "gridDimensions"),
MODEL_GRID_WIDTH, MODEL_GRID_HEIGHT, MODELS_PER_GRID_CELL);
glGenBuffers(1, &mModelVertexBuffer);
glGenBuffers(1, &mModelIndexBuffer);
glGenBuffers(1, &mScatterPointsBuffer);
assertNoGlError();
for (size_t i = 0; i < maxModelCount; ++i)
mResultSet[std::to_string(i)] = vector<float>(HISTOGRAM_TEXTURE_AREA);
mResultSet["total_pixel_counts"] = vector<float>(maxModelCount);
mResultSet["histogram_coverage"] = vector<float>(maxModelCount);
}
void ForegroundHistogramProcessor::setModels(const vector<ModelData>& models,
const glm::mat4& mvpMatrix)
{
mReductionFboSets.clear();
mHistogramFboSpecs.clear();
mModelCount = models.size();
assert(mModelCount <= mMaxModelCount);
setupModelGeometry(models);
setupHistogramBuffers(models, mvpMatrix);
mModelAreas = computeModelAreas(models, mvpMatrix, BASE_TEXTURE_WIDTH,
BASE_TEXTURE_HEIGHT);
}
ForegroundHistogramProcessor::~ForegroundHistogramProcessor() {
glDeleteProgram(mHistogramGlslProgram);
glDeleteBuffers(1, &mModelVertexBuffer);
glDeleteBuffers(1, &mModelIndexBuffer);
glDeleteBuffers(1, &mScatterPointsBuffer);
glDeleteProgram(std::get<0>(mReductionFboSpecs[0]));
glDeleteFramebuffers(mHistogramFbos.size(), mHistogramFbos.data());
glDeleteTextures(mHistogramTextures.size(), mHistogramTextures.data());
glDeleteFramebuffers(mForegroundFbos.size(), mForegroundFbos.data());
glDeleteTextures(mForegroundTextures.size(), mForegroundTextures.data());
}
void ForegroundHistogramProcessor::setupReductionGlslPrograms(const glm::mat4& mvpMatrix) {
GLuint mainGlslProgram = gles_utils::GlslProgramBuilder()
.attachShader(gles_utils::ShaderBuilder(GL_VERTEX_SHADER)
.appendSourceFile("glsl/transformation.vert")
.compile())
.attachShader(gles_utils::ShaderBuilder(GL_FRAGMENT_SHADER)
.appendSourceFile("glsl/include/color-space.frag")
.appendSourceFile("glsl/histogram-foreground.frag")
.compile())
.bindAttribLocation(VertexAttributeLocations::kPosition, "vertex")
.bindAttribLocation(VertexAttributeLocations::kColor, "vertexColor")
.bindAttribLocation(VertexAttributeLocations::kCellOffset, "cellOffset")
.link();
glUseProgram(mainGlslProgram);
glUniform2f(glGetUniformLocation(mainGlslProgram, "viewportDimensions"),
mFrameProperties.dimensions().first,
mFrameProperties.dimensions().second);
glUniformMatrix4fv(glGetUniformLocation(mainGlslProgram, "projectionMatrix"),
1, GL_FALSE, glm::value_ptr(mvpMatrix));
glUniform1i(glGetUniformLocation(mainGlslProgram, "tex"), 0);
assertNoGlError();
mReductionFboSpecs.push_back(std::make_tuple(mainGlslProgram,
BASE_TEXTURE_WIDTH,
BASE_TEXTURE_HEIGHT));
}
void ForegroundHistogramProcessor::addModelForegroundFbo() {
// Prepare a texture to store the foreground of the model
GLuint averageTexture;
glActiveTexture(GL_TEXTURE3);
glGenTextures(1, &averageTexture);
glBindTexture(GL_TEXTURE_2D, averageTexture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
MODEL_GRID_WIDTH * BASE_TEXTURE_WIDTH,
MODEL_GRID_HEIGHT * BASE_TEXTURE_HEIGHT, 0, GL_RGBA,
GL_UNSIGNED_BYTE, 0);
assertNoGlError();
// Prepare an FBO to store the foreground of the model
GLuint averageFbo;
glGenFramebuffers(1, &averageFbo);
glBindFramebuffer(GL_FRAMEBUFFER, averageFbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, averageTexture, 0);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
assertNoGlError();
mForegroundTextures.push_back(averageTexture);
mForegroundFbos.push_back(averageFbo);
}
void ForegroundHistogramProcessor::addHistogramFbo() {
// Prepare a texture to store the foreground histogram of the model
GLuint histogramTexture;
glActiveTexture(GL_TEXTURE3);
glGenTextures(1, &histogramTexture);
glBindTexture(GL_TEXTURE_2D, histogramTexture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
MODELS_PER_GRID_CELL * MODEL_GRID_WIDTH * HISTOGRAM_TEXTURE_WIDTH,
MODEL_GRID_HEIGHT * HISTOGRAM_TEXTURE_HEIGHT, 0, GL_RGBA,
GL_UNSIGNED_BYTE, 0);
assertNoGlError();
// Prepare an FBO to store the foreground histogram of the model
GLuint histogramFbo;
glGenFramebuffers(1, &histogramFbo);
glBindFramebuffer(GL_FRAMEBUFFER, histogramFbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, histogramTexture, 0);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
assertNoGlError();
mHistogramTextures.push_back(histogramTexture);
mHistogramFbos.push_back(histogramFbo);
}
void ForegroundHistogramProcessor::setupFbos(size_t modelCount) {
uint_fast8_t fboCount = modelCount / MODEL_GRID_MODEL_COUNT;
if (modelCount % MODEL_GRID_MODEL_COUNT > 0)
++fboCount;
for (size_t i = 0; i < fboCount; ++i) {
addModelForegroundFbo();
addHistogramFbo();
}
}
void ForegroundHistogramProcessor::setupHistogramBuffers(const std::vector<ModelData>& models,
const glm::mat4& mvpMatrix)
{
size_t pointOffset = 0, fboScatterPointCount = 0;
vector<tuple<uint_fast16_t, uint_fast16_t, uint_fast16_t, uint_fast16_t>> bboxVertices;
size_t totalScatterPointCount = 0;
uint_fast16_t modelNumber = 0;
for (auto& model : models) {
GLfloat xMin = mFrameProperties.dimensions().first, xMax = 0.0f;
GLfloat yMin = mFrameProperties.dimensions().second, yMax = 0.0f;
for (size_t i = 0; i < model.first.size(); i += 3) {
glm::vec4 vertexVector(model.first[i], model.first[i + 1],
model.first[i + 2], 1.0);
glm::vec4 projectedPosition = mvpMatrix * vertexVector;
glm::vec2 normalizedPosition(projectedPosition.x / projectedPosition.z,
projectedPosition.y / projectedPosition.z);
if (normalizedPosition.x > xMax)
xMax = normalizedPosition.x;
if (normalizedPosition.x < xMin)
xMin = normalizedPosition.x;
if (normalizedPosition.y > yMax)
yMax = normalizedPosition.y;
if (normalizedPosition.y < yMin)
yMin = normalizedPosition.y;
}
xMin = glm::clamp(xMin / mFrameProperties.dimensions().first, 0.0f, 1.0f);
xMax = glm::clamp(xMax / mFrameProperties.dimensions().first, 0.0f, 1.0f);
yMin = glm::clamp(yMin / mFrameProperties.dimensions().second, 0.0f, 1.0f);
yMax = glm::clamp(yMax / mFrameProperties.dimensions().second, 0.0f, 1.0f);
uint_fast16_t xMinInt = glm::floor(xMin * BASE_TEXTURE_WIDTH);
uint_fast16_t xMaxInt = glm::ceil(xMax * BASE_TEXTURE_WIDTH);
uint_fast16_t yMinInt = glm::floor(yMin * BASE_TEXTURE_HEIGHT);
uint_fast16_t yMaxInt = glm::ceil(yMax * BASE_TEXTURE_HEIGHT);
bboxVertices.push_back(std::make_tuple(xMinInt, xMaxInt, yMinInt, yMaxInt));
size_t modelScatterPointCount = (xMaxInt - xMinInt) * (yMaxInt - yMinInt);
fboScatterPointCount += modelScatterPointCount;
totalScatterPointCount += modelScatterPointCount;
if (++modelNumber % MODEL_GRID_MODEL_COUNT == 0) {
mHistogramFboSpecs.push_back(std::make_pair(pointOffset,
fboScatterPointCount));
pointOffset += fboScatterPointCount;
fboScatterPointCount = 0;
}
}
if (fboScatterPointCount > 0)
mHistogramFboSpecs.push_back(std::make_pair(pointOffset,
fboScatterPointCount));
GLfloat* pointData = new GLfloat[totalScatterPointCount * 3];
size_t pointDataOffset = 0;
modelNumber = 0;
for (auto& bboxVertexSet : bboxVertices) {
auto modelGridCellNumber = (modelNumber++ % MODEL_GRID_MODEL_COUNT);
auto modelGridLocX = modelGridCellNumber %
(MODELS_PER_GRID_CELL * MODEL_GRID_WIDTH);
auto modelGridLocY = modelGridCellNumber /
(MODELS_PER_GRID_CELL * MODEL_GRID_WIDTH);
uint_fast16_t xMinInt, xMaxInt, yMinInt, yMaxInt;
std::tie(xMinInt, xMaxInt, yMinInt, yMaxInt) = bboxVertexSet;
for (size_t i = yMinInt; i < yMaxInt; ++i) {
for (size_t j = xMinInt; j < xMaxInt; ++j) {
pointData[pointDataOffset++] =
((modelGridLocX / MODELS_PER_GRID_CELL) * BASE_TEXTURE_WIDTH + j) /
static_cast<GLfloat>(MODEL_GRID_WIDTH * BASE_TEXTURE_WIDTH) +
HALF_BASE_TEXEL_WIDTH;
pointData[pointDataOffset++] =
(modelGridLocY * BASE_TEXTURE_HEIGHT + i) /
static_cast<GLfloat>(MODEL_GRID_HEIGHT * BASE_TEXTURE_HEIGHT) +
HALF_BASE_TEXEL_HEIGHT;
pointData[pointDataOffset++] = modelGridCellNumber % 2;
}
}
}
glBindBuffer(GL_ARRAY_BUFFER, mScatterPointsBuffer);
glBufferData(GL_ARRAY_BUFFER, totalScatterPointCount * 3 * sizeof(GLfloat),
pointData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
assertNoGlError();
delete[] pointData;
}
void ForegroundHistogramProcessor::setupModelGeometry(const std::vector<ModelData>& models) {
size_t vertexCount = 0, indexCount = 0, fboIndexCount = 0;
ptrdiff_t vertexOffset = 0;
ptrdiff_t indexOffset = 0;
unsigned short int modelNumber = 0;
for (auto& model : models) {
vertexCount += model.first.size();
indexCount += model.second.size();
fboIndexCount += model.second.size();
if (++modelNumber % MODEL_GRID_MODEL_COUNT == 0) {
mReductionFboSets.push_back(std::make_tuple(modelNumber,
indexOffset * sizeof(GLushort),
fboIndexCount));
indexOffset += fboIndexCount;
fboIndexCount = 0;
modelNumber = 0;
}
}
if (fboIndexCount > 0)
mReductionFboSets.push_back(std::make_tuple(modelNumber,
indexOffset * sizeof(GLushort),
fboIndexCount));
GLfloat vertexData[vertexCount * 3];
GLushort indexData[indexCount];
memset(vertexData, 0, sizeof(vertexData));
indexOffset = 0;
modelNumber = 0;
for (auto& model : models) {
uint_fast8_t modelColorChannel = 2 * (modelNumber % 2);
auto modelGridCellNumber = (modelNumber % MODEL_GRID_MODEL_COUNT) /
MODELS_PER_GRID_CELL;
auto modelGridLocX = modelGridCellNumber % MODEL_GRID_WIDTH;
auto modelGridLocY = modelGridCellNumber / MODEL_GRID_WIDTH;
for (size_t i = 0; i < model.first.size(); i += 3) {
memcpy(vertexData + vertexOffset + i * 3, model.first.data() + i,
3 * sizeof(GLfloat));
vertexData[vertexOffset + i * 3 + 3 + modelColorChannel] = 1.0;
vertexData[vertexOffset + i * 3 + 4 + modelColorChannel] = 1.0;
vertexData[vertexOffset + i * 3 + 7] = modelGridLocX;
vertexData[vertexOffset + i * 3 + 8] = modelGridLocY;
}
for (size_t i = 0; i < model.second.size(); ++i)
indexData[indexOffset + i] = model.second[i] + vertexOffset / 9;
modelNumber++;
vertexOffset += model.first.size() * 3;
indexOffset += model.second.size();
}
glBindBuffer(GL_ARRAY_BUFFER, mModelVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData,
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
assertNoGlError();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mModelIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData,
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
assertNoGlError();
}
const ProcessingResultSet& ForegroundHistogramProcessor::process(GLuint frameTexture) {
auto reductionSpecIter = std::begin(mReductionFboSpecs);
GLuint reductionGlslProgram;
uint_fast16_t fboWidth, fboHeight;
std::tie(reductionGlslProgram, fboWidth, fboHeight) = *reductionSpecIter;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, frameTexture);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glBlendEquation(GL_FUNC_ADD);
glEnableVertexAttribArray(VertexAttributeLocations::kPosition);
glEnableVertexAttribArray(VertexAttributeLocations::kColor);
glEnableVertexAttribArray(VertexAttributeLocations::kCellOffset);
// Step 1: preprocessing
glViewport(0, 0, MODEL_GRID_WIDTH * fboWidth, MODEL_GRID_HEIGHT * fboHeight);
glUseProgram(reductionGlslProgram);
glBindBuffer(GL_ARRAY_BUFFER, mModelVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mModelIndexBuffer);
glVertexAttribPointer(VertexAttributeLocations::kPosition, 3, GL_FLOAT,
GL_FALSE, 9 * sizeof(GLfloat), 0);
glVertexAttribPointer(VertexAttributeLocations::kColor, 4, GL_FLOAT,
GL_FALSE, 9 * sizeof(GLfloat),
(GLvoid*)(3 * sizeof(GLfloat)));
glVertexAttribPointer(VertexAttributeLocations::kCellOffset, 2, GL_FLOAT,
GL_FALSE, 9 * sizeof(GLfloat),
(GLvoid*)(7 * sizeof(GLfloat)));
auto foregroundFboIter = std::begin(mForegroundFbos);
for (auto& reductionFboSet : mReductionFboSets) {
glBindFramebuffer(GL_FRAMEBUFFER, *(foregroundFboIter++));
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, std::get<2>(reductionFboSet),
GL_UNSIGNED_SHORT, (GLvoid*)std::get<1>(reductionFboSet));
assertNoGlError();
}
// Step 2: compute histograms by scattering points
glDisableVertexAttribArray(VertexAttributeLocations::kColor);
glDisableVertexAttribArray(VertexAttributeLocations::kCellOffset);
glActiveTexture(GL_TEXTURE2);
glBindBuffer(GL_ARRAY_BUFFER, mScatterPointsBuffer);
glVertexAttribPointer(VertexAttributeLocations::kPosition, 3, GL_FLOAT,
GL_FALSE, 3 * sizeof(GLfloat), 0);
glViewport(0, 0,
MODELS_PER_GRID_CELL * MODEL_GRID_WIDTH * HISTOGRAM_TEXTURE_WIDTH,
MODEL_GRID_HEIGHT * HISTOGRAM_TEXTURE_HEIGHT);
glUseProgram(mHistogramGlslProgram);
auto foregroundTextureIter = std::begin(mForegroundTextures);
auto histogramFboIter = std::begin(mHistogramFbos);
for (auto& histogramFboSpec : mHistogramFboSpecs) {
glBindTexture(GL_TEXTURE_2D, *(foregroundTextureIter++));
glBindFramebuffer(GL_FRAMEBUFFER, *(histogramFboIter++));
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_POINTS, std::get<0>(histogramFboSpec),
std::get<1>(histogramFboSpec));
}
glDisable(GL_BLEND);
glDisableVertexAttribArray(VertexAttributeLocations::kPosition);
size_t modelNumber = 0;
size_t modelCount = mModelCount;
auto& totalPixelCounts =
boost::get<vector<float>>(mResultSet["total_pixel_counts"]);
auto& histogramCoverage =
boost::get<vector<float>>(mResultSet["histogram_coverage"]);
// Step 3: extract histograms
for (auto histogramFbo: mHistogramFbos) {
glBindFramebuffer(GL_FRAMEBUFFER, histogramFbo);
GLubyte pixelData[MODELS_PER_GRID_CELL * MODEL_GRID_AREA *
HISTOGRAM_TEXTURE_WIDTH * HISTOGRAM_TEXTURE_HEIGHT * 4];
glReadPixels(0, 0,
MODELS_PER_GRID_CELL * MODEL_GRID_WIDTH * HISTOGRAM_TEXTURE_WIDTH,
MODEL_GRID_HEIGHT * HISTOGRAM_TEXTURE_HEIGHT, GL_RGBA,
GL_UNSIGNED_BYTE, pixelData);
uint_fast16_t offset = 0;
for (uint_fast16_t i = 0; i < MODEL_GRID_HEIGHT; ++i) {
vector<vector<uint_fast16_t>> histogramVectors(8);
vector<uint_fast16_t> histogramTotals(8);
for (uint_fast16_t j = 0; j < HISTOGRAM_TEXTURE_HEIGHT; ++j) {
for (uint_fast16_t k = 0;
k < MODELS_PER_GRID_CELL * MODEL_GRID_WIDTH * HISTOGRAM_TEXTURE_WIDTH;
k += 1)
{
uint_fast8_t histogramIndex = k / HISTOGRAM_TEXTURE_WIDTH;
uint_fast16_t bucketValue = pixelData[offset] +
pixelData[offset + 1] +
pixelData[offset + 2] +
pixelData[offset + 3];
histogramVectors[histogramIndex].push_back(bucketValue);
histogramTotals[histogramIndex] += bucketValue;
offset += 4;
}
}
for (uint_fast8_t j = 0; j < std::min(modelCount, 8u); ++j) {
auto& resultHistogram = histogramVectors[j];
auto& normalizedHistogram =
boost::get<vector<float>>(mResultSet[std::to_string(modelNumber)]);
float histogramTotal = histogramTotals[j];
histogramCoverage[modelNumber] =
histogramTotal / mModelAreas[modelNumber];
totalPixelCounts[modelNumber++] = histogramTotal;
if (histogramTotal == 0) {
for (uint_fast16_t k = 0; k < HISTOGRAM_TEXTURE_AREA; ++k)
normalizedHistogram[k] = 0.0f;
} else {
for (uint_fast16_t k = 0; k < HISTOGRAM_TEXTURE_AREA; ++k)
normalizedHistogram[k] = resultHistogram[k] / histogramTotal;
}
}
if (modelCount < 8)
return mResultSet;
modelCount -= 8;
}
}
return mResultSet;
}
} // end namespace processors
} // end namespace glipf
| 38.675573 | 107 | 0.690072 | [
"vector",
"model"
] |
5cdb755955a3875590bc64b28d997ab161a4952a | 1,952 | hpp | C++ | src/vm/object_support/factory.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 10 | 2020-01-23T20:41:19.000Z | 2021-12-28T20:24:44.000Z | src/vm/object_support/factory.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | 22 | 2021-03-25T16:22:08.000Z | 2022-03-17T12:50:38.000Z | src/vm/object_support/factory.hpp | mbeckem/tiro | b3d729fce46243f25119767c412c6db234c2d938 | [
"MIT"
] | null | null | null | #ifndef TIRO_VM_OBJECT_SUPPORT_FACTORY_HPP
#define TIRO_VM_OBJECT_SUPPORT_FACTORY_HPP
#include "common/assert.hpp"
#include "common/defs.hpp"
#include "vm/context.hpp"
#include "vm/object_support/layout.hpp"
namespace tiro::vm {
namespace detail {
template<typename Layout, typename... Args>
inline Layout* create_impl(Heap& heap, Header* type, Args&&... args) {
using Traits = LayoutTraits<Layout>;
static_assert(
Traits::has_static_size, "the layout has dynamic size, use create_varsize instead");
return heap.template create<Layout>(Traits::static_size, type, std::forward<Args>(args)...);
}
template<typename Layout, typename SizeArg, typename... Args>
inline Layout* create_varsize_impl(Heap& heap, Header* type, SizeArg&& size_arg, Args&&... args) {
using Traits = LayoutTraits<Layout>;
static_assert(!Traits::has_static_size, "the layout has static size, use create() instead");
const size_t total_byte_size = Traits::dynamic_alloc_size(size_arg);
Layout* data = heap.template create<Layout>(total_byte_size, type, std::forward<Args>(args)...);
TIRO_DEBUG_ASSERT(Traits::dynamic_size(data) == total_byte_size,
"byte size mismatch between requested and calculated dynamic object size");
return data;
}
} // namespace detail
template<typename BuiltinType, typename... LayoutArgs>
auto create_object(Context& ctx, LayoutArgs&&... layout_args) {
using Layout = typename BuiltinType::Layout;
auto type = ctx.types().raw_internal_type<BuiltinType>(); // rooted by the TypeSystem instance
if constexpr (LayoutTraits<Layout>::has_static_size) {
return detail::create_impl<Layout>(
ctx.heap(), type, std::forward<LayoutArgs>(layout_args)...);
} else {
return detail::create_varsize_impl<Layout>(
ctx.heap(), type, std::forward<LayoutArgs>(layout_args)...);
}
}
} // namespace tiro::vm
#endif // TIRO_VM_OBJECT_SUPPORT_FACTORY_HPP
| 36.830189 | 100 | 0.722848 | [
"object"
] |
5ce527610d7612f56a69ededb4afdeb4293582f2 | 23,388 | cpp | C++ | CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Weapon/CsFpsWeapon.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Weapon/CsFpsWeapon.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsCoreDEPRECATED/Source/CsCoreDEPRECATED/Weapon/CsFpsWeapon.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2019 Closed Sum Games, LLC. All Rights Reserved.
#include "Weapon/CsFpsWeapon.h"
#include "CsCoreDEPRECATED.h"
#include "CsCVars.h"
// Library
#include "Library/CsLibrary_Common.h"
// Pawn
#include "Player/CsFpsPawn.h"
// Anim
#include "Animation/CsAnimInstance_Character.h"
#include "Animation/CsAnimInstance_Weapon.h"
// Data
#include "Data/CsData_ProjectileWeapon_DEPRECATED.h"
#include "Data/CsData_Character.h"
#include "Data/CsData_WeaponMaterialSkin.h"
// Components
#include "Components/CsSkeletalMeshComponent.h"
// Enums
#pragma region
namespace ECsFpsWeaponMultiValueMember
{
// Spread
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember MovingSpreadBonus = EMCsWeaponMultiValueMember::Get().Create(TEXT("MovingSpreadBonus"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember JumpSpreadImpulse = EMCsWeaponMultiValueMember::Get().Create(TEXT("JumpSpreadImpulse"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember ScopeAccuracyBonus = EMCsWeaponMultiValueMember::Get().Create(TEXT("ScopeAccuracyBonus"));
// Scope
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember DoScopePower = EMCsWeaponMultiValueMember::Get().Create(TEXT("DoScopePower"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember MaxScopePower = EMCsWeaponMultiValueMember::Get().Create(TEXT("MaxScopePower"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember ScopePowerGrowthRate = EMCsWeaponMultiValueMember::Get().Create(TEXT("ScopePowerGrowthRate"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember CurrentScopePower = EMCsWeaponMultiValueMember::Get().Create(TEXT("CurrentScopePower"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember LastScopePower = EMCsWeaponMultiValueMember::Get().Create(TEXT("LastScopePower"));
// Movement
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember DoSlowWhileFiring = EMCsWeaponMultiValueMember::Get().Create(TEXT("DoSlowWhileFiring"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember SlowWhileFiringRate = EMCsWeaponMultiValueMember::Get().Create(TEXT("SlowWhileFiringRate"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember DoKickback = EMCsWeaponMultiValueMember::Get().Create(TEXT("DoKickback"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember DoKickbackOnGround = EMCsWeaponMultiValueMember::Get().Create(TEXT("DoKickbackOnGround"));
CSCOREDEPRECATED_API const FECsWeaponMultiValueMember KickbackStrength = EMCsWeaponMultiValueMember::Get().Create(TEXT("KickbackStrength"));
}
#pragma endregion Enums
ACsFpsWeapon::ACsFpsWeapon(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
Mesh1P = ObjectInitializer.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("Mesh1P"));
Mesh1P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::OnlyTickPoseWhenRendered;
Mesh1P->bReceivesDecals = false;
Mesh1P->CastShadow = false;
Mesh1P->SetHiddenInGame(true);
Mesh1P->SetVisibility(false);
Mesh1P->SetOnlyOwnerSee(true);
Mesh1P->SetOwnerNoSee(false);
Mesh1P->SetCollisionObjectType(ECC_WorldDynamic);
Mesh1P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
Mesh1P->SetCollisionResponseToAllChannels(ECR_Ignore);
Mesh1P->SetRenderCustomDepth(true);
Mesh1P->Deactivate();
Mesh1P->PrimaryComponentTick.bStartWithTickEnabled = false;
RootComponent = Mesh1P;
Mesh3P = ObjectInitializer.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("Mesh3P"));
Mesh3P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::OnlyTickPoseWhenRendered;
Mesh3P->bReceivesDecals = false;
Mesh3P->CastShadow = false;
Mesh3P->bCastDynamicShadow = false;
Mesh3P->SetHiddenInGame(true);
Mesh3P->SetVisibility(false);
Mesh3P->SetOnlyOwnerSee(false);
Mesh3P->SetOwnerNoSee(true);
Mesh3P->SetCollisionObjectType(ECC_WorldDynamic);
Mesh3P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
Mesh3P->SetCollisionResponseToAllChannels(ECR_Ignore);
Mesh3P->SetRenderCustomDepth(true);
//Mesh3P->SetCollisionResponseToChannel(COLLISION_WEAPON, ECR_Block);
//Mesh3P->SetCollisionResponseToChannel(ECC_Visibility, ECR_Block);
//Mesh3P->SetCollisionResponseToChannel(COLLISION_PROJECTILE, ECR_Block);
Mesh3P->Deactivate();
Mesh3P->SetupAttachment(Mesh1P);
Mesh3P->PrimaryComponentTick.bStartWithTickEnabled = false;
}
// Members
#pragma region
void ACsFpsWeapon::InitMultiValueMembers()
{
Super::InitMultiValueMembers();
// Spread
{
InitMultiRefValueMember<float>(MovingSpreadBonus, 0.0f);
MovingSpreadBonus.GetDelegate.BindUObject(this, &ACsFpsWeapon::GetMovingSpreadBonus);
InitMultiRefValueMember<float>(JumpSpreadImpulse, 0.0f);
JumpSpreadImpulse.GetDelegate.BindUObject(this, &ACsFpsWeapon::GetJumpSpreadImpulse);
InitMultiRefValueMember<float>(ScopeAccuracyBonus, 0.0f);
ScopeAccuracyBonus.GetDelegate.BindUObject(this, &ACsFpsWeapon::GetScopeAccuracyBonus);
}
// Scope
{
InitMultiRefValueMember<bool>(DoScopePower, false);
InitMultiRefValueMember<float>(MaxScopePower, 0.0f);
MaxScopePower.GetDelegate.BindUObject(this, &ACsFpsWeapon::GetMaxScopePower);
InitMultiRefValueMember<float>(ScopePowerGrowthRate, 0.0f);
ScopePowerGrowthRate.GetDelegate.BindUObject(this, &ACsFpsWeapon::GetScopePowerGrowthRate);
InitMultiValueMember<float>(CurrentScopePower, 0.0f);
InitMultiValueMember<float>(LastScopePower, 0.0f);
}
// Movement
{
InitMultiRefValueMember<bool>(DoSlowWhileFiring, false);
InitMultiRefValueMember<float>(SlowWhileFiringRate, 0.0f);
InitMultiRefValueMember<bool>(DoKickback, false);
InitMultiRefValueMember<bool>(DoKickbackOnGround, false);
InitMultiRefValueMember<float>(KickbackStrength, 0.0f);
}
}
// Set
#pragma region
void ACsFpsWeapon::SetMemberValue_float(const FECsWeaponMultiValueMember& Member, const FECsWeaponFireMode& FireMode, const float &Value)
{
if (Member.Value < ECsFpsWeaponMultiValueMember::MovingSpreadBonus.Value)
{
Super::SetMemberValue_float(Member, FireMode, Value);
}
else
{
// Firing
{
// Scope
if (Member == ECsFpsWeaponMultiValueMember::CurrentScopePower) { CurrentScopePower.Set(FireMode, Value); }
if (Member == ECsFpsWeaponMultiValueMember::LastScopePower) { CurrentScopePower.Set(FireMode, Value); }
}
}
}
void ACsFpsWeapon::SetMultiValueMembers()
{
Super::SetMultiValueMembers();
// Movement
{
// DoSlowWhileFiring
SetMemberMultiRefValue<bool>(DoSlowWhileFiring, MovementDataFireMode, TEXT("DoSlowWhileFiring"));
// SlowWhileFiringRate
SetMemberMultiRefValue<float>(SlowWhileFiringRate, MovementDataFireMode, TEXT("SlowWhileFiringRate"));
// DoKickback
SetMemberMultiRefValue<bool>(DoKickback, MovementDataFireMode, TEXT("DoKickback"));
// DoKickbackOnGround
SetMemberMultiRefValue<bool>(DoKickbackOnGround, MovementDataFireMode, TEXT("DoKickbackOnGround"));
// KickbackStrength
SetMemberMultiRefValue<float>(KickbackStrength, MovementDataFireMode, TEXT("KickbackStrength"));
}
// Aiming
{
// MovingSpreadBonus
SetMemberMultiRefValue<float>(MovingSpreadBonus, AimingDataFireMode, TEXT("MovingSpreadBonus"));
// JumpSpreadImpulse
SetMemberMultiRefValue<float>(JumpSpreadImpulse, AimingDataFireMode, TEXT("JumpSpreadImpulse"));
// ScopeAccuracyBonus
SetMemberMultiRefValue<float>(ScopeAccuracyBonus, AimingDataFireMode, TEXT("ScopeAccuracyBonus"));
}
// Scope
{
// DoScopePower
SetMemberMultiRefValue<bool>(DoScopePower, ScopeDataFireMode, TEXT("DoScopePower"));
// MaxScopePower
SetMemberMultiRefValue<float>(MaxScopePower, ScopeDataFireMode, TEXT("MaxScopePower"));
// ScopePowerGrowthRate
SetMemberMultiRefValue<float>(ScopePowerGrowthRate, ScopeDataFireMode, TEXT("ScopePowerGrowthRate"));
// CurrentScopePower
SetMemberMultiValue<float>(CurrentScopePower, 0.0f);
}
}
#pragma endregion Set
// Get
#pragma region
bool ACsFpsWeapon::GetMemberValue_bool(const FECsWeaponMultiValueMember& Member, const FECsWeaponFireMode& FireMode)
{
if (Member.Value < ECsFpsWeaponMultiValueMember::MovingSpreadBonus.Value)
{
return GetMemberValue_bool(Member, FireMode);
}
else
{
// Firing
{
// Scope
if (Member == ECsFpsWeaponMultiValueMember::DoScopePower) { return DoScopePower[FireMode]; }
}
// Movement
{
if (Member == ECsFpsWeaponMultiValueMember::DoSlowWhileFiring) { return DoSlowWhileFiring[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::DoKickback) { return DoKickback[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::DoKickbackOnGround) { return DoKickbackOnGround[FireMode]; }
}
}
return false;
}
float ACsFpsWeapon::GetMemberValue_float(const FECsWeaponMultiValueMember& Member, const FECsWeaponFireMode& FireMode)
{
if (Member.Value < ECsFpsWeaponMultiValueMember::MovingSpreadBonus.Value)
{
return GetMemberValue_float(Member, FireMode);
}
else
{
// Firing
{
// Spread
if (Member == ECsFpsWeaponMultiValueMember::MovingSpreadBonus) { return MovingSpreadBonus[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::JumpSpreadImpulse) { return JumpSpreadImpulse[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::ScopeAccuracyBonus) { return ScopeAccuracyBonus[FireMode]; }
// Scope
if (Member == ECsFpsWeaponMultiValueMember::MaxScopePower) { return MaxScopePower[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::ScopePowerGrowthRate) { return ScopePowerGrowthRate[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::CurrentScopePower) { return CurrentScopePower[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::LastScopePower) { return LastScopePower[FireMode]; }
}
// Movement
{
if (Member == ECsFpsWeaponMultiValueMember::SlowWhileFiringRate) { return SlowWhileFiringRate[FireMode]; }
if (Member == ECsFpsWeaponMultiValueMember::KickbackStrength) { return KickbackStrength[FireMode]; }
}
}
return 0.0f;
}
#pragma endregion Get
#pragma endregion Members
// Owner
#pragma region
void ACsFpsWeapon::AttachMeshToPawn()
{
UCsData_Character* Data_Character = nullptr;
const ECsViewType ViewType = GetCurrentViewType();
USkeletalMeshComponent* CharacterMesh = GetCharacterMesh(ViewType);
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
if (UCsAnimInstance_Character* AnimInstance = GetMyOwner<UCsAnimInstance_Character>())
Data_Character = AnimInstance->GetData();
}
else
#endif // #if WITH_EDITOR
{
if (MyOwnerType == PawnWeaponOwner)
Data_Character = GetMyPawn()->GetMyData_Character();
}
if (!Data_Character)
return;
const FName WeaponBone = Data_Character->GetBoneToAttachWeaponTo();
//const FName MeleeBone = Data_Character->BoneToAttachMeleeItemTo;
// 1P
if (ViewType == ECsViewType::FirstPerson)
{
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
Mesh1P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones;
Mesh1P->SetOnlyOwnerSee(false);
Mesh1P->SetOwnerNoSee(false);
}
#endif // #if WITH_EDITOR
Mesh3P->DetachFromComponent(FDetachmentTransformRules::KeepRelativeTransform);
SetRootComponent(Mesh1P);
if (IsEquipped)
{
Mesh1P->SetHiddenInGame(false);
Mesh1P->SetVisibility(true);
}
Mesh1P->AttachToComponent(CharacterMesh, FAttachmentTransformRules::KeepRelativeTransform, WeaponBone);
//Mesh1P->SetAnimInstanceClass(WeaponData->AnimBlueprints.Blueprint1P);
//MeleeAttachment1P->AttachToComponent(PawnMesh1P, FAttachmentTransformRules::KeepRelativeTransform, MeleeAttachmentPoint);
if (IsEquipped)
{
Mesh1P->Activate();
Mesh1P->SetComponentTickEnabled(true);
Mesh1P->UpdateComponentToWorld(EUpdateTransformFlags::None, ETeleportType::None);
}
Mesh3P->SetHiddenInGame(true);
}
// 3P
if (ViewType == ECsViewType::ThirdPerson)
{
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
Mesh3P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones;
Mesh3P->SetOnlyOwnerSee(false);
Mesh3P->SetOwnerNoSee(false);
}
#endif // #if WITH_EDITOR
Mesh1P->DetachFromComponent(FDetachmentTransformRules::KeepRelativeTransform);
SetRootComponent(Mesh3P);
if (IsEquipped)
{
Mesh3P->SetHiddenInGame(false);
Mesh3P->SetVisibility(true);
Mesh3P->SetCastShadow(true);
}
Mesh3P->AttachToComponent(CharacterMesh, FAttachmentTransformRules::KeepRelativeTransform, WeaponBone);
//MeleeAttachment3P->AttachToComponent(PawnMesh1P, FAttachmentTransformRules::KeepRelativeTransform, MeleeAttachmentPoint);
if (IsEquipped)
{
Mesh3P->Activate();
Mesh3P->SetComponentTickEnabled(true);
Mesh3P->UpdateComponentToWorld(EUpdateTransformFlags::None, ETeleportType::None);
}
Mesh1P->SetHiddenInGame(true);
}
}
USkeletalMeshComponent* ACsFpsWeapon::GetCharacterMesh(const ECsViewType& ViewType)
{
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
if (UCsAnimInstance_Character* AnimInstance = GetMyOwner<UCsAnimInstance_Character>())
return AnimInstance->GetSkeletalMeshComponent();
}
else
#endif // #if WITH_EDITOR
{
ACsFpsPawn* Pawn = GetMyPawn<ACsFpsPawn>();
if (MyOwnerType == PawnWeaponOwner)
return ViewType == ECsViewType::FirstPerson ? Cast<USkeletalMeshComponent>(Pawn->Mesh1P) : Pawn->GetMesh();
}
return nullptr;
}
#pragma endregion Owner
// State
#pragma region
void ACsFpsWeapon::OnTick(const float &DeltaSeconds)
{
#if WITH_EDITOR
if (Override_OnTick_ScriptEvent.IsBound())
{
if (CsCVarLogOverrideFunctions->GetInt() == CS_CVAR_DISPLAY)
{
UE_LOG(LogCsCoreDEPRECATED, Warning, TEXT("ACsFpsWeapon::OnTick (%s): Using Override Function."), *GetName());
}
Override_OnTick_ScriptEvent.Broadcast(WeaponSlot, DeltaSeconds);
return;
}
#endif // #if WITH_EDITOR
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
}
// In Game
else
#endif // #if WITH_EDITOR
{
const float TimeSeconds = GetWorld()->GetTimeSeconds();
ACsPawn* MyOwnerAsPawn = GetMyPawn();
// Spread
const int32& Count = EMCsWeaponFireMode::Get().Num();
for (int32 I = 0; I < Count; ++I)
{
const FECsWeaponFireMode& FireMode = EMCsWeaponFireMode::Get().GetEnumAt(I);
if (DoSpread[FireMode])
{
// Jumping
if (!Last_OwnerIsFalling && MyOwnerAsPawn->GetCharacterMovement()->IsFalling())
{
CurrentBaseSpread.Add(FireMode, JumpSpreadImpulse[FireMode]);
}
Last_OwnerIsFalling = MyOwnerAsPawn->GetCharacterMovement()->IsFalling();
// Firing
if (TimeSeconds - LastSpreadFireTime[FireMode] > FiringSpreadRecoveryDelay[FireMode])
{
CurrentBaseSpread.Set(FireMode, FMath::Max(CurrentBaseSpread[FireMode] - (SpreadRecoveryRate.GetEX(FireMode) * DeltaSeconds), MinSpread.GetEX(FireMode)));
}
// Moving
const float MovingThreshold = 0.5f;
const bool IsMoving = MyOwnerAsPawn->CurrentSpeed > MovingThreshold;
float Bonus = IsMoving ? MovingSpreadBonus[FireMode]: 0.f;
Bonus -= IsScopeActive ? ScopeAccuracyBonus[FireMode]: 0.f;
CurrentSpread.Set(FireMode, FMath::Clamp(CurrentBaseSpread[FireMode] + Bonus, 0.f, MaxSpread[FireMode]));
}
}
}
#if WITH_EDITOR
OnTick_ScriptEvent.Broadcast(WeaponSlot, DeltaSeconds);
#endif // #if WITH_EDITOR
OnTick_HandleStates();
Last_IsFirePressed = IsFirePressed;
}
void ACsFpsWeapon::Disable()
{
Super::Disable();
IsScopeActive = false;
IsScopeActive_Toggle = false;
}
void ACsFpsWeapon::Show()
{
const ECsViewType ViewType = GetCurrentViewType();
Mesh1P->SetHiddenInGame(ViewType != ECsViewType::FirstPerson);
Mesh1P->SetVisibility(ViewType == ECsViewType::FirstPerson);
Mesh1P->SetComponentTickEnabled(ViewType == ECsViewType::FirstPerson);
// 1P
if (ViewType == ECsViewType::FirstPerson)
{
Mesh1P->Activate();
Mesh1P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones;
Mesh1P->UpdateComponentToWorld();
}
// 3P
if (ViewType == ECsViewType::ThirdPerson ||
GetLocalRole() == ROLE_Authority)
{
if (ViewType == ECsViewType::ThirdPerson)
{
Mesh3P->SetHiddenInGame(false);
Mesh3P->SetVisibility(true);
}
Mesh3P->Activate();
Mesh3P->SetComponentTickEnabled(true);
Mesh3P->UpdateComponentToWorld();
}
}
void ACsFpsWeapon::Hide()
{
// 1P
Mesh1P->SetHiddenInGame(true);
Mesh1P->SetVisibility(false);
Mesh1P->Deactivate();
Mesh1P->SetComponentTickEnabled(false);
//Cast<UCsAnimInstance>(Mesh1P->GetAnimInstance())->StopAllMontagesEX(0.0f);
Mesh1P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::OnlyTickPoseWhenRendered;
// 3P
Mesh3P->SetHiddenInGame(true);
Mesh3P->SetVisibility(false);
Mesh3P->Deactivate();
Mesh3P->SetComponentTickEnabled(false);
//Cast<UCsAnimInstance>(Mesh3P->GetAnimInstance())->StopAllMontagesEX(0.0f);
Mesh3P->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::OnlyTickPoseWhenRendered;
}
#pragma endregion State
// Mesh
#pragma region
void ACsFpsWeapon::SetMesh()
{
const ECsViewType ViewType = GetCurrentViewType();
// 1P
if (ViewType == ECsViewType::FirstPerson)
SetMesh1P();
// 3P
if (ViewType == ECsViewType::ThirdPerson)
SetMesh3P();
}
void ACsFpsWeapon::SetMesh1P()
{
Mesh1P->SetAnimInstanceClass(nullptr);
UCsData_Weapon_DEPRECATED* Data_Weapon = GetMyData_Weapon();
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
USkeletalMeshComponent* Mesh = nullptr;
// Character
if (UCsAnimInstance_Character* AnimInstance = GetMyOwner<UCsAnimInstance_Character>())
{
Mesh = Mesh1P;
Data_Weapon->SetMesh(Mesh, ECsViewType::FirstPerson);
Data_Weapon->SetAnimBlueprint(Mesh, ECsViewType::FirstPerson);
}
// Weapon
if (UCsAnimInstance_Weapon* AnimInstance = GetMyOwner<UCsAnimInstance_Weapon>())
Mesh = AnimInstance->GetSkeletalMeshComponent();
if (!Mesh)
return;
if (UCsData_WeaponMaterialSkin* Skin = GetMyData_WeaponMaterialSkin())
{
Skin->SetMaterials(Mesh, ECsViewType::FirstPerson);
UCsLibrary_Common::SetMIDs(Mesh, MeshMIDs1P, *Skin->GetMaterials(ECsViewType::FirstPerson));
}
else
{
TArray<UMaterialInstanceConstant*> Materials;
Data_Weapon->GetDefaultMaterials(Materials, ECsViewType::FirstPerson);
UCsLibrary_Common::SetMIDs(Mesh, MeshMIDs1P, Materials);
}
return;
}
// In Game
#endif // #if WITH_EDITOR
{
Data_Weapon->SetMesh(Mesh1P, ECsViewType::FirstPerson);
Data_Weapon->SetAnimBlueprint(Mesh1P, ECsViewType::FirstPerson);
if (UCsData_WeaponMaterialSkin* Skin = GetMyData_WeaponMaterialSkin())
{
Skin->SetMaterials(Mesh1P, ECsViewType::FirstPerson);
UCsLibrary_Common::SetMIDs(Mesh1P, MeshMIDs1P, *Skin->GetMaterials(ECsViewType::FirstPerson));
}
else
{
TArray<UMaterialInstanceConstant*> Materials;
Data_Weapon->GetDefaultMaterials(Materials, ECsViewType::FirstPerson);
UCsLibrary_Common::SetMIDs(Mesh1P, MeshMIDs1P, Materials);
}
//Mesh1P->SetRelativeScale3D(Data_Weapon->Mesh1PScale);
}
}
void ACsFpsWeapon::SetMesh3P()
{
Mesh3P->SetAnimInstanceClass(nullptr);
UCsData_Weapon_DEPRECATED* Data_Weapon = GetMyData_Weapon();
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
USkeletalMeshComponent* Mesh = nullptr;
// Character
if (UCsAnimInstance_Character* AnimInstance = GetMyOwner<UCsAnimInstance_Character>())
{
Mesh = Mesh3P;
Data_Weapon->SetMesh(Mesh3P, ECsViewType::ThirdPerson, UseMesh3PLow);
Data_Weapon->SetAnimBlueprint(Mesh3P, ECsViewType::ThirdPerson, UseMesh3PLow);
}
// Weapon
if (UCsAnimInstance_Weapon* AnimInstance = GetMyOwner<UCsAnimInstance_Weapon>())
Mesh = AnimInstance->GetSkeletalMeshComponent();
if (!Mesh)
return;
if (UCsData_WeaponMaterialSkin* Skin = GetMyData_WeaponMaterialSkin())
{
Skin->SetMaterials(Mesh, ECsViewType::ThirdPerson);
UCsLibrary_Common::SetMIDs(Mesh, MeshMIDs3P, *Skin->GetMaterials(ECsViewType::ThirdPerson));
}
else
{
TArray<UMaterialInstanceConstant*> Materials;
Data_Weapon->GetDefaultMaterials(Materials, ECsViewType::ThirdPerson);
UCsLibrary_Common::SetMIDs(Mesh, MeshMIDs3P, Materials);
}
return;
}
// In Game
#endif // #if WITH_EDITOR
{
Data_Weapon->SetMesh(Mesh3P, ECsViewType::ThirdPerson, UseMesh3PLow);
Data_Weapon->SetAnimBlueprint(Mesh3P, ECsViewType::ThirdPerson, UseMesh3PLow);
if (UCsData_WeaponMaterialSkin* Skin = GetMyData_WeaponMaterialSkin())
{
Skin->SetMaterials(Mesh3P, ECsViewType::ThirdPerson);
UCsLibrary_Common::SetMIDs(Mesh3P, MeshMIDs3P, *Skin->GetMaterials(ECsViewType::ThirdPerson));
}
else
{
TArray<UMaterialInstanceConstant*> Materials;
Data_Weapon->GetDefaultMaterials(Materials, ECsViewType::ThirdPerson);
UCsLibrary_Common::SetMIDs(Mesh3P, MeshMIDs3P, Materials);
}
//Mesh3P->SetRelativeScale3D(WeaponData->Mesh3PScale);
Mesh3P->SetCastShadow(false);
}
}
USkeletalMeshComponent* ACsFpsWeapon::GetMesh(const ECsViewType& ViewType)
{
#if WITH_EDITOR
// In Editor Preview Window
if (UCsLibrary_Common::IsPlayInEditorPreview(GetWorld()))
{
// Character
if (UCsAnimInstance_Character* AnimInstance = GetMyOwner<UCsAnimInstance_Character>())
{
if (ViewType == ECsViewType::FirstPerson)
return Mesh1P;
if (ViewType == ECsViewType::ThirdPerson)
return Mesh3P;
}
// Weapon
if (UCsAnimInstance_Weapon* AnimInstance = GetMyOwner<UCsAnimInstance_Weapon>())
return AnimInstance->GetSkeletalMeshComponent();
}
#endif // #if WITH_EDITOR
if (IsValidOwnerTypeInGame())
{
if (ViewType == ECsViewType::FirstPerson)
return Mesh1P;
if (ViewType == ECsViewType::ThirdPerson)
return Mesh3P;
}
return nullptr;
}
USkeletalMeshComponent* ACsFpsWeapon::GetCurrentMesh()
{
return GetMesh(GetCurrentViewType());
}
#pragma endregion Mesh
// Firing
#pragma region
FVector ACsFpsWeapon::GetMuzzleLocation(const ECsViewType& ViewType, const FECsWeaponFireMode& FireMode)
{
return GetMyData_Weapon<UCsData_ProjectileWeapon_DEPRECATED>()->GetMuzzleLocation(GetMesh(ViewType), ViewType, FireMode, CurrentProjectilePerShotIndex.Get(FireMode));
}
float ACsFpsWeapon::GetMovingSpreadBonus(const FECsWeaponFireMode& FireMode) { return MovingSpreadBonus.Get(FireMode); }
float ACsFpsWeapon::GetJumpSpreadImpulse(const FECsWeaponFireMode& FireMode) { return JumpSpreadImpulse.Get(FireMode); }
float ACsFpsWeapon::GetScopeAccuracyBonus(const FECsWeaponFireMode& FireMode) { return ScopeAccuracyBonus.Get(FireMode); }
float ACsFpsWeapon::GetMaxScopePower(const FECsWeaponFireMode& FireMode) { return MaxScopePower.Get(FireMode); }
float ACsFpsWeapon::GetScopePowerGrowthRate(const FECsWeaponFireMode& FireMode) { return ScopePowerGrowthRate.Get(FireMode); }
void ACsFpsWeapon::FireProjectile_Internal(const FECsWeaponFireMode& FireMode, FCsProjectileFirePayload* Payload)
{
ACsPawn* MyOwnerAsPawn = GetMyPawn();
// Scope
if (DoScopePower.Get(FireMode))
{
LastScopePower.Set(FireMode, CurrentScopePower.Get(FireMode));
CurrentScopePower.Set(FireMode, 0.f);
ScopeActiveStartTime = GetWorld()->TimeSeconds;
}
// Kickback
if (DoKickback.Get(FireMode))
{
if (MyOwnerAsPawn->GetCharacterMovement()->IsFalling() || DoKickbackOnGround.Get(FireMode))
{
//KickbackPlayer(FireMode, -ShootDir);
}
}
}
#pragma endregion Firing | 33.268848 | 167 | 0.77792 | [
"mesh"
] |
5ceb53acd4b7702a3c7a120c3f0423ec8b994993 | 758 | cpp | C++ | codeforces/363/B.cpp | amitdu6ey/Online-Judge-Submissions | 9585aec29228211454bca5cf1d5738f49fb0aa8f | [
"MIT"
] | 5 | 2020-06-30T12:44:25.000Z | 2021-07-14T06:35:57.000Z | codeforces/363/B.cpp | amitdu6ey/Online-Judge-Submissions | 9585aec29228211454bca5cf1d5738f49fb0aa8f | [
"MIT"
] | null | null | null | codeforces/363/B.cpp | amitdu6ey/Online-Judge-Submissions | 9585aec29228211454bca5cf1d5738f49fb0aa8f | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#define ll long long
using namespace std;
void solve(){
ll n,k,sum=0,min=0,ans=1;
cin>>n>>k;
vector<ll> a(n);
for(vector<ll>::iterator it = a.begin();it != a.end();it++){
cin>>*it;
}
for(vector<ll>::iterator it = a.begin();it != a.begin()+k;it++){
sum += *it;
}
min=sum;
for(vector<ll>::iterator it = a.begin()+k;it != a.end();it++){
sum += a.at(it-a.begin());
sum -= a.at(it-a.begin()-k);
if(sum<min){
min=sum;
ans = it-a.begin()+1-k+1;
// cout<<ans<<"#"<<sum<<"\n";
}
}
cout<<ans;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
return 0;
} | 20.486486 | 68 | 0.472296 | [
"vector"
] |
5cec6b2ccaa52b7856c5fc4ac162bb599b7bb78a | 13,189 | cc | C++ | storage/browser/quota/usage_tracker_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | storage/browser/quota/usage_tracker_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | storage/browser/quota/usage_tracker_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/url_util.h"
#include "storage/browser/quota/usage_tracker.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gtest/include/gtest/gtest.h"
using blink::mojom::QuotaStatusCode;
using blink::mojom::StorageType;
namespace storage {
namespace {
void DidGetGlobalUsage(bool* done,
int64_t* usage_out,
int64_t* unlimited_usage_out,
int64_t usage,
int64_t unlimited_usage) {
EXPECT_FALSE(*done);
*done = true;
*usage_out = usage;
*unlimited_usage_out = unlimited_usage;
}
void DidGetUsage(bool* done, int64_t* usage_out, int64_t usage) {
EXPECT_FALSE(*done);
*done = true;
*usage_out = usage;
}
} // namespace
class MockQuotaClient : public QuotaClient {
public:
MockQuotaClient() = default;
ID id() const override { return kFileSystem; }
void OnQuotaManagerDestroyed() override {}
void GetOriginUsage(const url::Origin& origin,
StorageType type,
GetUsageCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
int64_t usage = GetUsage(origin);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), usage));
}
void GetOriginsForType(StorageType type,
GetOriginsCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
std::set<url::Origin> origins;
for (const auto& origin_usage_pair : origin_usage_map_)
origins.insert(origin_usage_pair.first);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), origins));
}
void GetOriginsForHost(StorageType type,
const std::string& host,
GetOriginsCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
std::set<url::Origin> origins;
for (const auto& origin_usage_pair : origin_usage_map_) {
if (net::GetHostOrSpecFromURL(origin_usage_pair.first.GetURL()) == host)
origins.insert(origin_usage_pair.first);
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), origins));
}
void DeleteOriginData(const url::Origin& origin,
StorageType type,
DeletionCallback callback) override {
EXPECT_EQ(StorageType::kTemporary, type);
origin_usage_map_.erase(origin);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), QuotaStatusCode::kOk));
}
void PerformStorageCleanup(blink::mojom::StorageType type,
base::OnceClosure callback) override {
std::move(callback).Run();
}
bool DoesSupport(StorageType type) const override {
return type == StorageType::kTemporary;
}
int64_t GetUsage(const url::Origin& origin) {
auto found = origin_usage_map_.find(origin);
if (found == origin_usage_map_.end())
return 0;
return found->second;
}
void SetUsage(const url::Origin& origin, int64_t usage) {
origin_usage_map_[origin] = usage;
}
int64_t UpdateUsage(const url::Origin& origin, int64_t delta) {
return origin_usage_map_[origin] += delta;
}
private:
~MockQuotaClient() override = default;
std::map<url::Origin, int64_t> origin_usage_map_;
DISALLOW_COPY_AND_ASSIGN(MockQuotaClient);
};
class UsageTrackerTest : public testing::Test {
public:
UsageTrackerTest()
: storage_policy_(new MockSpecialStoragePolicy()),
quota_client_(base::MakeRefCounted<MockQuotaClient>()),
usage_tracker_(GetUsageTrackerList(),
StorageType::kTemporary,
storage_policy_.get()) {}
~UsageTrackerTest() override = default;
UsageTracker* usage_tracker() {
return &usage_tracker_;
}
static void DidGetUsageBreakdown(
bool* done,
int64_t* usage_out,
blink::mojom::UsageBreakdownPtr* usage_breakdown_out,
int64_t usage,
blink::mojom::UsageBreakdownPtr usage_breakdown) {
EXPECT_FALSE(*done);
*usage_out = usage;
*usage_breakdown_out = std::move(usage_breakdown);
*done = true;
}
void UpdateUsage(const url::Origin& origin, int64_t delta) {
quota_client_->UpdateUsage(origin, delta);
usage_tracker_.UpdateUsageCache(quota_client_->id(), origin, delta);
base::RunLoop().RunUntilIdle();
}
void UpdateUsageWithoutNotification(const url::Origin& origin,
int64_t delta) {
quota_client_->UpdateUsage(origin, delta);
}
void GetGlobalLimitedUsage(int64_t* limited_usage) {
bool done = false;
usage_tracker_.GetGlobalLimitedUsage(
base::BindOnce(&DidGetUsage, &done, limited_usage));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(done);
}
void GetGlobalUsage(int64_t* usage, int64_t* unlimited_usage) {
bool done = false;
usage_tracker_.GetGlobalUsage(
base::BindOnce(&DidGetGlobalUsage, &done, usage, unlimited_usage));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(done);
}
void GetHostUsage(const std::string& host, int64_t* usage) {
bool done = false;
usage_tracker_.GetHostUsage(host,
base::BindOnce(&DidGetUsage, &done, usage));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(done);
}
std::pair<int64_t, blink::mojom::UsageBreakdownPtr> GetHostUsageBreakdown(
const std::string& host) {
int64_t usage;
blink::mojom::UsageBreakdownPtr usage_breakdown;
bool done = false;
usage_tracker_.GetHostUsageWithBreakdown(
host, base::BindOnce(&UsageTrackerTest::DidGetUsageBreakdown, &done,
&usage, &usage_breakdown));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(done);
return std::make_pair(usage, std::move(usage_breakdown));
}
void GrantUnlimitedStoragePolicy(const url::Origin& origin) {
if (!storage_policy_->IsStorageUnlimited(origin.GetURL())) {
storage_policy_->AddUnlimited(origin.GetURL());
storage_policy_->NotifyGranted(origin,
SpecialStoragePolicy::STORAGE_UNLIMITED);
}
}
void RevokeUnlimitedStoragePolicy(const url::Origin& origin) {
if (storage_policy_->IsStorageUnlimited(origin.GetURL())) {
storage_policy_->RemoveUnlimited(origin.GetURL());
storage_policy_->NotifyRevoked(origin,
SpecialStoragePolicy::STORAGE_UNLIMITED);
}
}
void SetUsageCacheEnabled(const url::Origin& origin, bool enabled) {
usage_tracker_.SetUsageCacheEnabled(quota_client_->id(), origin, enabled);
}
private:
std::vector<scoped_refptr<QuotaClient>> GetUsageTrackerList() {
std::vector<scoped_refptr<QuotaClient>> client_list;
client_list.push_back(quota_client_);
return client_list;
}
base::test::TaskEnvironment task_environment_;
scoped_refptr<MockSpecialStoragePolicy> storage_policy_;
scoped_refptr<MockQuotaClient> quota_client_;
UsageTracker usage_tracker_;
DISALLOW_COPY_AND_ASSIGN(UsageTrackerTest);
};
TEST_F(UsageTrackerTest, GrantAndRevokeUnlimitedStorage) {
int64_t usage = 0;
int64_t unlimited_usage = 0;
int64_t host_usage = 0;
blink::mojom::UsageBreakdownPtr host_usage_breakdown_expected =
blink::mojom::UsageBreakdown::New();
GetGlobalUsage(&usage, &unlimited_usage);
EXPECT_EQ(0, usage);
EXPECT_EQ(0, unlimited_usage);
// TODO(crbug.com/889590): Use helper for url::Origin creation from string.
const url::Origin origin = url::Origin::Create(GURL("http://example.com"));
const std::string host(net::GetHostOrSpecFromURL(origin.GetURL()));
UpdateUsage(origin, 100);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
EXPECT_EQ(100, host_usage);
host_usage_breakdown_expected->fileSystem = 100;
std::pair<int64_t, blink::mojom::UsageBreakdownPtr> host_usage_breakdown =
GetHostUsageBreakdown(host);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
GrantUnlimitedStoragePolicy(origin);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(100, unlimited_usage);
EXPECT_EQ(100, host_usage);
host_usage_breakdown = GetHostUsageBreakdown(host);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
RevokeUnlimitedStoragePolicy(origin);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
EXPECT_EQ(100, host_usage);
GetHostUsageBreakdown(host);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
}
TEST_F(UsageTrackerTest, CacheDisabledClientTest) {
int64_t usage = 0;
int64_t unlimited_usage = 0;
int64_t host_usage = 0;
blink::mojom::UsageBreakdownPtr host_usage_breakdown_expected =
blink::mojom::UsageBreakdown::New();
const url::Origin origin = url::Origin::Create(GURL("http://example.com"));
const std::string host(net::GetHostOrSpecFromURL(origin.GetURL()));
UpdateUsage(origin, 100);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
EXPECT_EQ(100, host_usage);
host_usage_breakdown_expected->fileSystem = 100;
std::pair<int64_t, blink::mojom::UsageBreakdownPtr> host_usage_breakdown =
GetHostUsageBreakdown(host);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
UpdateUsageWithoutNotification(origin, 100);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(100, usage);
EXPECT_EQ(0, unlimited_usage);
EXPECT_EQ(100, host_usage);
host_usage_breakdown = GetHostUsageBreakdown(host);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
GrantUnlimitedStoragePolicy(origin);
UpdateUsageWithoutNotification(origin, 100);
SetUsageCacheEnabled(origin, false);
UpdateUsageWithoutNotification(origin, 100);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(400, usage);
EXPECT_EQ(400, unlimited_usage);
EXPECT_EQ(400, host_usage);
host_usage_breakdown = GetHostUsageBreakdown(host);
host_usage_breakdown_expected->fileSystem = 400;
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
RevokeUnlimitedStoragePolicy(origin);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(400, usage);
EXPECT_EQ(0, unlimited_usage);
EXPECT_EQ(400, host_usage);
host_usage_breakdown = GetHostUsageBreakdown(host);
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
SetUsageCacheEnabled(origin, true);
UpdateUsage(origin, 100);
GetGlobalUsage(&usage, &unlimited_usage);
GetHostUsage(host, &host_usage);
EXPECT_EQ(500, usage);
EXPECT_EQ(0, unlimited_usage);
EXPECT_EQ(500, host_usage);
host_usage_breakdown = GetHostUsageBreakdown(host);
host_usage_breakdown_expected->fileSystem = 500;
EXPECT_EQ(host_usage_breakdown_expected, host_usage_breakdown.second);
}
TEST_F(UsageTrackerTest, LimitedGlobalUsageTest) {
const url::Origin kNormal = url::Origin::Create(GURL("http://normal"));
const url::Origin kUnlimited = url::Origin::Create(GURL("http://unlimited"));
const url::Origin kNonCached = url::Origin::Create(GURL("http://non_cached"));
const url::Origin kNonCachedUnlimited =
url::Origin::Create(GURL("http://non_cached-unlimited"));
GrantUnlimitedStoragePolicy(kUnlimited);
GrantUnlimitedStoragePolicy(kNonCachedUnlimited);
SetUsageCacheEnabled(kNonCached, false);
SetUsageCacheEnabled(kNonCachedUnlimited, false);
UpdateUsageWithoutNotification(kNormal, 1);
UpdateUsageWithoutNotification(kUnlimited, 2);
UpdateUsageWithoutNotification(kNonCached, 4);
UpdateUsageWithoutNotification(kNonCachedUnlimited, 8);
int64_t limited_usage = 0;
int64_t total_usage = 0;
int64_t unlimited_usage = 0;
GetGlobalLimitedUsage(&limited_usage);
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(1 + 4, limited_usage);
EXPECT_EQ(1 + 2 + 4 + 8, total_usage);
EXPECT_EQ(2 + 8, unlimited_usage);
UpdateUsageWithoutNotification(kNonCached, 16 - 4);
UpdateUsageWithoutNotification(kNonCachedUnlimited, 32 - 8);
GetGlobalLimitedUsage(&limited_usage);
GetGlobalUsage(&total_usage, &unlimited_usage);
EXPECT_EQ(1 + 16, limited_usage);
EXPECT_EQ(1 + 2 + 16 + 32, total_usage);
EXPECT_EQ(2 + 32, unlimited_usage);
}
} // namespace storage
| 33.559796 | 80 | 0.719312 | [
"vector"
] |
5cf2a987bcdfb263237a1f9abfa01b8c6a968a4a | 1,052 | cpp | C++ | grooking_patterns_cpp/dp_probs/min_diff_partition.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | 1 | 2021-09-19T16:41:58.000Z | 2021-09-19T16:41:58.000Z | grooking_patterns_cpp/dp_probs/min_diff_partition.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | grooking_patterns_cpp/dp_probs/min_diff_partition.cpp | Amarnathpg123/grokking_coding_patterns | c615482ef2819d90cba832944943a6b5713d11f3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
size_t min_diff_dp(vector<unsigned> &arr) {
size_t sum = accumulate(arr.begin(), arr.end(), 0);
vector<vector<bool>> dp(arr.size()+1, vector<bool> (sum+1, 0));
for(size_t i = 0; i <= arr.size(); ++i) dp[i][0] = 1;
for(size_t i = 1; i <= sum; ++i) dp[0][i] = 0;
for(size_t i = 1; i <= arr.size(); ++i) {
for(size_t j = 1; j <= sum; ++j){
dp[i][j] = dp[i-1][j];
if(arr[i-1] <= j)
dp[i][j] = (dp[i-1][j] | dp[i-1][j-arr[i-1]]);
}
}
size_t diff = 0;
for(long i = sum/2; i >= 0; --i) {
if(dp[arr.size()][i]) {
diff = sum-2*i;
break;
}
}
return diff;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
size_t n; cin >> n;
vector<unsigned> arr; unsigned temp;
while(n) {
cin >> temp; arr.push_back(temp);
n--;
}
printf("Minimum difference parition of set is: %lu\n", min_diff_dp(arr));
return 0;
} | 23.909091 | 77 | 0.475285 | [
"vector"
] |
9dd1287fd13282d503a7b425251478dea3e3c5d9 | 5,987 | hh | C++ | src/cxx/include/layout/Barcode.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | 5 | 2021-06-07T12:36:11.000Z | 2022-02-08T09:49:02.000Z | src/cxx/include/layout/Barcode.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | 1 | 2022-03-01T23:55:57.000Z | 2022-03-01T23:57:15.000Z | src/cxx/include/layout/Barcode.hh | sbooeshaghi/bcl2fastq | 3f39a24cd743fa71fba9b7dcf62e5d33cea8272d | [
"BSD-3-Clause"
] | null | null | null | /**
* BCL to FASTQ file converter
* Copyright (c) 2007-2017 Illumina, Inc.
*
* This software is covered by the accompanying EULA
* and certain third party copyright/licenses, and any user of this
* source file is bound by the terms therein.
*
* \file Barcode.hh
*
* \brief Declaration of barcode.
*
* \author Marek Balint
*/
#ifndef BCL2FASTQ_LAYOUT_BARCODE_HH
#define BCL2FASTQ_LAYOUT_BARCODE_HH
#include <vector>
#include <string>
#include <stdint.h>
#include "common/Types.hh"
namespace bcl2fastq {
namespace layout {
/// \brief Barcode type definition.
class Barcode
{
public:
/// \brief Barcode component type definition.
class Component
{
public:
/// \brief Size type definition.
/// \note Size of the integer type limits maximum number of component's bases (1 base per 3 bits).
typedef uint8_t SizeType;
public:
/// \brief Invalid base character.
static const char INVALID_BASE;
public:
/// \brief Constructor.
/// \param value Component value.
/// \pre <code>value.empty() == false</code>
/// \pre <code>value.size() <= 21</code>
explicit Component(const std::string &value);
Component() : value_() { }
public:
/// \brief Less-than comparison.
/// \param rhs Other instance to compare with.
/// \retval true Other instance is less than this instance.
/// \retval false Other instance is not less than this instance.
bool less(const Component &rhs) const { return value_ < rhs.value_; }
bool operator!=(const Component &rhs) const { return value_ != rhs.value_; }
public:
/// \brief Get barcode component length.
/// \return Number of bases in barcode component.
Barcode::Component::SizeType getLength() const { return value_.size(); }
/// \brief Get the barcode component length.
/// \return Number of bases in barcode component.
size_t size() const { return value_.size(); }
/// \brief Get the barcode string.
/// \return the string.
const std::string& getString() const { return value_; }
/// \brief Get the barcode string.
/// \return the string.
std::string& getString() { return value_; }
/// \brief Reset the memory, without deallocating.
void reset() { value_.clear(); }
public:
/// \brief Generate components with mismatches.
/// \param position Mismatching position.
/// \param componentInserter Insert iterator for mismatching barcode components.
/// \pre <code>position < this->getLength()</code>
template<typename Inserter>
void generateMismatches(
Component::SizeType position,
Inserter componentInserter
) const;
private:
/// \brief Value.
std::string value_;
};
/// \brief Barcodes container type definition.
typedef std::vector<Component> ComponentsContainer;
public:
/// \brief Barcode components separator.
static const char COMPONENT_SEPARATOR;
/// \brief Label to use when no Barcode is given.
static const char DEFAULT_BARCODE[];
public:
/// \brief Constructor.
/// \param componentsBegin Beginning of barcode components.
/// \param componentsEnd End of barcode components.
/// \pre Iterator @c componentsEnd is reachable from @c componentsBegin.
/// \pre <code>componentsBegin != componentsEnd</code>
template<typename Iterator>
Barcode(Iterator componentsBegin, Iterator componentsEnd);
Barcode() : components_() { }
void reset(size_t numComponents);
std::string toString() const;
public:
/// \brief Less-than comparison.
/// \param rhs Other instance to compare with.
/// \retval true Other instance is less than this instance.
/// \retval false Other instance is not less than this instance.
bool operator<(const Barcode &rhs) const;
bool operator==(const Barcode &rhs) const;
bool operator!=(const Barcode &rhs) const;
public:
/// \brief Get beginning of barcode components.
/// \return Iterator to beginning of barcode segmetns.
Barcode::ComponentsContainer::const_iterator componentsBegin() const { return components_.begin(); }
/// \brief Get end of barcode components.
/// \return Iterator to end of barcode components.
Barcode::ComponentsContainer::const_iterator componentsEnd() const { return components_.end(); }
/// \brief Get the barcode components
/// \return Barcode components
const ComponentsContainer& getComponents() const { return components_; }
public:
/// \brief Generate barcodes with mismatches.
/// \param component Mismatching component.
/// \param position Mismatching position of component.
/// \param barcodeInserter Insert iterator for mismatching barcodes.
/// \pre Iterator @c component must be reachable from <code>this->componentsBegin()</code>
/// \pre Iterator @c component must be dereferencable.
/// \pre <code>position < component->getLength()</code>
template<typename Inserter>
void generateMismatches(
ComponentsContainer::const_iterator component,
Component::SizeType position,
Inserter barcodeInserter
) const;
/// \brief Ouput the barcode to the buffer
/// \param buffer to output to
void output(std::vector<char>& buffer) const;
/// \brief Mask the barcode for the given index number
/// \param index number.
void mask(common::ReadNumber indexNumber);
//private:
friend std::ostream& operator<<(std::ostream& os, const Barcode& barcode);
/// \brief Barcode components.
ComponentsContainer components_;
};
/// \brief Barcodes container type definition.
typedef std::vector<Barcode> BarcodesContainer;
} // namespace layout
} // namespace bcl2fastq
#include "layout/Barcode.hpp"
#endif // BCL2FASTQ_LAYOUT_BARCODE_HH
| 28.509524 | 106 | 0.663772 | [
"vector"
] |
9dd187726df31df2d5c4c7af59883862413c1a56 | 268 | hpp | C++ | sha1-hmac.hpp | zolbooo/gtotp | 7635e177b47aab07c8e3748560d308103d3d9503 | [
"MIT"
] | null | null | null | sha1-hmac.hpp | zolbooo/gtotp | 7635e177b47aab07c8e3748560d308103d3d9503 | [
"MIT"
] | null | null | null | sha1-hmac.hpp | zolbooo/gtotp | 7635e177b47aab07c8e3748560d308103d3d9503 | [
"MIT"
] | null | null | null | #include <openssl/hmac.h>
#include <cstring>
#include <string>
#include <vector>
const int hmac_size = 20;
std::vector<uint8_t> sha1_hmac(std::string key, std::string message);
std::vector<uint8_t> sha1_hmac(std::vector<uint8_t> key, std::vector<uint8_t> message); | 26.8 | 87 | 0.738806 | [
"vector"
] |
9de61966cab0303e5a7067e766776c19f04cf1b7 | 656 | cpp | C++ | escenario.cpp | EnriqueJose99/P3Lab-6_EnriqueGaleanoTalavera_NUEVO | 3819f35527aeb0b53a4e5e5a597e1d37063409ac | [
"MIT"
] | null | null | null | escenario.cpp | EnriqueJose99/P3Lab-6_EnriqueGaleanoTalavera_NUEVO | 3819f35527aeb0b53a4e5e5a597e1d37063409ac | [
"MIT"
] | null | null | null | escenario.cpp | EnriqueJose99/P3Lab-6_EnriqueGaleanoTalavera_NUEVO | 3819f35527aeb0b53a4e5e5a597e1d37063409ac | [
"MIT"
] | null | null | null | #include "escenario.h"
#include "bombas.h"
#include <iostream>
#include <string>
using namespace std;
Escenario::Escenario(){
}
Escenario::Escenario(string pNombreEs){
nombreEs = pNombreEs;
}
void Escenario::setNombreEs(string pNombreEs){
nombreEs = pNombreEs;
}
string Escenario::getNombreEs(){
return nombreEs;
}
vector<Bombas*>Escenario::getBombas(){
return bombas;
}
Items*** Escenario::crearTablero(){
Items*** tablero = new Items**[11];
for (int i = 0; i < 11; i++) {
tablero[i] = new Items*[13];
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 13; j++) {
tablero[i][j] = NULL;
}
}
return tablero;
}
| 16.820513 | 46 | 0.625 | [
"vector"
] |
9de84b29e8b8b7b20a801f9f9495c1644d126be7 | 64,303 | cpp | C++ | shell/osshell/accessib/narrator/narrator/narrator.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | shell/osshell/accessib/narrator/narrator/narrator.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | shell/osshell/accessib/narrator/narrator/narrator.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*************************************************************************
Project: Narrator
Module: narrator.c
Author: Paul Blenkhorn
Date: April 1997
Notes: Contains main application initalization code
Credit to be given to MSAA team - bits of code have been
lifted from:
Babble, Inspect, and Snapshot.
Copyright (C) 1997-1999 by Microsoft Corporation. All rights reserved.
See bottom of file for disclaimer
History: Bug Fixes/ New features/ Additions: 1999 Anil Kumar
*************************************************************************/
#define STRICT
#include <windows.h>
#include <windowsx.h>
#include <oleacc.h>
#include <string.h>
#include <stdio.h>
#include <mmsystem.h>
#include <initguid.h>
#include <objbase.h>
#include <objerror.h>
#include <ole2ver.h>
#include <commctrl.h>
#include "Narrator.h"
#include "resource.h"
#include <htmlhelp.h>
#include "reader.h"
#include "..\NarrHook\keys.h"
#include "w95trace.c"
#include "DeskSwitch.c"
// Bring in Speech API declarations
// The SAPI5 define determines whether SAPI5 or SAPI4 is used. Comment out
// the next line to use SAPI4.
#define SAPI5
#ifndef SAPI5
#include "speech.h"
#else
#include "sapi.h"
#endif
#include <stdlib.h>
// UM
#include <TCHAR.h>
#include <string.h>
#include <WinSvc.h>
#include <stdio.h>
#define MAX_ENUMMODES 80
#define MAX_LANGUAGES 27
#define MAX_NAMELEN 30 // number of characters in the name excluding the path info
#define WM_DELAYEDMINIMIZE WM_USER + 102
#define ARRAYSIZE(n) (sizeof(n)/sizeof(n[0]))
#ifndef SAPI5
// TTS info
TTSMODEINFO gaTTSInfo[MAX_ENUMMODES];
PIAUDIOMULTIMEDIADEVICE pIAMM; // multimedia device interface for audio-dest
#endif
DEFINE_GUID(MSTTS_GUID,
0xC5C35D60, 0xDA44, 0x11D1, 0xB1, 0xF1, 0x0, 0x0, 0xF8, 0x03, 0xE4, 0x56);
// language test table, taken from WINNT.h...
LPTSTR Languages[MAX_LANGUAGES]={
TEXT("NEUTRAL"),TEXT("BULGARIAN"),TEXT("CHINESE"),TEXT("CROATIAN"),TEXT("CZECH"),
TEXT("DANISH"),TEXT("DUTCH"),TEXT("ENGLISH"),TEXT("FINNISH"),
TEXT("FRENCH"),TEXT("GERMAN"),TEXT("GREEK"),TEXT("HUNGARIAN"),TEXT("ICELANDIC"),
TEXT("ITALIAN"),TEXT("JAPANESE"),TEXT("KOREAN"),TEXT("NORWEGIAN"),
TEXT("POLISH"),TEXT("PORTUGUESE"),TEXT("ROMANIAN"),TEXT("RUSSIAN"),TEXT("SLOVAK"),
TEXT("SLOVENIAN"),TEXT("SPANISH"),TEXT("SWEDISH"),TEXT("TURKISH")};
WORD LanguageID[MAX_LANGUAGES]={
LANG_NEUTRAL,LANG_BULGARIAN,LANG_CHINESE,LANG_CROATIAN,LANG_CZECH,LANG_DANISH,LANG_DUTCH,
LANG_ENGLISH,LANG_FINNISH,LANG_FRENCH,LANG_GERMAN,LANG_GREEK,LANG_HUNGARIAN,LANG_ICELANDIC,
LANG_ITALIAN,LANG_JAPANESE,LANG_KOREAN,LANG_NORWEGIAN,LANG_POLISH,LANG_PORTUGUESE,
LANG_ROMANIAN,LANG_RUSSIAN,LANG_SLOVAK,LANG_SLOVENIAN,LANG_SPANISH,LANG_SWEDISH,LANG_TURKISH};
// Start Type
DWORD StartMin = FALSE;
// Show warning
DWORD ShowWarn = TRUE;
// the total number of enumerated modes
DWORD gnmodes=0;
// Local functions
#ifndef SAPI5
PITTSCENTRAL FindAndSelect(PTTSMODEINFO pTTSInfo);
#endif
BOOL InitTTS(void);
BOOL UnInitTTS(void);
// Dialog call back procs
INT_PTR CALLBACK MainDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
INT_PTR CALLBACK AboutDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
INT_PTR CALLBACK ConfirmProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
INT_PTR CALLBACK WarnDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
BOOL InitApp(HINSTANCE hInstance, int nCmdShow);
BOOL UnInitApp(void);
BOOL SpeakString(TCHAR * pszSpeakText, BOOL forceRead, DWORD dwFlags);
void Shutup(void);
int MessageBoxLoadStrings (HWND hWnd,UINT uIDText,UINT uIDCaption,UINT uType);
void SetRegistryValues();
BOOL SetVolume (int nVolume);
BOOL SetSpeed (int nSpeed);
BOOL SetPitch (int nPitch);
DWORD GetDesktop();
void CenterWindow(HWND);
void FilterSpeech(TCHAR* szSpeak);
// Global varibles
TCHAR g_szLastStringSpoken[MAX_TEXT] = { NULL };
HWND g_hwndMain = NULL;
HINSTANCE g_hInst;
BOOL g_fAppExiting = FALSE;
int currentVoice = -1;
#ifndef SAPI5
PITTSCENTRAL g_pITTSCentral;
PITTSENUM g_pITTSEnum = NULL;
PITTSATTRIBUTES g_pITTSAttributes = NULL;
#else
ISpObjectToken *g_pVoiceTokens[80];
WCHAR g_szCurrentVoice[256];
WCHAR *g_szVoices[80];
ISpVoice *g_pISpV = NULL;
#define SPEAK_NORMAL SPF_ASYNC | SPF_IS_NOT_XML
#define SPEAK_XML SPF_ASYNC | SPF_PERSIST_XML
#define SPEAK_MUTE SPF_PURGEBEFORESPEAK
//
// Simple inline function converts a ulong to a hex string.
//
inline void SpHexFromUlong(WCHAR * psz, ULONG ul)
{
const static WCHAR szHexChars[] = L"0123456789ABCDEF";
if (ul == 0)
{
psz[0] = L'0';
psz[1] = 0;
}
else
{
ULONG ulChars = 1;
psz[0] = 0;
while (ul)
{
memmove(psz + 1, psz, ulChars * sizeof(WCHAR));
psz[0] = szHexChars[ul % 16];
ul /= 16;
ulChars++;
}
}
}
inline HRESULT SpEnumTokens(
const WCHAR * pszCategoryId,
const WCHAR * pszReqAttribs,
const WCHAR * pszOptAttribs,
IEnumSpObjectTokens ** ppEnum)
{
HRESULT hr = S_OK;
const BOOL fCreateIfNotExist = FALSE;
ISpObjectTokenCategory *cpCategory;
hr = CoCreateInstance(CLSID_SpObjectTokenCategory, NULL, CLSCTX_ALL,
__uuidof(ISpObjectTokenCategory),
reinterpret_cast<void **>(&cpCategory) );
if (SUCCEEDED(hr))
hr = cpCategory->SetId(pszCategoryId, fCreateIfNotExist);
if (SUCCEEDED(hr))
hr = cpCategory->EnumTokens( pszReqAttribs, pszOptAttribs, ppEnum);
cpCategory->Release();
return hr;
}
#endif
DWORD minSpeed, maxSpeed, lastSpeed = -1, currentSpeed = 5;
WORD minPitch, maxPitch, lastPitch = -1, currentPitch = 5;
DWORD minVolume, maxVolume, lastVolume = -1, currentVolume = 5;
#define SET_VALUE(fn, newVal, lastVal) \
{ \
if (lastVal != newVal) {\
fn(newVal); \
lastVal = newVal; \
} \
}
inline void SetDialogIcon(HWND hwnd)
{
HANDLE hIcon = LoadImage( g_hInst, MAKEINTRESOURCE(IDI_ICON1),
IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
if(hIcon)
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
}
// Combo box support
int GetComboItemData(HWND hwnd);
void FillAndSetCombo(HWND hwnd, int iMinVal, int iMaxVal, int iSelVal);
BOOL g_startUM = FALSE; // Started from Utililty Manager
HANDLE g_hMutexNarratorRunning;
BOOL logonCheck = FALSE;
// UM stuff
static BOOL AssignDesktop(LPDWORD desktopID, LPTSTR pname);
static BOOL InitMyProcessDesktopAccess(VOID);
static VOID ExitMyProcessDesktopAccess(VOID);
static HWINSTA origWinStation = NULL;
static HWINSTA userWinStation = NULL;
// Keep a global desktop ID
DWORD desktopID;
// For Link Window
EXTERN_C BOOL WINAPI LinkWindow_RegisterClass() ;
// For Utility Manager
#define UTILMAN_DESKTOP_CHANGED_MESSAGE __TEXT("UtilityManagerDesktopChanged")
#define DESKTOP_ACCESSDENIED 0
#define DESKTOP_DEFAULT 1
#define DESKTOP_SCREENSAVER 2
#define DESKTOP_WINLOGON 3
#define DESKTOP_TESTDISPLAY 4
#define DESKTOP_OTHER 5
//CS help
DWORD g_rgHelpIds[] = { IDC_VOICESETTINGS, 70600,
IDC_VOICE, 70605,
IDC_NAME, 70605,
IDC_COMBOSPEED, 70610,
IDC_COMBOVOLUME, 70615,
IDC_COMBOPITCH, 70620,
IDC_MODIFIERS, 70645,
IDC_ANNOUNCE, 70710,
IDC_READING, 70625,
IDC_MOUSEPTR, 70695,
IDC_MSRCONFIG, 70600,
IDC_STARTMIN, 70705,
IDC_EXIT, -1,
IDC_MSRHELP, -1,
IDC_CAPTION, -1
};
// IsSystem - Returns TRUE if our process is running as SYSTEM
//
BOOL IsSystem()
{
BOOL fStatus = FALSE;
BOOL fIsLocalSystem = FALSE;
SID_IDENTIFIER_AUTHORITY siaLocalSystem = SECURITY_NT_AUTHORITY;
PSID psidSystem;
if (!AllocateAndInitializeSid(&siaLocalSystem,
1,
SECURITY_LOCAL_SYSTEM_RID,
0, 0, 0, 0, 0, 0, 0,
&psidSystem))
{
return FALSE;
}
if (psidSystem)
{
fStatus = CheckTokenMembership(NULL, psidSystem, &fIsLocalSystem);
}
return (fStatus && fIsLocalSystem);
}
BOOL IsInteractiveUser()
{
BOOL fStatus = FALSE;
BOOL fIsInteractiveUser = FALSE;
PSID psidInteractiveUser = 0;
SID_IDENTIFIER_AUTHORITY siaLocalSystem = SECURITY_NT_AUTHORITY;
if (!AllocateAndInitializeSid(&siaLocalSystem,
1,
SECURITY_INTERACTIVE_RID,
0, 0, 0, 0, 0, 0, 0,
&psidInteractiveUser))
{
psidInteractiveUser = 0;
}
if (psidInteractiveUser)
{
fStatus = CheckTokenMembership(NULL, psidInteractiveUser, &fIsInteractiveUser);
}
return (fStatus && fIsInteractiveUser);
}
/*************************************************************************
Function: WinMain
Purpose: Entry point of application
Inputs:
Returns: Int containing the return value of the app.
History:
*************************************************************************/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
UINT deskSwitchMsg;
// Get the commandline so that it works for MUI/Unicode
LPTSTR lpCmdLineW = GetCommandLine();
if(NULL != lpCmdLineW && lstrlen(lpCmdLineW))
{
LPTSTR psz = wcschr(lpCmdLineW,_TEXT('/'));
if (psz && lstrcmpi(psz, TEXT("/UM")) == 0)
{
g_startUM = TRUE;
}
}
// Don't allow multiple versions of Narrator running at a time. If
// this instance was started by UtilMan then the code tries up to 4
// times to detect the absence of the narrator mutex; during a
// desktop switch we need to wait for the old narrator to quit.
int cTries;
for (cTries=0;cTries < 4;cTries++)
{
g_hMutexNarratorRunning = CreateMutex(NULL, TRUE, TEXT("AK:NarratorRunning"));
if (g_hMutexNarratorRunning && GetLastError() == ERROR_SUCCESS)
break; // mutex created and it didn't already exist
// cleanup before possible retry
if (g_hMutexNarratorRunning)
{
CloseHandle(g_hMutexNarratorRunning);
g_hMutexNarratorRunning = 0;
}
if (!g_startUM)
break; // not started by UtilMan but there's another narrator running
// pause...
Sleep(500);
}
if (!g_hMutexNarratorRunning || cTries >= 4)
return 0; // fail to start narrator
InitCommonControls();
// for the Link Window in finish page...
LinkWindow_RegisterClass();
// Initialization
g_hInst = hInstance;
TCHAR name[300];
// For Multiple desktops (UM)
deskSwitchMsg = RegisterWindowMessage(UTILMAN_DESKTOP_CHANGED_MESSAGE);
InitMyProcessDesktopAccess();
AssignDesktop(&desktopID,name);
// the only place it is ok to run as system is on the DESKTOP_WINLOGON desktop. If that is
// not where we are than get out before we cause any security problems. The check for interactive
// user is ther to make sure we run during setup or oobe becuase the security threat only exists
// when a user can exploit it
if (DESKTOP_WINLOGON != desktopID && IsSystem() && IsInteractiveUser() )
{
if ( g_hMutexNarratorRunning )
ReleaseMutex(g_hMutexNarratorRunning);
ExitMyProcessDesktopAccess();
return 0;
}
SpewOpenFile(TEXT("NarratorSpew.txt"));
if (InitApp(hInstance, nCmdShow))
{
MSG msg;
// Main message loop
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsDialogMessage(g_hwndMain, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == deskSwitchMsg)
{
g_fAppExiting = TRUE;
UnInitApp();
}
}
}
}
SpewCloseFile();
// UM
ExitMyProcessDesktopAccess();
return 0;
}
/*************************************************************************
Function:
Purpose:
Inputs:
Returns:
History:
*************************************************************************/
LPTSTR LangIDtoString( WORD LangID )
{
int i;
for( i=0; i<MAX_LANGUAGES; i++ )
{
if( (LangID & 0xFF) == LanguageID[i] )
return Languages[i];
}
return NULL;
}
#ifndef SAPI5
/*************************************************************************
Function:
Purpose: Get the range for speed, pitch etc..,
Inputs:
Returns:
History:
*************************************************************************/
void GetSpeechMinMaxValues(void)
{
WORD tmpPitch;
DWORD tmpSpeed;
DWORD tmpVolume;
g_pITTSAttributes->PitchGet(&tmpPitch);
g_pITTSAttributes->PitchSet(TTSATTR_MAXPITCH);
g_pITTSAttributes->PitchGet(&maxPitch);
g_pITTSAttributes->PitchSet(TTSATTR_MINPITCH);
g_pITTSAttributes->PitchGet(&minPitch);
g_pITTSAttributes->PitchSet(tmpPitch);
g_pITTSAttributes->SpeedGet(&tmpSpeed);
g_pITTSAttributes->SpeedSet(TTSATTR_MINSPEED);
g_pITTSAttributes->SpeedGet(&minSpeed);
g_pITTSAttributes->SpeedSet(TTSATTR_MAXSPEED);
g_pITTSAttributes->SpeedGet(&maxSpeed);
g_pITTSAttributes->SpeedSet(tmpSpeed);
g_pITTSAttributes->VolumeGet(&tmpVolume);
g_pITTSAttributes->VolumeSet(TTSATTR_MINVOLUME);
g_pITTSAttributes->VolumeGet(&minVolume);
g_pITTSAttributes->VolumeSet(TTSATTR_MAXVOLUME);
g_pITTSAttributes->VolumeGet(&maxVolume);
g_pITTSAttributes->VolumeSet(tmpVolume);
}
#endif
/*************************************************************************
Function: VoiceDlgProc
Purpose: Handles messages for the Voice Box dialog
Inputs:
Returns:
History:
*************************************************************************/
INT_PTR CALLBACK VoiceDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static WORD oldVoice, oldPitch;
static DWORD oldSpeed, oldVolume;
static HWND hwndList;
WORD wNewPitch;
DWORD i;
int Selection;
TCHAR szTxt[MAX_TEXT];
HRESULT hRes;
szTxt[0]=TEXT('\0');
switch (uMsg)
{
case WM_INITDIALOG:
oldVoice = currentVoice; // save voice parameters in case of CANCEL
oldPitch = currentPitch;
oldVolume = currentVolume;
oldSpeed = currentSpeed;
Shutup();
hwndList = GetDlgItem(hwnd, IDC_NAME);
SetDialogIcon(hwnd);
// Only allow picking a voice when not on secure desktop
if ( !logonCheck )
{
#ifndef SAPI5
for (i = 0; i < gnmodes; i++)
{
lstrcpyn(szTxt,gaTTSInfo[i].szModeName,MAX_TEXT);
lstrcatn(szTxt,TEXT(", "),MAX_TEXT);
lstrcatn(szTxt,
LangIDtoString(gaTTSInfo[i].language.LanguageID),
MAX_TEXT);
lstrcatn(szTxt,TEXT(", "),MAX_TEXT);
lstrcatn(szTxt,gaTTSInfo[i].szMfgName,MAX_TEXT);
SendMessage(hwndList, LB_ADDSTRING, 0, (LPARAM) szTxt);
}
#else
// Show the description for the voice narrator is using
for ( int i = 0; i < ARRAYSIZE( g_szVoices ) && g_szVoices[i] != NULL; i++ )
{
SendMessage(hwndList, LB_ADDSTRING, 0, (LPARAM) g_szVoices[i] );
}
hRes = g_pISpV->SetVoice( g_pVoiceTokens[currentVoice] );
if ( FAILED(hRes) )
DBPRINTF (TEXT("SetVoice failed hr=0x%lX\r\n"),hRes);
#endif
SendMessage(hwndList, LB_SETCURSEL, currentVoice, 0L);
}
else
{
LoadString(g_hInst, IDS_SAM, szTxt, MAX_TEXT);
SendMessage(hwndList, LB_ADDSTRING, 0, (LPARAM) szTxt);
EnableWindow(hwndList, FALSE);
}
FillAndSetCombo(GetDlgItem(hwnd, IDC_COMBOSPEED), 1, 9, currentSpeed);
FillAndSetCombo(GetDlgItem(hwnd, IDC_COMBOVOLUME), 1, 9, currentVolume);
FillAndSetCombo(GetDlgItem(hwnd, IDC_COMBOPITCH), 1, 9, currentPitch);
break;
case WM_COMMAND:
{
DWORD dwValue;
int control = LOWORD(wParam);
switch (LOWORD(wParam))
{
case IDC_NAME:
hwndList = GetDlgItem(hwnd,IDC_NAME);
Selection = (WORD) SendMessage(hwndList, LB_GETCURSEL,0, 0L);
if (Selection < 0 || Selection > 79)
Selection = 0;
Shutup();
#ifndef SAPI5
if (currentVoice != Selection)
{ // voice changed!
MessageBeep(MB_OK);
currentVoice = (WORD)Selection;
// Get the audio dest
g_pITTSCentral->Release();
if ( pIAMM )
{
pIAMM->Release();
pIAMM = NULL;
}
hRes = CoCreateInstance(CLSID_MMAudioDest,
NULL,
CLSCTX_ALL,
IID_IAudioMultiMediaDevice,
(void**)&pIAMM);
if (FAILED(hRes))
return TRUE; // error
hRes = g_pITTSEnum->Select( gaTTSInfo[Selection].gModeID,
&g_pITTSCentral,
(LPUNKNOWN) pIAMM);
if (FAILED(hRes))
MessageBeep(MB_OK);
g_pITTSAttributes->Release();
hRes = g_pITTSCentral->QueryInterface (IID_ITTSAttributes, (void**)&g_pITTSAttributes);
}
GetSpeechMinMaxValues(); // get speech parameters for this voice
#else
if ( currentVoice != Selection )
{
currentVoice = Selection;
hRes = g_pISpV->SetVoice( g_pVoiceTokens[currentVoice] );
if ( FAILED(hRes) )
{
DBPRINTF (TEXT("SetVoice failed hr=0x%lX\r\n"),hRes);
}
SendMessage(hwndList, LB_SETCURSEL, currentVoice, 0L);
}
#endif
// then reset pitch etc. accordingly
currentPitch = GetComboItemData(GetDlgItem(hwnd, IDC_COMBOPITCH));
currentSpeed = GetComboItemData(GetDlgItem(hwnd, IDC_COMBOSPEED));
currentVolume = GetComboItemData(GetDlgItem(hwnd, IDC_COMBOVOLUME));
SET_VALUE(SetPitch, currentPitch, lastPitch)
SET_VALUE(SetSpeed, currentSpeed, lastSpeed)
SET_VALUE(SetVolume, currentVolume, lastVolume)
break;
case IDC_COMBOSPEED:
if (IsWindowVisible(GetDlgItem(hwnd, control)))
{
dwValue = GetComboItemData(GetDlgItem(hwnd, control));
SET_VALUE(SetSpeed, dwValue, lastSpeed)
}
break;
case IDC_COMBOVOLUME:
if (IsWindowVisible(GetDlgItem(hwnd, control)))
{
dwValue = GetComboItemData(GetDlgItem(hwnd, control));
SET_VALUE(SetVolume, dwValue, lastVolume)
}
break;
case IDC_COMBOPITCH:
if (IsWindowVisible(GetDlgItem(hwnd, control)))
{
dwValue = GetComboItemData(GetDlgItem(hwnd, control));
SET_VALUE(SetPitch, dwValue, lastPitch)
}
break;
case IDCANCEL:
MessageBeep(MB_OK);
Shutup();
#ifndef SAPI5
if (currentVoice != oldVoice)
{ // voice changed!
currentVoice = oldVoice;
// Get the audio dest
g_pITTSCentral->Release();
if ( pIAMM )
{
pIAMM->Release();
pIAMM = NULL;
}
hRes = CoCreateInstance(CLSID_MMAudioDest,
NULL,
CLSCTX_ALL,
IID_IAudioMultiMediaDevice,
(void**)&pIAMM);
if (FAILED(hRes))
return TRUE; // error
hRes = g_pITTSEnum->Select( gaTTSInfo[currentVoice].gModeID,
&g_pITTSCentral,
(LPUNKNOWN) pIAMM);
if (FAILED(hRes))
MessageBeep(MB_OK);
g_pITTSAttributes->Release();
hRes = g_pITTSCentral->QueryInterface (IID_ITTSAttributes, (void**)&g_pITTSAttributes);
}
GetSpeechMinMaxValues(); // speech get parameters for old voice
#endif
currentPitch = oldPitch; // restore old values
SET_VALUE(SetPitch, currentPitch, lastPitch)
currentSpeed = oldSpeed;
SET_VALUE(SetSpeed, currentSpeed, lastSpeed)
currentVolume = oldVolume;
SET_VALUE(SetVolume, currentVolume, lastVolume)
EndDialog (hwnd, IDCANCEL);
return(TRUE);
case IDOK: // set values of pitch etc. from check boxes
currentPitch = GetComboItemData(GetDlgItem(hwnd, IDC_COMBOPITCH));
currentSpeed = GetComboItemData(GetDlgItem(hwnd, IDC_COMBOSPEED));
currentVolume = GetComboItemData(GetDlgItem(hwnd, IDC_COMBOVOLUME));
SET_VALUE(SetPitch, currentPitch, lastPitch)
SET_VALUE(SetSpeed, currentSpeed, lastSpeed)
SET_VALUE(SetVolume, currentVolume, lastVolume)
SetRegistryValues();
EndDialog (hwnd, IDOK);
return(TRUE);
} // end switch on control of WM_COMMAND
}
break;
case WM_CONTEXTMENU: // right mouse click
if ( !RunSecure(GetDesktop()) )
{
WinHelp((HWND) wParam, __TEXT("reader.hlp"), HELP_CONTEXTMENU, (DWORD_PTR) (LPSTR) g_rgHelpIds);
}
break;
case WM_CLOSE:
EndDialog (hwnd, IDOK);
return TRUE;
break;
case WM_HELP:
if ( !RunSecure(GetDesktop()) )
{
WinHelp((HWND) ((LPHELPINFO) lParam)->hItemHandle, __TEXT("reader.hlp"), HELP_WM_HELP, (DWORD_PTR) (LPSTR) g_rgHelpIds);
}
return(TRUE);
} // end switch uMsg
return(FALSE); // didn't handle
}
/*************************************************************************
Function: SetVolume
Purpose: set volume to a normalized value 1-9
Inputs: int volume in range 1-9
Returns:
History: At the application layer, volume is a number from 0 to 100
where 100 is the maximum value for a voice. It is a linear
progression so that a value 50 represents half of the loudest
permitted. The increments should be the range divided by 100.
*************************************************************************/
BOOL SetVolume (int nVolume)
{
#ifndef SAPI5
DWORD dwNewVolume;
WORD wNewVolumeLeft,
wNewVolumeRight;
//ASSERT (nVolume >= 1 && nVolume <= 9);
wNewVolumeLeft = (WORD)( (LOWORD(minVolume) + (((LOWORD(maxVolume) - LOWORD(minVolume))/9.0)*nVolume)) );
wNewVolumeRight = (WORD)( (HIWORD(minVolume) + (((HIWORD(maxVolume) - HIWORD(minVolume))/9.0)*nVolume)) );
dwNewVolume = MAKELONG (wNewVolumeLeft,wNewVolumeRight);
return (SUCCEEDED(g_pITTSAttributes->VolumeSet(dwNewVolume)));
#else
USHORT usNewVolume;
HRESULT hr;
if(nVolume < 1) nVolume = 1;
if(nVolume > 9) nVolume = 9;
//calculate a value between 10 and 90
usNewVolume = (USHORT)( nVolume * 10 );
hr = g_pISpV->SetVolume(usNewVolume);
return SUCCEEDED(hr);
#endif
}
/*************************************************************************
Function: SetSpeed
Purpose: set Speed to a normalized value 1-9
Inputs: int Speed in range 1-9
Returns:
History: The value can range from -10 to +10.
A value of 0 sets a voice to speak at its default rate.
A value of -10 sets a voice to speak at one-sixth of its default rate.
A value of +10 sets a voice to speak at 6 times its default rate.
Each increment between -10 and +10 is logarithmically distributed such
that incrementing or decrementing by 1 is multiplying or dividing the
rate by the 10th root of 6 (about 1.2). Values more extreme than -10 and +10
will be passed to an engine. However, SAPI 5.0-compliant engines may not
support such extremes and may clip the rate to the maximum or minimum
rate it supports.
*************************************************************************/
BOOL SetSpeed (int nSpeed)
{
#ifndef SAPI5
DWORD dwNewSpeed;
//ASSERT (nSpeed >= 1 && nSpeed <= 9);
dwNewSpeed = minSpeed + (DWORD) ((maxSpeed-minSpeed)/9.0*nSpeed);
return (SUCCEEDED(g_pITTSAttributes->SpeedSet(dwNewSpeed)));
#else
long lNewSpeed;
HRESULT hr;
if(nSpeed < 1) nSpeed = 1;
if(nSpeed > 9) nSpeed = 9;
switch(nSpeed)
{
case 1: lNewSpeed = -8; break;
case 2: lNewSpeed = -6; break;
case 3: lNewSpeed = -4; break;
case 4: lNewSpeed = -2; break;
case 5: lNewSpeed = 0; break;
case 6: lNewSpeed = 2; break;
case 7: lNewSpeed = 4; break;
case 8: lNewSpeed = 6; break;
case 9: lNewSpeed = 8; break;
default: lNewSpeed = 0; break;
}
hr = g_pISpV->SetRate(lNewSpeed);
return SUCCEEDED(hr);
#endif
}
/*************************************************************************
Function: SetPitch
Purpose: set Pitch to a normalized value 1-9
Inputs: int Pitch in range 1-9
Returns:
History: The value can range from -10 to +10. A value of 0 sets a voice to speak at
its default pitch. A value of -10 sets a voice to speak at three-fourths of
its default pitch. A value of +10 sets a voice to speak at four-thirds of
its default pitch. Each increment between -10 and +10 is logarithmically
distributed such that incrementing or decrementing by 1 is multiplying or
dividing the pitch by the 24th root of 2 (about 1.03). Values outside of
the -10 and +10 range will be passed to an engine. However, SAPI 5.0-compliant
engines may not support such extremes and may clip the pitch to the maximum or
minimum it supports. Values of -24 and +24 must lower and raise pitch by 1 octave
respectively. All incrementing or decrementing by 1 must multiply or divide the
pitch by the 24th root of 2.
Pitch changes can only be submitted via ::Speak using XML embedded in a string.
*************************************************************************/
BOOL SetPitch (int nPitch)
{
#ifndef SAPI5
WORD wNewPitch;
wNewPitch = (WORD)((minPitch + (((maxPitch - minPitch)/9.0)*nPitch)));
return (SUCCEEDED(g_pITTSAttributes->PitchSet(wNewPitch)));
#else
if(nPitch < 1) nPitch = 1;
if(nPitch > 9) nPitch = 9;
int nNewPitch;
switch(nPitch)
{
case 1: nNewPitch = -8; break;
case 2: nNewPitch = -6; break;
case 3: nNewPitch = -4; break;
case 4: nNewPitch = -2; break;
case 5: nNewPitch = 0; break;
case 6: nNewPitch = 2; break;
case 7: nNewPitch = 4; break;
case 8: nNewPitch = 6; break;
case 9: nNewPitch = 8; break;
default: nNewPitch = 0; break;
}
LPTSTR pszSpeak = new TCHAR[60];
if (pszSpeak)
{
wsprintf(pszSpeak,L"<PITCH ABSMIDDLE=\"%d\"/>",nNewPitch);
SpeakString(pszSpeak, TRUE, SPEAK_XML);
delete [] pszSpeak;
}
return TRUE;
#endif
}
#define TIMERID 6466
/*************************************************************************
Function: MainDlgProc
Purpose: Handles messages for the Main dialog
Inputs:
Returns:
History:
*************************************************************************/
INT_PTR CALLBACK MainDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
TCHAR szText[MAX_TEXT];
switch (uMsg)
{
case WM_INITDIALOG:
{
SetDialogIcon(hwnd);
// Disable Help button on other desktops
BOOL fRunSecure = RunSecure(GetDesktop());
if ( fRunSecure )
{
EnableWindow(GetDlgItem(hwnd, IDC_MSRHELP), FALSE);
}
CheckDlgButton(hwnd,IDC_MOUSEPTR,GetTrackInputFocus());
CheckDlgButton(hwnd,IDC_READING,GetEchoChars());
CheckDlgButton(hwnd,IDC_ANNOUNCE,GetAnnounceWindow());
CheckDlgButton(hwnd,IDC_STARTMIN,StartMin);
// To show the warning message on default desktop...
if (ShowWarn && !fRunSecure)
SetTimer(hwnd, TIMERID, 20, NULL);
// Enable desktop switching detection
InitWatchDeskSwitch(hwnd, WM_MSRDESKSW);
}
break;
case WM_TIMER:
KillTimer(hwnd, (UINT)wParam);
DialogBox (g_hInst, MAKEINTRESOURCE(IDD_WARNING),hwnd, WarnDlgProc);
return TRUE;
break;
case WM_WININICHANGE:
if (g_fAppExiting) break;
// If someone else turns off the system-wide screen reader
// flag, we want to turn it back on.
if (wParam == SPI_SETSCREENREADER && !lParam)
SystemParametersInfo(SPI_SETSCREENREADER, TRUE, NULL, SPIF_UPDATEINIFILE|SPIF_SENDCHANGE);
return 0;
case WM_DELAYEDMINIMIZE:
// Delayed mimimize message
ShowWindow(hwnd, SW_HIDE);
ShowWindow(hwnd, SW_MINIMIZE);
break;
case WM_MUTE:
Shutup();
break;
case WM_MSRSPEAK:
GetCurrentText(szText, MAX_TEXT);
SpeakString(szText, TRUE, SPEAK_NORMAL);
break;
case WM_MSRSPEAKXML:
GetCurrentText(szText, MAX_TEXT);
SpeakString(szText, TRUE, SPEAK_XML);
break;
case WM_MSRSPEAKMUTE:
SpeakString(NULL, TRUE, SPEAK_MUTE);
break;
case WM_CLOSE:
case WM_MSRDESKSW:
// When the desktop changes, if UtilMan is running and FUS isn't
// enabled then exit (when FUS is enabled we don't have to worry
// about running on another desktop therefore we don't need to
// exit). UtilMan will start us up again if necessary.
Shutup();
g_startUM = IsUtilManRunning();
// Jan23,2001 Optimization to FUS piggybacks the winlogon desktop
// to the session being switch from. This means we have to quit
// in case user needs to run from the winlogon desktop.
if (uMsg == WM_MSRDESKSW && (!g_startUM /*|| !CanLockDesktopWithoutDisconnect()*/))
break; // ignore message
// UtilMan is managing starting us. UtilMan will
// start us up again if necessary so quit...
case WM_MSRQUIT:
// Do not show an exit confirmation if started from UM and not at logon desktop
if ( !g_startUM && !RunSecure(GetDesktop()) )
{
if (IDOK != DialogBox(g_hInst, MAKEINTRESOURCE(IDD_CONFIRMEXIT), g_hwndMain, ConfirmProc))
return(FALSE);
}
// Intentional fall through
case WM_DESTROY:
// Required for desktop switches :a-anilk
g_fAppExiting = TRUE;
g_hwndMain = NULL;
TermWatchDeskSwitch(); // Terminate the desktop switch thread
UnInitApp();
if ( g_hMutexNarratorRunning )
ReleaseMutex(g_hMutexNarratorRunning);
// Let others know that you are turning off the system-wide
// screen reader flag.
SystemParametersInfo(SPI_SETSCREENREADER, FALSE, NULL, SPIF_UPDATEINIFILE|SPIF_SENDCHANGE);
EndDialog (hwnd, IDCANCEL);
PostQuitMessage(0);
return(TRUE);
case WM_MSRHELP:
// Show HTML help
if ( !RunSecure(GetDesktop()) )
{
HtmlHelp(hwnd ,TEXT("reader.chm"),HH_DISPLAY_TOPIC, 0);
}
break;
case WM_MSRCONFIGURE:
DialogBox (g_hInst, MAKEINTRESOURCE(IDD_VOICE),hwnd, VoiceDlgProc);
break;
case WM_HELP:
if ( !RunSecure(GetDesktop()) )
{
HtmlHelp(hwnd ,TEXT("reader.chm"),HH_DISPLAY_TOPIC, 0);
}
break;
case WM_CONTEXTMENU: // right mouse click
if ( !RunSecure(GetDesktop()) )
{
WinHelp((HWND) wParam, __TEXT("reader.hlp"), HELP_CONTEXTMENU, (DWORD_PTR) (LPSTR) g_rgHelpIds);
}
break;
case WM_SYSCOMMAND:
if ((wParam & 0xFFF0) == IDM_ABOUTBOX)
{
DialogBox (g_hInst, MAKEINTRESOURCE(IDD_ABOUTBOX),hwnd,AboutDlgProc);
return TRUE;
}
break;
// case WM_QUERYENDSESSION:
// return TRUE;
case WM_ENDSESSION:
{
HKEY hKey;
DWORD dwPosition;
const TCHAR szSubKey[] = __TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce");
const TCHAR szImageName[] = __TEXT("Narrator.exe");
const TCHAR szValueName[] = __TEXT("RunNarrator");
if ( ERROR_SUCCESS == RegCreateKeyEx(HKEY_CURRENT_USER, szSubKey, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_QUERY_VALUE | KEY_SET_VALUE, NULL, &hKey, &dwPosition))
{
RegSetValueEx(hKey, (LPCTSTR) szValueName, 0, REG_SZ, (CONST BYTE*)szImageName, (lstrlen(szImageName)+1)*sizeof(TCHAR) );
RegCloseKey(hKey);
}
}
return 0;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_MSRHELP :
PostMessage(hwnd, WM_MSRHELP,0,0);
break;
case IDC_MINIMIZE:
BackToApplication();
break;
case IDC_MSRCONFIG :
PostMessage(hwnd, WM_MSRCONFIGURE,0,0);
break;
case IDC_EXIT :
PostMessage(hwnd, WM_MSRQUIT,0,0);
break;
case IDC_ANNOUNCE:
SetAnnounceWindow(IsDlgButtonChecked(hwnd,IDC_ANNOUNCE));
SetAnnounceMenu(IsDlgButtonChecked(hwnd,IDC_ANNOUNCE));
SetAnnouncePopup(IsDlgButtonChecked(hwnd,IDC_ANNOUNCE));
break;
case IDC_READING:
if (IsDlgButtonChecked(hwnd,IDC_READING))
SetEchoChars(MSR_ECHOALNUM | MSR_ECHOSPACE | MSR_ECHODELETE | MSR_ECHOMODIFIERS
| MSR_ECHOENTER | MSR_ECHOBACK | MSR_ECHOTAB);
else
SetEchoChars(0);
SetRegistryValues();
break;
case IDC_MOUSEPTR:
SetTrackInputFocus(IsDlgButtonChecked(hwnd,IDC_MOUSEPTR));
SetTrackCaret(IsDlgButtonChecked(hwnd,IDC_MOUSEPTR));
break;
case IDC_STARTMIN:
StartMin = IsDlgButtonChecked(hwnd,IDC_STARTMIN);
break;
}
}
return(FALSE); // didn't handle
}
/*************************************************************************
Function: AboutDlgProc
Purpose: Handles messages for the About Box dialog
Inputs:
Returns:
History:
*************************************************************************/
INT_PTR CALLBACK AboutDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
Shutup();
SetDialogIcon(hwnd);
// If minimized, Center on the desktop..
if ( IsIconic(g_hwndMain) )
{
CenterWindow(hwnd);
}
if (RunSecure(GetDesktop()) )
{
EnableWindow(GetDlgItem(hwnd, IDC_ENABLEWEBA), FALSE);
}
return TRUE;
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
Shutup();
EndDialog (hwnd, IDCANCEL);
return(TRUE);
}
break;
case WM_NOTIFY:
{
INT idCtl = (INT)wParam;
LPNMHDR pnmh = (LPNMHDR)lParam;
switch ( pnmh->code)
{
case NM_RETURN:
case NM_CLICK:
if ( idCtl == IDC_ENABLEWEBA && !RunSecure(GetDesktop()) )
{
TCHAR webAddr[256];
LoadString(g_hInst, IDS_ENABLEWEB, webAddr, 256);
ShellExecute(hwnd, NULL, webAddr, NULL, NULL, SW_SHOW);
}
break;
}
}
break;
};
return(FALSE); // didn't handle
}
/*************************************************************************
Function: WarnDlgProc
Purpose: Handles messages for the Warning dialog
Inputs:
Returns:
History:
*************************************************************************/
INT_PTR CALLBACK WarnDlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
Shutup();
SetDialogIcon(hwnd);
// If minimized, Center on the desktop..
if ( IsIconic(g_hwndMain) )
{
CenterWindow(hwnd);
}
return TRUE;
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_WARNING:
ShowWarn = !(IsDlgButtonChecked(hwnd,IDC_WARNING));
break;
case IDOK:
case IDCANCEL:
Shutup();
EndDialog (hwnd, IDCANCEL);
return(TRUE);
}
break;
case WM_NOTIFY:
{
INT idCtl = (INT)wParam;
LPNMHDR pnmh = (LPNMHDR)lParam;
switch ( pnmh->code)
{
case NM_RETURN:
case NM_CLICK:
if ( idCtl == IDC_ENABLEWEBA && !RunSecure(GetDesktop()))
{
TCHAR webAddr[256];
LoadString(g_hInst, IDS_ENABLEWEB, webAddr, 256);
ShellExecute(hwnd, NULL, webAddr, NULL, NULL, SW_SHOW);
}
break;
}
}
break;
};
return(FALSE); // didn't handle
}
#define SET_NUMREGENTRY(key, keyname, t) \
{ \
t value = Get ## keyname(); \
RegSetValueEx(key, TEXT(#keyname), 0, REG_DWORD, (CONST BYTE *)&value, sizeof(t)); \
}
#define GET_NUMREGENTRY(key, keyname, t) \
{ \
DWORD dwSize = sizeof(t); \
t value; \
if (RegQueryValueEx(key, TEXT(#keyname), 0, NULL, (BYTE *)&value, &dwSize) == ERROR_SUCCESS) \
Set ## keyname(value); \
}
/*************************************************************************
Function:
Purpose: Save registry values
Inputs:
Returns:
History:
*************************************************************************/
void SetRegistryValues()
{ // set up the registry
HKEY reg_key; // key for the registry
if (SUCCEEDED (RegOpenKeyEx (HKEY_CURRENT_USER,__TEXT("Software\\Microsoft\\Narrator"),0,KEY_WRITE,®_key)))
{
// These we are setting from data stored in narrhook.dll
SET_NUMREGENTRY(reg_key, TrackCaret, BOOL)
SET_NUMREGENTRY(reg_key, TrackInputFocus, BOOL)
SET_NUMREGENTRY(reg_key, EchoChars, int)
SET_NUMREGENTRY(reg_key, AnnounceWindow, BOOL)
SET_NUMREGENTRY(reg_key, AnnounceMenu, BOOL)
SET_NUMREGENTRY(reg_key, AnnouncePopup, BOOL)
SET_NUMREGENTRY(reg_key, AnnounceToolTips, BOOL)
SET_NUMREGENTRY(reg_key, ReviewLevel, int)
// These are properties of the speech engine or narrator itself
RegSetValueEx(reg_key,__TEXT("CurrentSpeed"),0,REG_DWORD,(unsigned char *) ¤tSpeed,sizeof(currentSpeed));
RegSetValueEx(reg_key,__TEXT("CurrentPitch"),0,REG_DWORD,(unsigned char *) ¤tPitch,sizeof(currentPitch));
RegSetValueEx(reg_key,__TEXT("CurrentVolume"),0,REG_DWORD,(unsigned char *) ¤tVolume,sizeof(currentVolume));
#ifndef SAPI5
RegSetValueEx(reg_key,__TEXT("CurrentVoice"),0,REG_DWORD,(unsigned char *) ¤tVoice,sizeof(currentVoice));
#else
RegSetValueEx(reg_key,__TEXT("CurrentVoice"),0,REG_SZ,
(unsigned char *) g_szVoices[currentVoice],lstrlen(g_szVoices[currentVoice])*sizeof(TCHAR)+sizeof(TCHAR));
#endif
RegSetValueEx(reg_key,__TEXT("StartType"),0,REG_DWORD,(unsigned char *) &StartMin,sizeof(StartMin));
RegSetValueEx(reg_key,__TEXT("ShowWarning"),0,REG_DWORD, (BYTE*) &ShowWarn,sizeof(ShowWarn));
RegCloseKey (reg_key);
return;
}
}
/*************************************************************************
Function:
Purpose: Get Registry values
Inputs:
Returns:
History:
*************************************************************************/
void GetRegistryValues()
{
DWORD result;
HKEY reg_key;
DWORD reg_size;
// We use RegCreateKeyEx instead of RegOpenKeyEx to make sure that the
// key is created if it doesn't exist. Note that if the key doesn't
// exist, the values used will already be set. All these values are
// globals imported from narrhook.dll
RegCreateKeyEx(HKEY_CURRENT_USER,__TEXT("Software\\Microsoft\\Narrator"),0,
__TEXT("MSR"),REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS, NULL, ®_key, &result);
if (result == REG_OPENED_EXISTING_KEY)
{
// These values go into narrhook DLL shared data
GET_NUMREGENTRY(reg_key, TrackCaret, BOOL)
GET_NUMREGENTRY(reg_key, TrackInputFocus, BOOL)
GET_NUMREGENTRY(reg_key, EchoChars, int)
GET_NUMREGENTRY(reg_key, AnnounceWindow, BOOL)
GET_NUMREGENTRY(reg_key, AnnounceMenu, BOOL)
GET_NUMREGENTRY(reg_key, AnnouncePopup, BOOL)
GET_NUMREGENTRY(reg_key, AnnounceToolTips, BOOL)
GET_NUMREGENTRY(reg_key, ReviewLevel, int)
// These values go into the speech engine or narrator itself
reg_size = sizeof(currentSpeed);
RegQueryValueEx(reg_key,__TEXT("CurrentSpeed"),0,NULL,(unsigned char *) ¤tSpeed,®_size);
reg_size = sizeof(currentPitch);
RegQueryValueEx(reg_key,__TEXT("CurrentPitch"),0,NULL,(unsigned char *) ¤tPitch,®_size);
reg_size = sizeof(currentVolume);
RegQueryValueEx(reg_key,__TEXT("CurrentVolume"),0,NULL,(unsigned char *) ¤tVolume,®_size);
#ifndef SAPI5
reg_size = sizeof(currentVoice);
RegQueryValueEx(reg_key,__TEXT("CurrentVoice"),0,NULL,(unsigned char *) ¤tVoice,®_size);
#else
reg_size = sizeof(g_szCurrentVoice);
RegQueryValueEx(reg_key,__TEXT("CurrentVoice"),0,NULL,(unsigned char *) g_szCurrentVoice,®_size);
#endif
// Minimized Value
reg_size = sizeof(StartMin);
RegQueryValueEx(reg_key,__TEXT("StartType"),0,NULL,(unsigned char *) &StartMin,®_size);
reg_size = sizeof(ShowWarn);
RegQueryValueEx(reg_key,__TEXT("ShowWarning"),0,NULL,(unsigned char *) &ShowWarn,®_size);
}
// If the key was just created, then these values should already be set.
// The values are exported from narrhook.dll, and must be initialized
// when they are declared.
RegCloseKey (reg_key);
}
/*************************************************************************
Function: InitApp
Purpose: Initalizes the application.
Inputs: HINSTANCE hInstance - Handle to the current instance
INT nCmdShow - how to present the window
Returns: TRUE if app initalized without error.
History:
*************************************************************************/
BOOL InitApp(HINSTANCE hInstance, int nCmdShow)
{
HMENU hSysMenu;
RECT rcWorkArea;
RECT rcWindow;
int xPos,yPos;
HRESULT hr;
#ifdef SAPI5
memset( g_szCurrentVoice, NULL, sizeof(g_szCurrentVoice) );
wcscpy( g_szCurrentVoice, L"Microsoft Sam" );
#endif
GetRegistryValues();
// SMode = InitMode();
// start COM
hr = CoInitialize(NULL);
if (FAILED (hr))
{
DBPRINTF (TEXT("CoInitialize on primary thread returned 0x%lX\r\n"),hr);
MessageBoxLoadStrings (NULL, IDS_NO_OLE, IDS_MSR_ERROR, MB_OK);
return FALSE;
}
// Create the TTS Objects
// sets the global variable g_pITTSCentral
// if it fails, will throw up a message box
if (InitTTS())
{
// Initialize Microsoft Active Accessibility
// this is in narrhook.dll
// Installs WinEvent hook, creates helper thread
if (InitMSAA())
{
// Set the system screenreader flag on.
// e.g. Word 97 will expose the caret position.
SystemParametersInfo(SPI_SETSCREENREADER, TRUE, NULL, SPIF_UPDATEINIFILE|SPIF_SENDCHANGE);
// Create the dialog box
g_hwndMain = CreateDialog(g_hInst, MAKEINTRESOURCE(IDD_MAIN),
0, MainDlgProc);
if (!g_hwndMain)
{
DBPRINTF(TEXT("unable to create main dialog\r\n"));
return(FALSE);
}
// Init global hot keys (need to do here because we need a hwnd)
InitKeys(g_hwndMain);
// set icon for this dialog if we can...
// not an easy way to do this that I know of.
// hIcon is in the WndClass, which means that if we change it for
// us, we change it for everyone. Which means that we would
// have to create a superclass that looks like a dialog but
// has it's own hIcon. Sheesh.
// Add "About Narrator..." menu item to system menu.
hSysMenu = GetSystemMenu(g_hwndMain,FALSE);
if (hSysMenu != NULL)
{
TCHAR szAboutMenu[100];
if (LoadString(g_hInst,IDS_ABOUTBOX,szAboutMenu,ARRAYSIZE(szAboutMenu)))
{
AppendMenu(hSysMenu,MF_SEPARATOR,NULL,NULL);
AppendMenu(hSysMenu,MF_STRING,IDM_ABOUTBOX,szAboutMenu);
}
}
// Place dialog at bottom right of screen:AK
HWND hWndInsertAfter;
BOOL fRunSecure = RunSecure(GetDesktop());
hWndInsertAfter = ( fRunSecure ) ? HWND_TOPMOST:HWND_TOP;
SystemParametersInfo (SPI_GETWORKAREA,NULL,&rcWorkArea,NULL);
GetWindowRect (g_hwndMain,&rcWindow);
xPos = rcWorkArea.right - (rcWindow.right - rcWindow.left);
yPos = rcWorkArea.bottom - (rcWindow.bottom - rcWindow.top);
SetWindowPos(g_hwndMain, hWndInsertAfter,
xPos, yPos, 0, 0, SWP_NOSIZE |SWP_NOACTIVATE);
// If Start type is Minimized.
if(StartMin || fRunSecure)
{
ShowWindow(g_hwndMain, SW_SHOWMINIMIZED);
// This is required to kill focus from Narrator
// And put the focus back to the active window.
PostMessage(g_hwndMain, WM_DELAYEDMINIMIZE, 0, 0);
}
else
ShowWindow(g_hwndMain,nCmdShow);
return TRUE;
}
}
// Something failed, exit false
return FALSE;
}
/*************************************************************************
Function: UnInitApp
Purpose: Shuts down the application
Inputs: none
Returns: TRUE if app uninitalized properly
History:
*************************************************************************/
BOOL UnInitApp(void)
{
SetRegistryValues();
if (UnInitTTS())
{
if (UnInitMSAA())
{
UninitKeys();
return TRUE;
}
}
return FALSE;
}
/*************************************************************************
Function: SpeakString
Purpose: Sends a string of text to the speech engine
Inputs: PSZ pszSpeakText - String of ANSI characters to be spoken
Speech control tags can be embedded.
Returns: BOOL - TRUE if string was buffered correctly
History:
*************************************************************************/
BOOL SpeakString(TCHAR * szSpeak, BOOL forceRead, DWORD dwFlags)
{
// Check for redundent speak, filter out, If it is not Forced read
if ((lstrcmp(szSpeak, g_szLastStringSpoken) == 0) && (forceRead == FALSE))
return FALSE;
if (dwFlags != SPEAK_MUTE)
{
if (szSpeak[0] == 0) // don't speak null string
return FALSE;
// if exiting stop
if (g_fAppExiting)
return FALSE;
// Different string, save off
lstrcpyn(g_szLastStringSpoken, szSpeak, MAX_TEXT);
g_szLastStringSpoken[MAX_TEXT-1] = TEXT('\0');
FilterSpeech(szSpeak);
// The L&H speech engine for japanese, goes crazy if you pass a
// " ", It now takes approx 1 min to come back to life. Need to remove
// once they fix their stuff! :a-anilk
if (lstrcmp(szSpeak, TEXT(" ")) == 0)
{
return FALSE;
}
#ifdef SAPI5
// if there is only punctuation then speak it
int i = 0;
int cAlpha = 0;
while( szSpeak[i] != NULL && i < MAX_TEXT)
{
if ( _istalpha(szSpeak[i++]) )
cAlpha++;
}
if ( !cAlpha )
dwFlags |= SPF_NLP_MASK;
#endif
}
#ifndef SAPI5
SDATA data;
data.dwSize = (DWORD)(lstrlen(szSpeak)+1) * sizeof(TCHAR);
data.pData = szSpeak;
g_pITTSCentral->TextData (CHARSET_TEXT, 0, data, NULL, IID_ITTSBufNotifySinkW);
#else
HRESULT hr = g_pISpV->Speak(szSpeak, dwFlags, NULL);
if (FAILED(hr))
{
DBPRINTF(TEXT("SpeakString: Speak returned 0x%x\r\n"), hr);
return FALSE;
}
#endif
SpewToFile(TEXT("%s\r\n"), szSpeak);
return TRUE;
}
/*************************************************************************
Function: InitTTS
Purpose: Starts the Text to Speech Engine
Inputs: none
Returns: BOOL - TRUE if successful
History:
*************************************************************************/
BOOL InitTTS(void)
{
// See if we have a Text To Speech engine to use, and initialize it if it is there.
#ifndef SAPI5
TTSMODEINFO ttsModeInfo;
memset (&ttsModeInfo, 0, sizeof(ttsModeInfo));
g_pITTSCentral = FindAndSelect (&ttsModeInfo);
if (!g_pITTSCentral)
#else
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_INPROC_SERVER, IID_ISpVoice, (void**)&g_pISpV);
if (FAILED(hr) || !g_pISpV)
#endif
{
MessageBoxLoadStrings (NULL, IDS_NO_TTS, IDS_MSR_ERROR, MB_OK);
return FALSE;
};
#ifdef SAPI5
memset( g_szVoices, NULL, sizeof(g_szVoices) );
memset( g_pVoiceTokens, NULL, sizeof(g_pVoiceTokens) );
ISpObjectToken *pDefaultVoiceToken = NULL;
WCHAR *szVoice = NULL;
hr = g_pISpV->GetVoice(&pDefaultVoiceToken);
if (SUCCEEDED(hr))
{
ISpObjectToken *pCurVoiceToken = pDefaultVoiceToken;
IEnumSpObjectTokens *pIEnumSpObjectTokens;
hr = SpEnumTokens(SPCAT_VOICES, NULL, NULL, &pIEnumSpObjectTokens);
if (SUCCEEDED(hr))
{
ISpObjectToken *pCurVoiceToken;
int i = 0;
while (pIEnumSpObjectTokens->Next(1, &pCurVoiceToken, NULL) == S_OK)
{
hr = pCurVoiceToken->GetStringValue(NULL, &szVoice);
if (SUCCEEDED(hr))
{
// if this test for MS Sam is removed all voices in the machine will appear
if ( wcscmp( szVoice, L"Microsoft Sam" ) == 0 )
{
currentVoice = i;
hr = g_pISpV->SetVoice( pCurVoiceToken );
if (FAILED(hr))
return FALSE;
g_szVoices[i] = szVoice;
g_pVoiceTokens[i++] = pCurVoiceToken;
}
}
else
{
return FALSE;
}
}
if ( currentVoice < 0 )
return FALSE;
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
SET_VALUE(SetPitch, currentPitch, lastPitch)
SET_VALUE(SetSpeed, currentSpeed, lastSpeed)
SET_VALUE(SetVolume, currentVolume, lastVolume)
#endif
return TRUE;
}
/*************************************************************************
Function: UnInitTTS
Purpose: Shuts down the Text to Speech subsystem
Inputs: none
Returns: BOOL - TRUE if successful
History:
*************************************************************************/
BOOL UnInitTTS(void)
{
#ifndef SAPI5
// Release out TTS object - if we have one
if (g_pITTSCentral)
{
g_pITTSCentral->Release();
g_pITTSCentral = 0;
}
// Release IITSAttributes - if we have one:a-anilk
if (g_pITTSAttributes)
{
g_pITTSAttributes->Release();
g_pITTSAttributes = 0;
}
if ( pIAMM )
{
pIAMM->Release();
pIAMM = NULL;
}
#else
// Release speech tokens and voice strings
for ( int i = 0; i < ARRAYSIZE( g_pVoiceTokens ) && g_pVoiceTokens[i] != NULL; i++ )
{
CoTaskMemFree(g_szVoices[i]);
g_pVoiceTokens[i]->Release();
}
// Release speech engine
if (g_pISpV)
{
g_pISpV->Release();
g_pISpV = 0;
}
#endif
return TRUE;
}
/*************************************************************************
Function: Shutup
Purpose: stops speaking, flushes speech buffers
Inputs: none
Returns: none
History:
*************************************************************************/
void Shutup(void)
{
#ifndef SAPI5
if (g_pITTSCentral && !g_fAppExiting)
g_pITTSCentral->AudioReset();
#else
if (g_pISpV && !g_fAppExiting)
SendMessage(g_hwndMain, WM_MSRSPEAKMUTE, 0, 0);
#endif
}
#ifndef SAPI5
/*************************************************************************
Function: FindAndSelect
Purpose: Selects the TTS engine
Inputs: PTTSMODEINFO pTTSInfo - Desired mode
Returns: PITTSCENTRAL - Pointer to ITTSCentral interface of engine
History: a-anilk created
*************************************************************************/
PITTSCENTRAL FindAndSelect(PTTSMODEINFO pTTSInfo)
{
PITTSCENTRAL pITTSCentral; // central interface
HRESULT hRes;
WORD voice;
TCHAR defaultVoice[128];
WORD defLangID;
hRes = CoCreateInstance (CLSID_TTSEnumerator, NULL, CLSCTX_ALL, IID_ITTSEnum, (void**)&g_pITTSEnum);
if (FAILED(hRes))
return NULL;
// Security Check, Disallow Non-Microsoft Engines on Logon desktops..
logonCheck = RunSecure(GetDesktop());
// Get the audio dest
hRes = CoCreateInstance(CLSID_MMAudioDest,
NULL,
CLSCTX_ALL,
IID_IAudioMultiMediaDevice,
(void**)&pIAMM);
if (FAILED(hRes))
return NULL; // error
pIAMM->DeviceNumSet (WAVE_MAPPER);
if ( !logonCheck )
{
hRes = g_pITTSEnum->Next(MAX_ENUMMODES,gaTTSInfo,&gnmodes);
if (FAILED(hRes))
{
DBPRINTF(TEXT("Failed to get any TTS Engine"));
return NULL; // error
}
defLangID = (WORD) GetUserDefaultUILanguage();
// If the voice needs to be changed, Check in the list of voices..
// If found a matching language, Great. Otherwise cribb! Anyway select a
// voice at the end, First one id none is found...
// If not initialized, Then we need to over ride voice
if ( currentVoice < 0 || currentVoice >= gnmodes )
{
for (voice = 0; voice < gnmodes; voice++)
{
if (gaTTSInfo[voice].language.LanguageID == defLangID)
break;
}
if (voice >= gnmodes)
voice = 0;
currentVoice = voice;
}
if( gaTTSInfo[currentVoice].language.LanguageID != defLangID )
{
// Error message saying that the language was not not found...AK
MessageBoxLoadStrings (NULL, IDS_LANGW, IDS_WARNING, MB_OK);
}
// Pass off the multi-media-device interface as an IUnknown (since it is one)
hRes = g_pITTSEnum->Select( gaTTSInfo[currentVoice].gModeID,
&pITTSCentral,
(LPUNKNOWN) pIAMM);
if (FAILED(hRes))
return NULL;
}
else
{
// Pass off the multi-media-device interface as an IUnknown (since it is one)
hRes = g_pITTSEnum->Select( MSTTS_GUID,
&pITTSCentral,
(LPUNKNOWN) pIAMM);
if (FAILED(hRes))
return NULL;
}
hRes = pITTSCentral->QueryInterface (IID_ITTSAttributes, (void**)&g_pITTSAttributes);
if( FAILED(hRes) )
return NULL;
else
{
GetSpeechMinMaxValues();
}
SET_VALUE(SetPitch, currentPitch, lastPitch)
SET_VALUE(SetSpeed, currentSpeed, lastSpeed)
SET_VALUE(SetVolume, currentVolume, lastVolume)
return pITTSCentral;
}
#endif // ifndef SAPI5
/*************************************************************************
Function:
Purpose:
Inputs:
Returns:
History:
*************************************************************************/
int MessageBoxLoadStrings (HWND hWnd,UINT uIDText,UINT uIDCaption,UINT uType)
{
TCHAR szText[1024];
TCHAR szCaption[128];
LoadString(g_hInst, uIDText, szText, sizeof(szText)/sizeof(TCHAR)); // raid #113790
LoadString(g_hInst, uIDCaption, szCaption, sizeof(szCaption)/sizeof(TCHAR)); // raid #113791
return (MessageBox(hWnd, szText, szCaption, uType));
}
// AssignDeskTop() For UM
// a-anilk. 1-12-98
static BOOL AssignDesktop(LPDWORD desktopID, LPTSTR pname)
{
HDESK hdesk;
wchar_t name[300];
DWORD nl;
*desktopID = DESKTOP_ACCESSDENIED;
hdesk = OpenInputDesktop(0, FALSE, MAXIMUM_ALLOWED);
if (!hdesk)
{
// OpenInputDesktop will mostly fail on "Winlogon" desktop
hdesk = OpenDesktop(__TEXT("Winlogon"),0,FALSE,MAXIMUM_ALLOWED);
if (!hdesk)
return FALSE;
}
GetUserObjectInformation(hdesk,UOI_NAME,name,300,&nl);
if (pname)
wcscpy(pname, name);
if (!_wcsicmp(name, __TEXT("Default")))
*desktopID = DESKTOP_DEFAULT;
else if (!_wcsicmp(name, __TEXT("Winlogon")))
{
*desktopID = DESKTOP_WINLOGON;
}
else if (!_wcsicmp(name, __TEXT("screen-saver")))
*desktopID = DESKTOP_SCREENSAVER;
else if (!_wcsicmp(name, __TEXT("Display.Cpl Desktop")))
*desktopID = DESKTOP_TESTDISPLAY;
else
*desktopID = DESKTOP_OTHER;
CloseDesktop(GetThreadDesktop(GetCurrentThreadId()));
SetThreadDesktop(hdesk);
return TRUE;
}
// InitMyProcessDesktopAccess
// a-anilk: 1-12-98
static BOOL InitMyProcessDesktopAccess(VOID)
{
origWinStation = GetProcessWindowStation();
userWinStation = OpenWindowStation(__TEXT("WinSta0"), FALSE, MAXIMUM_ALLOWED);
if (!userWinStation)
return FALSE;
SetProcessWindowStation(userWinStation);
return TRUE;
}
// ExitMyProcessDesktopAccess
// a-anilk: 1-12-98
static VOID ExitMyProcessDesktopAccess(VOID)
{
if (origWinStation)
SetProcessWindowStation(origWinStation);
if (userWinStation)
{
CloseWindowStation(userWinStation);
userWinStation = NULL;
}
}
// a-anilk added
// Returns the current desktop-ID
DWORD GetDesktop()
{
HDESK hdesk;
TCHAR name[300];
DWORD value, nl, desktopID = DESKTOP_ACCESSDENIED;
HKEY reg_key;
DWORD cbData = sizeof(DWORD);
LONG retVal;
// Check if we are in setup mode...
if (SUCCEEDED( RegOpenKeyEx(HKEY_LOCAL_MACHINE, __TEXT("SYSTEM\\Setup"), 0, KEY_READ, ®_key)) )
{
retVal = RegQueryValueEx(reg_key, __TEXT("SystemSetupInProgress"), 0, NULL, (LPBYTE) &value, &cbData);
RegCloseKey(reg_key);
if ( (retVal== ERROR_SUCCESS) && value )
// Setup is in progress...
return DESKTOP_ACCESSDENIED;
}
hdesk = OpenInputDesktop(0, FALSE, MAXIMUM_ALLOWED);
if (!hdesk)
{
// OpenInputDesktop will mostly fail on "Winlogon" desktop
hdesk = OpenDesktop(__TEXT("Winlogon"),0,FALSE,MAXIMUM_ALLOWED);
if (!hdesk)
return DESKTOP_WINLOGON;
}
GetUserObjectInformation(hdesk, UOI_NAME, name, 300, &nl);
CloseDesktop(hdesk);
if (!_wcsicmp(name, __TEXT("Default")))
desktopID = DESKTOP_DEFAULT;
else if (!_wcsicmp(name, __TEXT("Winlogon")))
desktopID = DESKTOP_WINLOGON;
else if (!_wcsicmp(name, __TEXT("screen-saver")))
desktopID = DESKTOP_SCREENSAVER;
else if (!_wcsicmp(name, __TEXT("Display.Cpl Desktop")))
desktopID = DESKTOP_TESTDISPLAY;
else
desktopID = DESKTOP_OTHER;
return desktopID;
}
//Confirmation dialog.
INT_PTR CALLBACK ConfirmProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
{
if ( IsIconic(g_hwndMain) )
{
CenterWindow(hwnd);
}
return TRUE;
}
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
Shutup();
EndDialog (hwnd, IDOK);
return(TRUE);
case IDCANCEL:
Shutup();
EndDialog (hwnd, IDCANCEL);
return(TRUE);
}
};
return(FALSE); // didn't handle
}
// Centers Narrator dialogs when main window is minimized:AK
void CenterWindow(HWND hwnd)
{
RECT rect, dRect;
GetWindowRect(GetDesktopWindow(), &dRect);
GetWindowRect(hwnd, &rect);
rect.left = (dRect.right - (rect.right - rect.left))/2;
rect.top = (dRect.bottom - (rect.bottom - rect.top))/2;
SetWindowPos(hwnd, HWND_TOPMOST ,rect.left,rect.top,0,0,SWP_NOSIZE | SWP_NOACTIVATE);
}
// Helper method Filters smiley face utterances: AK
void FilterSpeech(TCHAR* szSpeak)
{
// the GUID's have a Tab followed by a {0087....
// If you find this pattern. Then donot speak that:AK
if ( lstrlen(szSpeak) <= 3 )
return;
TCHAR *szSpeakBegin = szSpeak;
// make sure the we don't go over MAX_TEXT.
while((*(szSpeak+3)) != NULL && (szSpeak-szSpeakBegin < MAX_TEXT-3))
{
if ( (*szSpeak == '(') && iswalpha(*(szSpeak + 1)) && ( (*(szSpeak + 3) == ')')) )
{
// Replace by isAlpha drive...
*(szSpeak + 2) = ' ';
}
szSpeak++;
}
}
// Helper functions for combo boxes
int GetComboItemData(HWND hwnd)
{
int iValue = CB_ERR;
LRESULT iCurSel = SendMessage(hwnd, CB_GETCURSEL, 0, 0);
if (iCurSel != CB_ERR)
iValue = SendMessage(hwnd, CB_GETITEMDATA, iCurSel, 0);
return iValue;
}
void FillAndSetCombo(HWND hwnd, int iMinVal, int iMaxVal, int iSelVal)
{
SendMessage(hwnd, CB_RESETCONTENT, 0, 0);
int iSelPos = -1;
for (int i=0;iMaxVal >= iMinVal;i++, iMaxVal--)
{
TCHAR szItem[100];
wsprintf(szItem, TEXT("%d"), iMaxVal);
int iPos = SendMessage(hwnd, CB_ADDSTRING, 0, (LPARAM)szItem);
SendMessage(hwnd, CB_SETITEMDATA, iPos, iMaxVal);
if (iSelVal == iMaxVal)
iSelPos = iPos; // note the current selection
}
// show the current value
SendMessage(hwnd, CB_SETCURSEL, iSelPos, 0);
}
/*************************************************************************
THE INFORMATION AND CODE PROVIDED HEREUNDER (COLLECTIVELY REFERRED TO
AS "SOFTWARE") IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN
NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR
ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL,
CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF
MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR
LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE
FOREGOING LIMITATION MAY NOT APPLY.
*************************************************************************/
| 31.215049 | 129 | 0.581948 | [
"object"
] |
9df0795bf465759bc3fe7f9df717d9567ee0aeed | 2,812 | cpp | C++ | demo/thread-pools/thread-pools.cpp | AndreLouisCaron/w32 | 75b26a149e268138cbcf43e6f4669756ac4ac850 | [
"BSD-2-Clause"
] | 9 | 2015-12-30T15:21:20.000Z | 2021-03-21T04:23:14.000Z | demo/thread-pools/thread-pools.cpp | AndreLouisCaron/w32 | 75b26a149e268138cbcf43e6f4669756ac4ac850 | [
"BSD-2-Clause"
] | 1 | 2022-01-02T11:12:57.000Z | 2022-01-02T11:12:57.000Z | demo/thread-pools/thread-pools.cpp | AndreLouisCaron/w32 | 75b26a149e268138cbcf43e6f4669756ac4ac850 | [
"BSD-2-Clause"
] | 5 | 2018-04-09T04:44:58.000Z | 2020-04-10T12:51:51.000Z | // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <w32.hpp>
#include <w32.mt.hpp>
#include <w32.tp.hpp>
namespace {
void foo ( w32::tp::Hints&, void * context )
{
std::cout << "foo(0x" << context << ")" << std::endl;
}
void bar ( w32::tp::Hints&, void * context )
{
std::cout << "bar(0x" << context << ")" << std::endl;
}
void __stdcall meh ( void * object, void * cleanup )
{
std::cout << "meh(0x" << object
<< ",0x" << cleanup << ")" << std::endl;
}
}
#include <w32/app/console-program.hpp>
namespace {
int run ( int argc, wchar_t ** argv )
{
// Create a thread pool and associated work queue.
w32::tp::Pool pool; pool.threads(1);
w32::tp::Queue queue(pool);
// Dummy context.
int a = 0; int b = 1; int c = 2;
std::cout << "&a = 0x" << &a << std::endl;
std::cout << "&b = 0x" << &b << std::endl;
std::cout << "&c = 0x" << &c << std::endl;
// Queue jobs.
w32::tp::Timer foo(queue, w32::tp::Timer::function<&::foo>(), &a);
w32::tp::Timer bar(queue, w32::tp::Timer::function<&::bar>(), &b);
foo.start(2000);
bar.start(5000);
// Wait for 'foo()' to finish, but not 'bar()'.
w32::mt::sleep(w32::Timespan(4000));
return (EXIT_SUCCESS);
}
}
#include <w32/app/console-program.cpp>
| 34.292683 | 75 | 0.620555 | [
"object"
] |
9df2a853531d5aa3452aa7ea89a2645c78e1a81b | 701 | cpp | C++ | src/NodeRTLib/CppTemplates/StaticPropertyGetter.cpp | appliedrd/NodeRT | 10b3003032078d2ae43db56636f094f1f5d6836e | [
"Apache-2.0"
] | 568 | 2015-01-06T17:35:15.000Z | 2022-03-09T17:51:38.000Z | src/NodeRTLib/CppTemplates/StaticPropertyGetter.cpp | appliedrd/NodeRT | 10b3003032078d2ae43db56636f094f1f5d6836e | [
"Apache-2.0"
] | 141 | 2015-02-11T20:49:13.000Z | 2022-02-25T11:36:51.000Z | src/NodeRTLib/CppTemplates/StaticPropertyGetter.cpp | appliedrd/NodeRT | 10b3003032078d2ae43db56636f094f1f5d6836e | [
"Apache-2.0"
] | 58 | 2015-05-03T10:05:08.000Z | 2022-02-07T21:23:17.000Z |
static void @(Model.Name)Getter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) {
HandleScope scope;
try
{@{
var jsConversionInfo = Converter.ToJS(Model.PropertyType, TX.MainModel.Types.ContainsKey(Model.PropertyType));
var winrtConversionInfo = Converter.ToWinRT(Model.PropertyType);
}
@winrtConversionInfo[0] result = @(TX.ToWinRT(Model.DeclaringType, false))::@(Model.Name);
info.GetReturnValue().Set(@string.Format(jsConversionInfo[1], "result"));
return;
} catch (Platform::Exception ^exception) {
NodeRT::Utils::ThrowWinRtExceptionInJs(exception);
return;
}
}
| 38.944444 | 120 | 0.654779 | [
"model"
] |
9df683e3105e79585e280a553ee00f5bd3c718c4 | 5,764 | cpp | C++ | test/test_math.cpp | tristanpenman/gameutils | d4695922c6a8ba201a67fc8e5319da53e0d25323 | [
"BSD-2-Clause"
] | null | null | null | test/test_math.cpp | tristanpenman/gameutils | d4695922c6a8ba201a67fc8e5319da53e0d25323 | [
"BSD-2-Clause"
] | null | null | null | test/test_math.cpp | tristanpenman/gameutils | d4695922c6a8ba201a67fc8e5319da53e0d25323 | [
"BSD-2-Clause"
] | null | null | null | #include "gameutils/math.h"
#include "gtest/gtest.h"
using gameutils::Vec2;
using gameutils::Vec3;
using gameutils::Mat3;
using gameutils::Mat4;
using gameutils::Quat;
class TestMath : public testing::Test
{
};
//----------------------------------------------------------------------------
//
// Vec2
//
//----------------------------------------------------------------------------
TEST_F(TestMath, Vec2_arithmetic)
{
const Vec2<double> v1(1.0, 1.0);
Vec2<double> v2(1.0, 2.0);
v2 += v1;
EXPECT_EQ(2.0, v2.x);
EXPECT_EQ(3.0, v2.y);
v2 = v2 + v1;
EXPECT_EQ(3.0, v2.x);
EXPECT_EQ(4.0, v2.y);
v2 -= v1;
EXPECT_EQ(2.0, v2.x);
EXPECT_EQ(3.0, v2.y);
v2 = v2 - v1;
EXPECT_EQ(1.0, v2.x);
EXPECT_EQ(2.0, v2.y);
v2 *= 2.0;
EXPECT_EQ(2.0, v2.x);
EXPECT_EQ(4.0, v2.y);
v2 = v2 * 2.0;
EXPECT_EQ(4.0, v2.x);
EXPECT_EQ(8.0, v2.y);
v2 = 2.0 * v2;
EXPECT_EQ(8.0, v2.x);
EXPECT_EQ(16.0, v2.y);
v2 /= 2.0;
EXPECT_EQ(4.0, v2.x);
EXPECT_EQ(8.0, v2.y);
v2 = v2 / 2.0;
EXPECT_EQ(2.0, v2.x);
EXPECT_EQ(4.0, v2.y);
}
TEST_F(TestMath, Vec2_assignment)
{
const Vec2<double> v1(3.0, 4.0);
Vec2<double> v2(10.0, 5.0);
v2 = v1;
EXPECT_EQ(3.0, v2.x);
EXPECT_EQ(4.0, v2.y);
}
TEST_F(TestMath, Vec2_comparison)
{
const Vec2<double> v0(3.0, 4.0);
const Vec2<double> v1(3.0, 4.0);
const Vec2<double> v2(3.0, 5.0);
const Vec2<double> v3(4.0, 5.0);
EXPECT_TRUE(v0.equalTo(v0, 5));
EXPECT_TRUE(v0.equalTo(v1, 5));
EXPECT_FALSE(v0.equalTo(v2, 5));
EXPECT_FALSE(v0.equalTo(v3, 5));
EXPECT_TRUE(v1.equalTo(v0, 5));
EXPECT_TRUE(v1.equalTo(v1, 5));
EXPECT_FALSE(v1.equalTo(v2, 5));
EXPECT_FALSE(v1.equalTo(v3, 5));
EXPECT_FALSE(v2.equalTo(v0, 5));
EXPECT_FALSE(v2.equalTo(v1, 5));
EXPECT_TRUE(v2.equalTo(v2, 5));
EXPECT_FALSE(v2.equalTo(v3, 5));
EXPECT_FALSE(v3.equalTo(v0, 5));
EXPECT_FALSE(v3.equalTo(v1, 5));
EXPECT_FALSE(v3.equalTo(v2, 5));
EXPECT_TRUE(v3.equalTo(v3, 5));
}
TEST_F(TestMath, Vec2_construction)
{
const Vec2<double> v1(3.0, 4.0);
EXPECT_EQ(3.0, v1.x);
EXPECT_EQ(4.0, v1.y);
const Vec2<double> v2;
EXPECT_EQ(0.0, v2.x);
EXPECT_EQ(0.0, v2.y);
}
TEST_F(TestMath, Vec2_dot)
{
const Vec2<double> v1(3.0, 4.0);
const Vec2<double> v2(2.0, 5.0);
double dotProduct = v1.dot(v2);
EXPECT_EQ(26.0, dotProduct);
}
TEST_F(TestMath, Vec2_length)
{
const Vec2<double> v1(3.0, 4.0);
const double epsilon = 0.00001;
const double expectedLength = sqrt(3.0 * 3.0 + 4.0 * 4.0);
const double actualLength = v1.length();
EXPECT_TRUE(abs(expectedLength - actualLength) < epsilon);
}
TEST_F(TestMath, Vec2_perp)
{
const Vec2<double> v1(3.0, 4.0);
const Vec2<double> v2 = v1.perp();
EXPECT_EQ(-v1.y, v2.x);
EXPECT_EQ( v1.x, v2.y);
}
//----------------------------------------------------------------------------
//
// Mat3
//
//----------------------------------------------------------------------------
TEST_F(TestMath, Mat3_inverse)
{
// Ensure that multiplying a vector by a matrix followed by the matrix
// inverse results in the original vector.
Vec3<float> v(1, 2, 3);
Mat3<float> m(
2.0, 4.0, 9.0,
3.0, -1.0, 1.0,
0.0, 10.0, 1.0);
Vec3<float> actual = m.inverse() * m * v;
EXPECT_TRUE(actual.equalTo(v, 5));
}
TEST_F(TestMath, Mat3_invert)
{
// Ensure that multiplying a vector by a matrix followed by the matrix
// inverse results in the original vector, when the in-place invert()
// method is used.
Vec3<float> v(1, 2, 3);
Mat3<float> m(
1.0, 3.0, 3.0,
3.0, -1.0, 1.3,
0.0, 10.0, 1.0);
Vec3<float> actual = m * v; // Transform vector
m.invert();
actual = m * actual; // Reverse transformation
EXPECT_TRUE(actual.equalTo(v, 5));
}
//----------------------------------------------------------------------------
//
// Quat
//
//----------------------------------------------------------------------------
TEST_F(TestMath, Quat_multiplication)
{
// Ensure that quaternion multiplication produces the correct result for
// an example pulled from a Wolfram Alpha query:
// quaternion -Sin[Pi]+3i+4j+3k multiplied by -1j+3.9i+4-3k
Quat<float> a(-std::sin(M_PI), 3, 4, 3);
Quat<float> b(4, 3.9, -1, -3);
Quat<float> actual = a * b;
Quat<float> expected(1.3, 3, 36.7, -6.6);
EXPECT_TRUE(actual.equalTo(expected, 5));
// Ensure that the same result is produced using in-place multiplication
actual = a;
actual *= b;
EXPECT_TRUE(actual.equalTo(expected, 5));
// Ensure that quaternion multiplication produces the correct result when
// multiplying a quaternion by itself.
Quat<float> c = Quat<float>::rotation(M_PI / 4, 1, 0, 0);
actual = c * c;
expected = Quat<float>::rotation(M_PI / 2, 1, 0, 0);
EXPECT_TRUE(actual.equalTo(expected, 5));
// Ensure that the same result is produced using in-place multiplication
actual = c;
actual *= c;
EXPECT_TRUE(actual.equalTo(expected, 5));
}
TEST_F(TestMath, Quat_rotation)
{
Quat<float> a = Quat<float>::rotation(M_PI / 2, 1, 0, 0);
// Ensure that the inverse of this quaternion is equal to its transpose,
// since rotation should produce an orthogonal matrix.
Mat4<float> b = Mat4<float>(a.makeMat3().inverse());
Mat4<float> c = a.makeMat4().transpose();
EXPECT_TRUE(b.equalTo(c, 5));
}
| 25.847534 | 79 | 0.534698 | [
"vector",
"transform"
] |
9dfb80f4c77eb704748ec07f6e4a4a6353c4f223 | 2,878 | hpp | C++ | legacy/multiple_occupancy_3d/gillespie3d.hpp | physics-based-ml/LatticeGillespieCpp | 2d583bc4cd762b7d6a045eaf9d3b680cf3616888 | [
"MIT"
] | null | null | null | legacy/multiple_occupancy_3d/gillespie3d.hpp | physics-based-ml/LatticeGillespieCpp | 2d583bc4cd762b7d6a045eaf9d3b680cf3616888 | [
"MIT"
] | null | null | null | legacy/multiple_occupancy_3d/gillespie3d.hpp | physics-based-ml/LatticeGillespieCpp | 2d583bc4cd762b7d6a045eaf9d3b680cf3616888 | [
"MIT"
] | null | null | null | // vector
#ifndef VECTOR_h
#define VECTOR_h
#include <vector>
#endif
// string
#ifndef STRING_h
#define STRING_h
#include <string>
#endif
// Other Gillespie3D
#ifndef SPECIES_h
#define SPECIES_h
#include "species.hpp"
#endif
#ifndef REACTIONS_h
#define REACTIONS_h
#include "reactions.hpp"
#endif
#ifndef LATTICE_h
#define LATTICE_h
#include "lattice.hpp"
#endif
/************************************
* Namespace for Gillespie3D
************************************/
namespace Gillespie3D {
/****************************************
General functions
****************************************/
// Write vector to file
void write_vector_to_file(std::string fname, std::vector<int> v);
// Print mvec
std::ostream& operator<<(std::ostream& os, const std::vector<Species>& vs);
/****************************************
Main simulation class
****************************************/
class Simulation
{
private:
// The lattice
Lattice _lattice;
// List of species
std::vector<Species> _species;
// List of bimol rxns
std::vector<BiReaction> _bi_rxns;
// List of unimol rxns
std::vector<UniReaction> _uni_rxns;
// Current time
double _t;
// Timestep
double _dt;
// Time and value of the next unimolecular reaction
double _t_uni_next;
UniReaction *_uni_next; // Null indicates there is none scheduled
/********************
Find a species by name
********************/
Species* _find_species(std::string name);
/********************
Schedule the next uni reaction
********************/
void _schedule_uni();
public:
/********************
Constructor/Destructor
********************/
Simulation(double dt, int box_length);
~Simulation();
/********************
Add species
********************/
void add_species(std::string name, bool conserved = false);
/********************
Add a reaction
********************/
// Unimolecular rxn
void add_uni_rxn(std::string name, double kr, std::string r);
void add_uni_rxn(std::string name, double kr, std::string r, std::string p);
void add_uni_rxn(std::string name, double kr, std::string r, std::string p1, std::string p2);
// Bimolecular rxn
void add_bi_rxn(std::string name, double prob, std::string r1, std::string r2);
void add_bi_rxn(std::string name, double prob, std::string r1, std::string r2, std::string p);
void add_bi_rxn(std::string name, double prob, std::string r1, std::string r2, std::string p1, std::string p2);
/********************
Populate lattice
********************/
void populate_lattice(std::map<std::string,int> counts);
/********************
Run simulation
********************/
void run(int n_timesteps, bool verbose = false, bool write_statistics = false);
/********************
Write lattice
********************/
void write_lattice(int index);
};
}; | 21.161765 | 113 | 0.561849 | [
"vector"
] |
3b026d8eb80b8e365121cfa9c3f4240a0de9e831 | 2,941 | cpp | C++ | test/numeric_test.cpp | sebrockm/Linqpp | 6689f6cbb076b30f260ef4cee2dd657cd6b8cc36 | [
"MIT"
] | 7 | 2017-08-09T06:12:15.000Z | 2021-09-23T01:00:51.000Z | test/numeric_test.cpp | sebrockm/Linqpp | 6689f6cbb076b30f260ef4cee2dd657cd6b8cc36 | [
"MIT"
] | null | null | null | test/numeric_test.cpp | sebrockm/Linqpp | 6689f6cbb076b30f260ef4cee2dd657cd6b8cc36 | [
"MIT"
] | null | null | null | #include <complex>
#include <forward_list>
#include <limits>
#include <list>
#include <vector>
#include "Linqpp.hpp"
#include "catch.hpp"
using namespace Linqpp;
TEST_CASE("numeric tests")
{
std::vector<int> ran = { 1, 2, 3, 4, 5 };
std::list<int> bid = { 6, 7, 8, 9 };
std::forward_list<int> forw = { 3, 4, 5, 6, 7 };
auto inp = []
{
START_YIELDING(int)
for (int i = -1; i < 7; ++i)
yield_return(i);
END_YIELDING
};
SECTION("Average")
{
CHECK(From(ran).Average() == Approx(3));
CHECK(From(bid).Average() == Approx(7.5));
CHECK(From(forw).Average() == Approx(5));
CHECK(inp().Average() == Approx(2.5));
long long n = 1'000'000;
CHECK(Enumerable::Range(1, n).Average() == Approx((n + 1) / 2.0));
CHECK(Enumerable::Range(0, n).Average() == Approx((n - 1) / 2.0));
CHECK(Enumerable::Range(1, n).Reverse().Average() == Approx((n + 1) / 2.0));
CHECK(Enumerable::Range(0, n).Reverse().Average() == Approx((n - 1) / 2.0));
n *= 100;
CHECK(Enumerable::Range(1, n).Average() == Approx((n + 1) / 2.0));
CHECK(Enumerable::Range(0, n).Average() == Approx((n - 1) / 2.0));
CHECK(Enumerable::Range(1, n).Reverse().Average() == Approx((n + 1) / 2.0));
CHECK(Enumerable::Range(0, n).Reverse().Average() == Approx((n - 1) / 2.0));
auto smallAndBig = Enumerable::Repeat(0.001, n).Concat(Enumerable::Repeat(n / 1'000.0, 1));
auto avg = Approx(n / 500.0 / (n + 1));
CHECK(smallAndBig.Average() == avg);
CHECK(smallAndBig.Reverse().Average() == avg);
CHECK(Enumerable::Repeat(std::numeric_limits<double>::max() / 2, 100).Average() == Approx(std::numeric_limits<double>::max() / 2));
CHECK(Enumerable::Repeat(std::numeric_limits<double>::min() / 2, 100).Average() == Approx(std::numeric_limits<double>::min() / 2));
using namespace std::literals::complex_literals;
std::vector<std::complex<double>> vec = { 1.0 + 2.0i, 4.0 - 6.0i, -3.0 + 4.0i, -5.0, 2.0i };
CHECK(From(vec).Average().real() == Approx(-0.6));
CHECK(From(vec).Average().imag() == Approx(0.4));
}
SECTION("Sum")
{
CHECK(From(ran).Sum() == 15);
CHECK(From(ran).Sum([](auto i) { return i * i; }) == 55);
CHECK(From(bid).Sum() == 30);
CHECK(From(bid).Sum([](auto i) { return i * i; }) == 230);
CHECK(From(forw).Sum() == 25);
CHECK(From(forw).Sum([](auto i) { return i * i; }) == 135);
CHECK(From(inp()).Sum() == 20);
CHECK(From(inp()).Sum([](auto i) { return i * i; }) == 92);
using namespace std::literals::complex_literals;
std::vector<std::complex<double>> vec = { 1.0 + 2.0i, 4.0 - 6.0i, -3.0 + 4.0i, -5.0, 2.0i };
CHECK(From(vec).Sum().real() == Approx(-3.0));
CHECK(From(vec).Sum().imag() == Approx(2.0));
}
}
| 37.705128 | 139 | 0.532132 | [
"vector"
] |
3b085c25f707d4b112e3507a71bfa92185405b8c | 3,900 | cpp | C++ | AGVCCON/fFastLoading.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | AGVCCON/fFastLoading.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | AGVCCON/fFastLoading.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------------------
// COPYRIGHT NOTICE
// ----------------------------------------------------------------------------------------
//
// The Source Code Store LLC
// ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC
// ActiveX Control
// Copyright (c) 2002-2017 The Source Code Store LLC
//
// All Rights Reserved. No parts of this file may be reproduced, modified or transmitted
// in any form or by any means without the written permission of the author.
//
// ----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "AGVCCON.h"
#include "fFastLoading.h"
IMPLEMENT_DYNAMIC(fFastLoading, CDialog)
fFastLoading::fFastLoading(CWnd* pParent /*=NULL*/)
: CDialog(fFastLoading::IDD, pParent)
{
}
fFastLoading::~fFastLoading()
{
}
void fFastLoading::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_ACTIVEGANTTVCCTL1, ActiveGanttVCCtl1);
}
BEGIN_MESSAGE_MAP(fFastLoading, CDialog)
ON_WM_SIZE()
END_MESSAGE_MAP()
BOOL fFastLoading::OnInitDialog()
{
CDialog::OnInitDialog();
g_MaximizeWindowsDim(this);
CWnd::ShowWindow(SW_SHOWMAXIMIZED);
//If you open the form: Styles And Templates -> Available Templates in the main menu (fTemplates.vb)
//you can preview all available Templates.
//Or you can also build your own:
//fMSProject11.vb shows you how to build a Solid Template in the InitializeAG Method.
//fMSProject14.vb shows you how to build a Gradient Template in the InitializeAG Method.
ActiveGanttVCCtl1.ApplyTemplate(STC_CH_VGRAD_ANAKIWA_BLUE, STO_DEFAULT);
int i = 0;
ActiveGanttVCCtl1.GetColumns().Add(_T("Tasks"), _T(""), 200, _T(""));
ActiveGanttVCCtl1.SetTreeviewColumnIndex(1);
ActiveGanttVCCtl1.GetRows().BeginLoad(FALSE);
ActiveGanttVCCtl1.GetTasks().BeginLoad(FALSE);
int lCurrentDepth = 0;
for (i = 1; i <= 5000; i++)
{
CclsRow oRow;
CclsTask oTask;
oRow = ActiveGanttVCCtl1.GetRows().Load(_T("K") + CStr(i));
oTask = ActiveGanttVCCtl1.GetTasks().Load(_T("K") + CStr(i), _T("K") + CStr(i));
oRow.SetHeight(20);
oRow.SetText(_T("Task K") + CStr(i));
oRow.SetMergeCells(TRUE);
oRow.GetNode().SetDepth(lCurrentDepth);
oTask.SetText(_T("K") + CStr(i));
oTask.SetStartDate(ActiveGanttVCCtl1.GetMathLib().DateTimeAdd(IL_HOUR, GetRnd(0, 5), GetCurrentDateTime()));
oTask.SetEndDate(ActiveGanttVCCtl1.GetMathLib().DateTimeAdd(IL_HOUR, GetRnd(2, 7), oTask.GetStartDate()));
lCurrentDepth = lCurrentDepth + GetRnd(-1, 1);
if (lCurrentDepth < 0)
{
lCurrentDepth = 0;
}
}
ActiveGanttVCCtl1.GetTasks().EndLoad();
ActiveGanttVCCtl1.GetRows().EndLoad();
ActiveGanttVCCtl1.GetRows().BeginLoad(TRUE);
ActiveGanttVCCtl1.GetTasks().BeginLoad(TRUE);
for (i = 5001; i <= 10000; i++)
{
CclsRow oRow;
CclsTask oTask;
oRow = ActiveGanttVCCtl1.GetRows().Load(_T("KL") + CStr(i));
oTask = ActiveGanttVCCtl1.GetTasks().Load(_T("KL") + CStr(i), _T("KL") + CStr(i));
oRow.SetHeight(20);
oRow.SetText(_T("Task KL") + CStr(i));
oRow.SetMergeCells(TRUE);
oTask.SetText(_T("KL") + CStr(i));
oTask.SetStartDate(ActiveGanttVCCtl1.GetMathLib().DateTimeAdd(IL_HOUR, GetRnd(0, 5), GetCurrentDateTime()));
oTask.SetEndDate(ActiveGanttVCCtl1.GetMathLib().DateTimeAdd(IL_HOUR, GetRnd(2, 7), oTask.GetStartDate()));
}
ActiveGanttVCCtl1.GetTasks().EndLoad();
ActiveGanttVCCtl1.GetRows().EndLoad();
ActiveGanttVCCtl1.Redraw();
return TRUE;
}
BEGIN_EVENTSINK_MAP(fFastLoading, CDialog)
END_EVENTSINK_MAP()
void fFastLoading::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
g_Resize(this, &ActiveGanttVCCtl1);
} | 34.513274 | 116 | 0.638462 | [
"solid"
] |
3b0e606c9d855e867f6f18125402df9cd58456ba | 9,385 | cc | C++ | node_modules/nodegit/src/buf.cc | jiumx60rus/grishyGhost | c56241304da11b9a1307c6261cca50f7546981b1 | [
"MIT"
] | null | null | null | node_modules/nodegit/src/buf.cc | jiumx60rus/grishyGhost | c56241304da11b9a1307c6261cca50f7546981b1 | [
"MIT"
] | null | null | null | node_modules/nodegit/src/buf.cc | jiumx60rus/grishyGhost | c56241304da11b9a1307c6261cca50f7546981b1 | [
"MIT"
] | null | null | null | // This is a generated file, modify: generate/templates/class_content.cc.
#include <nan.h>
#include <string.h>
#include <chrono>
#include <thread>
extern "C" {
#include <git2.h>
}
#include "../include/functions/copy.h"
#include "../include/macros.h"
#include "../include/buf.h"
#include "../include/buf.h"
#include <iostream>
using namespace std;
using namespace v8;
using namespace node;
GitBuf::GitBuf(git_buf *raw, bool selfFreeing) {
this->raw = raw;
this->selfFreeing = selfFreeing;
}
GitBuf::~GitBuf() {
if (this->selfFreeing) {
git_buf_free(this->raw);
this->raw = NULL;
}
// this will cause an error if you have a non-self-freeing object that also needs
// to save values. Since the object that will eventually free the object has no
// way of knowing to free these values.
}
void GitBuf::InitializeComponent(Handle<v8::Object> target) {
NanScope();
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(JSNewFunction);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->SetClassName(NanNew<String>("Buf"));
NODE_SET_PROTOTYPE_METHOD(tpl, "containsNul", ContainsNul);
NODE_SET_PROTOTYPE_METHOD(tpl, "free", Free);
NODE_SET_PROTOTYPE_METHOD(tpl, "grow", Grow);
NODE_SET_PROTOTYPE_METHOD(tpl, "isBinary", IsBinary);
NODE_SET_PROTOTYPE_METHOD(tpl, "set", Set);
NODE_SET_PROTOTYPE_METHOD(tpl, "ptr", Ptr);
NODE_SET_PROTOTYPE_METHOD(tpl, "asize", Asize);
NODE_SET_PROTOTYPE_METHOD(tpl, "size", Size);
Local<Function> _constructor_template = tpl->GetFunction();
NanAssignPersistent(constructor_template, _constructor_template);
target->Set(NanNew<String>("Buf"), _constructor_template);
}
NAN_METHOD(GitBuf::JSNewFunction) {
NanScope();
if (args.Length() == 0 || !args[0]->IsExternal()) {
return NanThrowError("A new GitBuf cannot be instantiated.");
}
GitBuf* object = new GitBuf(static_cast<git_buf *>(Handle<External>::Cast(args[0])->Value()), args[1]->BooleanValue());
object->Wrap(args.This());
NanReturnValue(args.This());
}
Handle<v8::Value> GitBuf::New(void *raw, bool selfFreeing) {
NanEscapableScope();
Handle<v8::Value> argv[2] = { NanNew<External>((void *)raw), NanNew<Boolean>(selfFreeing) };
return NanEscapeScope(NanNew<Function>(GitBuf::constructor_template)->NewInstance(2, argv));
}
git_buf *GitBuf::GetValue() {
return this->raw;
}
git_buf **GitBuf::GetRefValue() {
return this->raw == NULL ? NULL : &this->raw;
}
void GitBuf::ClearValue() {
this->raw = NULL;
}
/*
* @return Number result */
NAN_METHOD(GitBuf::ContainsNul) {
NanEscapableScope();
int result = git_buf_contains_nul(
ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue()
);
Handle<v8::Value> to;
// start convert_to_v8 block
to = NanNew<Number>( result);
// end convert_to_v8 block
NodeGitPsueodoNanReturnEscapingValue(to);
}
/*
*/
NAN_METHOD(GitBuf::Free) {
NanEscapableScope();
if (ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue() != NULL) {
git_buf_free(
ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue()
);
ObjectWrap::Unwrap<GitBuf>(args.This())->ClearValue();
}
NanReturnUndefined();
}
/*
* @param Number target_size
* @param Buf callback
*/
NAN_METHOD(GitBuf::Grow) {
NanScope();
if (args.Length() == 0 || !args[0]->IsNumber()) {
return NanThrowError("Number target_size is required.");
}
if (args.Length() == 1 || !args[1]->IsFunction()) {
return NanThrowError("Callback is required and must be a Function.");
}
GrowBaton* baton = new GrowBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->buffer = (git_buf *)malloc(sizeof(git_buf ));
// start convert_from_v8 block
size_t from_target_size;
from_target_size = (size_t) args[0]->ToNumber()->Value();
// end convert_from_v8 block
baton->target_size = from_target_size;
NanCallback *callback = new NanCallback(Local<Function>::Cast(args[1]));
GrowWorker *worker = new GrowWorker(baton, callback);
if (!args[0]->IsUndefined() && !args[0]->IsNull())
worker->SaveToPersistent("target_size", args[0]->ToObject());
NanAsyncQueueWorker(worker);
NanReturnUndefined();
}
void GitBuf::GrowWorker::Execute() {
int result = git_buf_grow(
baton->buffer,baton->target_size );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitBuf::GrowWorker::HandleOKCallback() {
TryCatch try_catch;
if (baton->error_code == GIT_OK) {
Handle<v8::Value> to;
// start convert_to_v8 block
if (baton->buffer != NULL) {
// GitBuf baton->buffer
to = GitBuf::New((void *)baton->buffer, false);
}
else {
to = NanNull();
}
// end convert_to_v8 block
Handle<v8::Value> result = to;
Handle<v8::Value> argv[2] = {
NanNull(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Handle<v8::Value> argv[1] = {
NanError(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else {
callback->Call(0, NULL);
}
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete baton;
}
/*
* @return Number result */
NAN_METHOD(GitBuf::IsBinary) {
NanEscapableScope();
int result = git_buf_is_binary(
ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue()
);
Handle<v8::Value> to;
// start convert_to_v8 block
to = NanNew<Number>( result);
// end convert_to_v8 block
NodeGitPsueodoNanReturnEscapingValue(to);
}
/*
* @param Buffer data
* @param Number datalen
* @param Buf callback
*/
NAN_METHOD(GitBuf::Set) {
NanScope();
if (args.Length() == 0 || !args[0]->IsObject()) {
return NanThrowError("Buffer data is required.");
}
if (args.Length() == 1 || !args[1]->IsNumber()) {
return NanThrowError("Number datalen is required.");
}
if (args.Length() == 2 || !args[2]->IsFunction()) {
return NanThrowError("Callback is required and must be a Function.");
}
SetBaton* baton = new SetBaton;
baton->error_code = GIT_OK;
baton->error = NULL;
baton->buffer = (git_buf *)malloc(sizeof(git_buf ));
// start convert_from_v8 block
const void * from_data;
from_data = Buffer::Data(args[0]->ToObject());
// end convert_from_v8 block
baton->data = from_data;
// start convert_from_v8 block
size_t from_datalen;
from_datalen = (size_t) args[1]->ToNumber()->Value();
// end convert_from_v8 block
baton->datalen = from_datalen;
NanCallback *callback = new NanCallback(Local<Function>::Cast(args[2]));
SetWorker *worker = new SetWorker(baton, callback);
if (!args[0]->IsUndefined() && !args[0]->IsNull())
worker->SaveToPersistent("data", args[0]->ToObject());
if (!args[1]->IsUndefined() && !args[1]->IsNull())
worker->SaveToPersistent("datalen", args[1]->ToObject());
NanAsyncQueueWorker(worker);
NanReturnUndefined();
}
void GitBuf::SetWorker::Execute() {
int result = git_buf_set(
baton->buffer,baton->data,baton->datalen );
baton->error_code = result;
if (result != GIT_OK && giterr_last() != NULL) {
baton->error = git_error_dup(giterr_last());
}
}
void GitBuf::SetWorker::HandleOKCallback() {
TryCatch try_catch;
if (baton->error_code == GIT_OK) {
Handle<v8::Value> to;
// start convert_to_v8 block
if (baton->buffer != NULL) {
// GitBuf baton->buffer
to = GitBuf::New((void *)baton->buffer, false);
}
else {
to = NanNull();
}
// end convert_to_v8 block
Handle<v8::Value> result = to;
Handle<v8::Value> argv[2] = {
NanNull(),
result
};
callback->Call(2, argv);
} else {
if (baton->error) {
Handle<v8::Value> argv[1] = {
NanError(baton->error->message)
};
callback->Call(1, argv);
if (baton->error->message)
free((void *)baton->error->message);
free((void *)baton->error);
} else {
callback->Call(0, NULL);
}
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete baton;
}
NAN_METHOD(GitBuf::Ptr) {
NanScope();
Handle<v8::Value> to;
char *
ptr =
ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue()->ptr;
// start convert_to_v8 block
if (ptr){
to = NanNew<String>(ptr);
}
else {
to = NanNull();
}
// end convert_to_v8 block
NanReturnValue(to);
}
NAN_METHOD(GitBuf::Asize) {
NanScope();
Handle<v8::Value> to;
size_t
asize =
ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue()->asize;
// start convert_to_v8 block
to = NanNew<Number>( asize);
// end convert_to_v8 block
NanReturnValue(to);
}
NAN_METHOD(GitBuf::Size) {
NanScope();
Handle<v8::Value> to;
size_t
size =
ObjectWrap::Unwrap<GitBuf>(args.This())->GetValue()->size;
// start convert_to_v8 block
to = NanNew<Number>( size);
// end convert_to_v8 block
NanReturnValue(to);
}
Persistent<Function> GitBuf::constructor_template;
| 24.313472 | 123 | 0.631113 | [
"object"
] |
3b13f289d84ad26bce4de1300f60c3b913c9f75d | 2,671 | cc | C++ | RecoJets/JetProducers/src/CastorJetIDHelper.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoJets/JetProducers/src/CastorJetIDHelper.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoJets/JetProducers/src/CastorJetIDHelper.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "RecoJets/JetProducers/interface/CastorJetIDHelper.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/CastorReco/interface/CastorTower.h"
#include "DataFormats/HcalRecHit/interface/CastorRecHit.h"
#include "DataFormats/HcalDetId/interface/HcalCastorDetId.h"
#include "TMath.h"
#include <vector>
#include <numeric>
#include <iostream>
reco::helper::CastorJetIDHelper::CastorJetIDHelper() { initValues(); }
void reco::helper::CastorJetIDHelper::initValues() {
emEnergy_ = 0.0;
hadEnergy_ = 0.0;
fem_ = 0.0;
width_ = 0.0;
depth_ = 0.0;
fhot_ = 0.0;
sigmaz_ = 0.0;
nTowers_ = 0;
}
void reco::helper::CastorJetIDHelper::calculate(const edm::Event& event, const reco::BasicJet& jet) {
initValues();
// calculate Castor JetID properties
double zmean = 0.;
double z2mean = 0.;
std::vector<CandidatePtr> ccp = jet.getJetConstituents();
std::vector<CandidatePtr>::const_iterator itParticle;
for (itParticle = ccp.begin(); itParticle != ccp.end(); ++itParticle) {
const CastorTower* castorcand = dynamic_cast<const CastorTower*>(itParticle->get());
emEnergy_ += castorcand->emEnergy();
hadEnergy_ += castorcand->hadEnergy();
depth_ += castorcand->depth() * castorcand->energy();
width_ += pow(phiangle(castorcand->phi() - jet.phi()), 2) * castorcand->energy();
fhot_ += castorcand->fhot() * castorcand->energy();
// loop over rechits
for (edm::RefVector<edm::SortedCollection<CastorRecHit> >::iterator it = castorcand->rechitsBegin();
it != castorcand->rechitsEnd();
it++) {
edm::Ref<edm::SortedCollection<CastorRecHit> > rechit_p = *it;
double Erechit = rechit_p->energy();
HcalCastorDetId id = rechit_p->id();
int module = id.module();
double zrechit = 0;
if (module < 3)
zrechit = -14390 - 24.75 - 49.5 * (module - 1);
if (module > 2)
zrechit = -14390 - 99 - 49.5 - 99 * (module - 3);
zmean += Erechit * zrechit;
z2mean += Erechit * zrechit * zrechit;
} // end loop over rechits
nTowers_++;
}
//cout << "" << endl;
depth_ = depth_ / jet.energy();
width_ = sqrt(width_ / jet.energy());
fhot_ = fhot_ / jet.energy();
fem_ = emEnergy_ / jet.energy();
zmean = zmean / jet.energy();
z2mean = z2mean / jet.energy();
double sigmaz2 = z2mean - zmean * zmean;
if (sigmaz2 > 0)
sigmaz_ = sqrt(sigmaz2);
}
// help function to calculate phi within [-pi,+pi]
double reco::helper::CastorJetIDHelper::phiangle(double testphi) {
double phi = testphi;
while (phi > M_PI)
phi -= (2 * M_PI);
while (phi < -M_PI)
phi += (2 * M_PI);
return phi;
}
| 31.05814 | 104 | 0.651441 | [
"vector"
] |
3b152e4a9b1480c95f48bb44ee16d2e2a0d15672 | 44,114 | hpp | C++ | src/cmr/matrix.hpp | discopt/cmr | 669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09 | [
"MIT"
] | 4 | 2015-04-13T12:48:09.000Z | 2019-06-26T11:56:31.000Z | src/cmr/matrix.hpp | xammy/unimodularity-test | 669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09 | [
"MIT"
] | 11 | 2021-08-19T09:06:05.000Z | 2021-11-27T23:18:47.000Z | src/cmr/matrix.hpp | discopt/cmr | 669811a8c8cbaa12dabd2a1242f0c0ff1aea6e09 | [
"MIT"
] | null | null | null | #pragma once
#include <cmr/config.h>
#include <cmr/export.h>
#include <boost/numeric/ublas/matrix.hpp>
#include "matrix_transposed.hpp"
#include <iomanip>
namespace tu
{
namespace detail
{
template <typename Iterator>
class Range
{
public:
Range(Iterator begin, Iterator end)
: _begin(begin), _end(end)
{
}
Range(const Range<Iterator>& other)
: _begin(other._begin), _end(other._end)
{
}
Iterator begin()
{
return _begin;
}
Iterator end()
{
return _end;
}
private:
Iterator _begin;
Iterator _end;
};
} /* namespace tu::detail */
/**
* \brief Base class for matrices whose entries have type \p V.
*/
template <typename V>
class Matrix
{
public:
typedef V Value; /// Type of entries
typedef std::size_t Index; /// Row/column index type
struct Nonzero
{
Index row;
Index column;
const Value& value;
Nonzero(Index r, Index c, const Value& v)
: row(r), column(c), value(v)
{
}
};
};
/**
* \brief Dense matrix with entries of type \p V.
*/
template <typename V>
class DenseMatrix : public Matrix<V>
{
public:
typedef typename Matrix<V>::Value Value;
typedef typename Matrix<V>::Index Index;
typedef typename Matrix<V>::Nonzero Nonzero;
template <bool Row>
class NonzeroIterator
{
public:
NonzeroIterator(const DenseMatrix<V>& matrix, Index major)
: _matrix(matrix), _major(major), _minor(0)
{
if (Row)
{
while (_minor < _matrix.numColumns() && _matrix.get(_major, _minor) == 0)
++_minor;
}
else
{
while (_minor < _matrix.numRows() && _matrix.get(_minor, _major) == 0)
++_minor;
}
}
NonzeroIterator(const DenseMatrix<V>& matrix, Index major, int dummy)
: _matrix(matrix), _major(major)
{
if (Row)
_minor = _matrix.numColumns();
else
_minor = _matrix.numRows();
}
NonzeroIterator<Row>& operator++()
{
++_minor;
if (Row)
{
while (_minor < _matrix.numColumns() && _matrix.get(_major, _minor) == 0)
++_minor;
}
else
{
while (_minor < _matrix.numRows() && _matrix.get(_minor, _major) == 0)
++_minor;
}
}
Nonzero operator*() const
{
if (Row)
{
assert(_major < _matrix.numRows());
assert(_minor < _matrix.numColumns());
return Nonzero(_major, _minor, _matrix.get(_major, _minor));
}
else
{
assert(_minor < _matrix.numRows());
assert(_major < _matrix.numColumns());
return Nonzero(_minor, _major, _matrix.get(_minor, _major));
}
}
bool operator!=(const NonzeroIterator<Row>& other) const
{
assert(&_matrix == &other._matrix);
assert(_major == other._major);
return _minor != other._minor;
}
private:
const DenseMatrix<V>& _matrix;
std::size_t _major, _minor;
};
typedef detail::Range<NonzeroIterator<true>> NonzeroRowRange;
typedef detail::Range<NonzeroIterator<false>> NonzeroColumnRange;
/**
* \brief Default constructor for 0x0 matrix.
*/
DenseMatrix()
: _data(nullptr), _numRows(0), _numColumns(0)
{
}
/**
* \brief Move constructor that steals the data from \p other.
*/
DenseMatrix(DenseMatrix<V>&& other)
: _data(other._data), _numRows(other._numRows), _numColumns(other._numColumns)
{
other._data = nullptr;
other._numRows = 0;
other._numColumns = 0;
}
/**
* \brief Copy constructor.
*/
template <typename V2>
DenseMatrix(const DenseMatrix<V2>& other)
: _numRows(other._numRows), _numColumns(other._numColumns)
{
std::size_t size = other._numRows * other._numColumns;
_data = new Value[size];
for (std::size_t i = 0; i < size; ++i)
_data[i] = other._data[i];
}
/**
* \brief Move assignment operator that steals the data from \p other.
*/
DenseMatrix<V>& operator=(DenseMatrix<V>&& other)
{
_data = other._data;
_numRows = other._numRows;
_numColumns = other._numColumns;
other._data = nullptr;
other._numRows = 0;
other._numColumns = 0;
return *this;
}
/**
* \brief Assignment operator.
*/
template <typename V2>
DenseMatrix<V>& operator=(const DenseMatrix<V2>& other)
{
_numRows = other._numRows;
_numColumns = other._numColumns;
std::size_t size = other._numRows * other._numColumns;
_data = new Value[size];
for (std::size_t i = 0; i < size; ++i)
_data[i] = other._data[i];
return *this;
}
/**
* \brief Destructor.
*/
~DenseMatrix()
{
if (_data != nullptr)
delete[] _data;
}
/**
* \brief Constructs zero matrix of given size.
*/
DenseMatrix(Index numRows, Index numColumns)
: _numRows(numRows), _numColumns(numColumns)
{
std::size_t size = numRows * numColumns;
_data = new Value[size];
for (std::size_t i = 0; i < size; ++i)
_data[i] = 0;
}
/**
* \brief Returns the number of rows.
*/
Index numRows() const
{
return _numRows;
}
/**
* \brief Returns the number of columns.
*/
Index numColumns() const
{
return _numColumns;
}
/**
* \brief Returns entry at \p row, \p column.
*/
const Value& get(Index row, Index column) const
{
assert(row < _numRows);
assert(column < _numColumns);
return _data[_numColumns * row + column];
}
/**
* \brief Sets entry at \p row, \p column to copy of \p value.
*/
template <typename V2>
void set(Index row, Index column, const V2& value)
{
assert(row < _numRows);
assert(column < _numColumns);
_data[_numColumns * row + column] = value;
}
/**
* \brief Returns the number of nonzeros in \p row.
*/
std::size_t countRowNonzeros(Index row) const
{
std::size_t begin = _numColumns * row;
std::size_t end = _numColumns * (row + 1);
std::size_t count = 0;
for (std::size_t i = begin; i < end; ++i)
{
if (_data[i] != 0)
++count;
}
return count;
}
/**
* \brief Returns the number of nonzeros in \p column.
*/
std::size_t countColumnNonzeros(Index column) const
{
std::size_t begin = column;
std::size_t end = _numRows * _numColumns;
std::size_t count = 0;
for (std::size_t i = begin; i < end; i += _numColumns)
{
if (_data[i] != 0)
++count;
}
return count;
}
/**
* \brief Returns a range for iterating over the nonzeros of \p row.
*/
NonzeroRowRange iterateRowNonzeros(Index row) const
{
return NonzeroRowRange(NonzeroIterator<true>(*this, row),
NonzeroIterator<true>(*this, row, 0));
}
/**
* \brief Returns a range for iterating over the nonzeros of \p column.
*/
NonzeroColumnRange iterateColumnNonzeros(Index column) const
{
return NonzeroColumnRange(NonzeroIterator<false>(*this, column),
NonzeroIterator<false>(*this, column, 0));
}
/**
* \brief Checks for consistency, raising a \ref std::runtime_error if inconsistent.
*/
void ensureConsistency() const
{
}
protected:
Value* _data; /// Matrix entries with row-major ordering.
Index _numRows; /// Number of rows.
Index _numColumns; /// Number of columns.
};
/**
* \brief Sparse matrix with entries of type \p V.
*/
template<typename V>
class SparseMatrix : public Matrix<V>
{
public:
typedef typename Matrix<V>::Value Value;
typedef typename Matrix<V>::Index Index;
typedef typename Matrix<V>::Nonzero Nonzero;
/**
* \brief Matrix data, row-wise or column-wise.
*
* Matrix data, row-wise or column-wise. The term major refers to the rows if it is a row-wise
* view and to columns otherwise. The term minor refers to the opposite.
*/
struct Data
{
/// Array that maps a major to its nonzero range specified by first and beyond entries.
std::vector<std::pair<Index, Index>> range;
/// Array that maps the nonzero indices to pairs of minor index and value.
std::vector<std::pair<Index, Value>> entries;
/// Whether the data is sorted by minor.
bool isSorted;
/**
* \brief Default constructor.
*/
Data()
: isSorted(true)
{
}
/**
* \brief Move constructor.
*/
Data(Data&& other)
: range(std::move(other.range)), entries(std::move(other.entries)), isSorted(other.isSorted)
{
}
/**
* \brief Copy constructor.
*/
Data(const Data& other)
: range(other.range), entries(other.entries), isSorted(other.isSorted)
{
}
/**
* \brief Move operator.
*/
Data& operator=(Data&& other)
{
range = std::move(other.range);
entries = std::move(other.entries);
isSorted = other.isSorted;
return *this;
}
/**
* \brief Assignment operator.
*/
Data& operator=(const Data& other)
{
range = other.range;
entries = other.entries;
isSorted = other.isSorted;
return *this;
}
/**
* \brief Destructor.
*/
~Data() = default;
/**
* \brief Computes the transpose version of \p data. \p numMinor is the new number of minor
* indices.
*/
void constructFromTransposed(const Data& transposedData, Index numMinor)
{
// Iterate over entries and count how many in each major.
range.resize(numMinor);
for (auto& r : range)
r.second = 0;
for (Index i = 0; i < Index(transposedData.range.size()); ++i)
{
for (Index j = transposedData.range[i].first; j < transposedData.range[i].second; ++j)
{
++range[transposedData.entries[j].first].second;
}
}
// Initialize start of each major. This will be incremented when copying.
range[0].first = 0;
for (Index i = 1; i < Index(range.size()); ++i)
{
range[i].first = range[i-1].first + range[i-1].second;
range[i-1].second = range[i].first;
}
range.back().second = transposedData.entries.size();
// Copy entries major-wise into slots indicated by first[i], incrementing the latter.
entries.resize(transposedData.entries.size());
for (Index transposedMajor = 0; transposedMajor < Index(transposedData.range.size());
++transposedMajor)
{
for (Index j = transposedData.range[transposedMajor].first;
j < transposedData.range[transposedMajor].second; ++j)
{
auto transposedEntry = transposedData.entries[j];
entries[range[transposedEntry.first].first] = std::make_pair(transposedMajor,
transposedEntry.second);
++range[transposedEntry.first].first;
}
}
// Re-initialize start of each major.
range[0].first = 0;
for (Index i = 1; i < Index(range.size()); ++i)
range[i].first = range[i-1].second;
isSorted = true;
}
/**
* \brief Checks for consistency, raising a \ref std::runtime_error if inconsistent.
*/
void ensureConsistency(Index numMinor = std::numeric_limits<Index>::max()) const
{
for (Index i = 0; i < Index(range.size()); ++i)
{
if (range[i].first > entries.size())
throw std::runtime_error(
"Inconsistent SparseMatrix::Data: range.first contains index out of range.");
if (range[i].second > entries.size())
throw std::runtime_error(
"Inconsistent SparseMatrix::Data: range.second contains index out of range.");
if (range[i].first > range[i].second)
throw std::runtime_error(
"Inconsistent SparseMatrix::Data: range.first > range.beyond.");
}
for (Index i = 0; i < Index(entries.size()); ++i)
{
if (entries[i].first >= numMinor)
throw std::runtime_error("Inconsistent SparseMatrix::Data: minor entry exceeds bound.");
if (entries[i].second == 0)
throw std::runtime_error("Inconsistent SparseMatrix::Data: zero entry found.");
}
for (Index i = 0; i < Index(range.size()); ++i)
{
for (Index j = range[i].first + 1; j < range[i].second; ++j)
{
if (entries[j-1].first == entries[j].first)
{
std::stringstream ss;
ss << "Inconsistent SparseMatrix::Data: minor entries of major " << i
<< " contain duplicate indices " << (j-1) << "->" << entries[j-1].first << " and "
<< j << "->" << entries[j].first << ".";
throw std::runtime_error(ss.str());
}
else if (entries[j-1].first > entries[j].first && isSorted)
{
std::stringstream ss;
ss << "Inconsistent SparseMatrix::Data: minor entries of major " << i
<< " are not sorted for indices " << (j-1) << "->" << entries[j-1].first << " and "
<< j << "->" << entries[j].first << ".";
throw std::runtime_error(ss.str());
}
}
}
}
/**
* \brief Swaps data with \p other.
*/
void swap(Data& other)
{
range.swap(other.range);
entries.swap(other.entries);
std::swap(isSorted, other.isSorted);
}
/**
* \brief Finds entry \p major,\p minor.
*
* Find entry \p major,\p minor. If it exists, the index of the entry is returned, and
* \c std::numeric_limits<std::size_t>::max() otherwise.
*/
std::size_t find(Index major, Index minor) const
{
if (isSorted)
{
// Binary search on interval [lower, upper)
std::size_t lower = range[major].first;
std::size_t upper = range[major].second;
std::size_t mid;
while (lower < upper)
{
mid = (lower + upper) / 2;
if (entries[mid].first < minor)
lower = mid + 1;
else if (entries[mid].first > minor)
upper = mid;
else
return mid;
}
}
else
{
// Linear scan.
for (std::size_t i = range[major].first; i < range[major].second; ++i)
{
if (entries[i].first == minor)
return i;
}
}
return std::numeric_limits<std::size_t>::max();
}
/**
* \brief Sort data by minor.
*/
void sort()
{
if (!isSorted)
return;
for (std::size_t i = 0; i < entries.size(); ++i)
{
auto compare = [] (const std::pair<Index, Value>& a,
const std::pair<Index, Value>& b)
{
return a.first < b.first;
};
std::sort(entries.begin() + range[i].first, entries.begin() + range[i].second, compare);
}
isSorted = true;
}
};
/**
* \brief Iterator for row- or column-wise iteration over the entries.
*/
template <bool Row>
struct NonzeroIterator
{
public:
NonzeroIterator(const SparseMatrix<V>& matrix, Index major)
: _data(Row ? matrix._rowData : matrix._columnData), _major(major),
_index(_data.range[major].first)
{
}
NonzeroIterator(const SparseMatrix<V>& matrix, Index major, int dummy)
: _data(Row ? matrix._rowData : matrix._columnData), _major(major),
_index(_data.range[major].second)
{
}
/**
* \brief Copy constructor.
*/
NonzeroIterator(const NonzeroIterator& other)
: _data(other._data), _major(other._major), _index(other._index)
{
}
/**
* \brief Returns the current entry.
*/
inline const Nonzero operator*() const
{
// Statically known, so one branch will be optimized away.
if (Row)
return Nonzero(_major, _data.entries[_index].first, _data.entries[_index].second);
else
return Nonzero(_data.entries[_index].first, _major, _data.entries[_index].second);
}
/**
* \brief Advances to the next entry in the same major.
*/
inline void operator++()
{
++_index;
assert(_index <= _data.range[_major].second);
}
/**
* \brief Compares two iterators for being not equal.
*/
inline bool operator!=(const NonzeroIterator<Row>& other) const
{
assert(&_data == &other._data);
return _major != other._major || _index != other._index;
}
private:
/// Reference to the matrix data.
const Data& _data;
/// Major index.
Index _major;
/// Index of the entry relative to this major.
Value _index;
};
typedef detail::Range<NonzeroIterator<true>> NonzeroRowRange;
typedef detail::Range<NonzeroIterator<false>> NonzeroColumnRange;
/**
* \brief Constructs a 0x0 matrix.
*/
SparseMatrix()
: _zero(0)
{
}
/**
* \brief Move constructor.
*/
SparseMatrix(SparseMatrix&& other)
: _rowData(std::move(other._rowData)), _columnData(std::move(other._columnData)), _zero(0)
{
}
/**
* \brief Move assignment operator.
*/
SparseMatrix& operator=(SparseMatrix&& other)
{
_rowData = std::move(other._rowData);
_columnData = std::move(other._columnData);
return *this;
}
/**
* \brief Constructs a matrix.
*
* Constructs a matrix. Given entries may contain zeros, but they are filtered.
*
* \param majorRow Indicates if data is row-wise.
* \param numMajor Number of rows (resp. columns) of the matrix.
* \param numMinor Number of columns (resp. rows) of the matrix.
* \param numEntries Number of provided entries.
* \param first Array of size \p numMajor with first index of each row (resp. column).
* \param beyond Array of size \p numMajor with beyond index of each row (resp. column).
* May be \c NULL in which case the first-entry of the next major is considered, i.e.,
* the rows (resp. columns) need to be given in an ordered way.
* \param entryMinors Array of size \p numEntries with column (resp. row) of each entry.
* \param entryValues Array of size \p numEntries with value of each entry.
* \param mayContainZeros Whether we have to check for zero entries.
* \param isSorted Whether the entries of each row (resp. column) are already sorted.
*/
SparseMatrix(bool majorRow, Index numMajor, Index numMinor, Index numEntries, Index* first,
Index* beyond, Index* entryMinors, Value* entryValues, bool mayContainZeros = true,
bool isSorted = false)
: _zero(0)
{
set(majorRow, numMajor, numMinor, numEntries, first, beyond, entryMinors, entryValues,
mayContainZeros, isSorted);
}
/**
* \brief Constructs a matrix.
*
* Constructs a matrix from a prepared data structure.
*
* \param majorRow Indicates if data is row-wise.
* \param majorIsSorted Whether the data of each major is sorted by minor.
* \param data Matrix data.
*/
SparseMatrix(bool majorRow, const Data& data, Index numMinor, bool majorIsSorted = false)
: _zero(0)
{
set(majorRow, data, numMinor, majorIsSorted);
}
/**
* \brief Constructs a matrix.
*
* Constructs a matrix from a prepared data structure.
*
* \param majorRow Indicates if data is row-wise.
* \param data Matrix data.
*/
SparseMatrix(bool majorRow, Data&& data, Index numMinor)
: _zero(0)
{
set(majorRow, data, numMinor);
}
/**
* \brief Constructs a matrix.
*
* Constructs a matrix from two prepared data structures.
*
* \param rowData Matrix row data.
* \param columnData Matrix column data.
*/
SparseMatrix(const Data& rowData, const Data& columnData)
: _zero(0)
{
set(rowData, columnData);
}
/**
* \brief Constructs a matrix.
*
* Constructs a matrix from a two prepared data structures.
*
* \param rowData Matrix row data.
* \param columnData Matrix column data.
*/
SparseMatrix(Data&& rowData, Data&& columnData)
: _zero(0)
{
set(std::move(rowData), std::move(columnData));
}
/**
* \brief Sets the contents of the matrix.
*
* Sets the contents of the matrix. Given entries may contain zeros, but they are filtered.
*
* \param majorRow Indicates if data is row-wise.
* \param numMajor Number of rows (resp. columns) of the matrix.
* \param numMinor Number of columns (resp. rows) of the matrix.
* \param numEntries Number of provided entries.
* \param first Array of size \p numMajor with first index of each row (resp. column).
* \param beyond Array of size \p numMajor with beyond index of each row (resp. column).
* May be \c nullptr in which case the first-entry of the next major is considered, i.e.,
* the rows (resp. columns) need to be ordered.
* \param entryMinors Array of size \p numEntries with column (resp. row) of each entry.
* \param entryValues Array of size \p numEntries with value of each entry.
* \param mayContainZeros Whether zero entries shall be skipped.
* \param isSorted Whether the entries of each major are sorted by minor.
*/
void set(bool majorRow, Index numMajor, Index numMinor, Index numEntries, const Index* first,
const Index* beyond, const Index* entryMinors, const Value* entryValues,
bool mayContainZeros = true, bool isSorted = false)
{
if (mayContainZeros)
{
// Use first run over entries to count nonzeros in each row (resp. column).
_rowData.range.resize(numMajor);
for (auto& range : _rowData.range)
range.first = 0;
Index current = 0;
for (Index i = 0; i < numMajor; ++i)
{
_rowData.range[i].first = current;
Index b;
if (beyond != nullptr)
b = beyond[i];
else if (i + 1 < numMajor)
b = first[i+1];
else
b = numEntries;
for (Index j = first[i]; j < b; ++j)
{
if (entryValues[j] != 0)
++current;
}
_rowData.range[i].second = current;
}
// Use second run to copy the nonzeros.
_rowData.entries.resize(current);
current = 0;
for (Index i = 0; i < numMajor; ++i)
{
Index b;
if (beyond != nullptr)
b = beyond[i];
else if (i + 1 < numMajor)
b = first[i+1];
else
b = numEntries;
for (Index j = first[i]; j < b; ++j)
{
if (entryValues[j] != 0)
{
_rowData.entries[current] = std::make_pair(entryMinors[j], entryValues[j]);
++current;
}
}
}
}
else
{
// If we can trust the input then we can copy directly.
_rowData.range.resize(numMajor);
if (beyond != nullptr)
{
for (Index i = 0; i < numMajor; ++i)
_rowData.range[i] = std::make_pair(first[i], beyond[i]);
}
else
{
for (Index i = 0; i + 1 < numMajor; ++i)
_rowData.range[i] = std::make_pair(first[i], first[i+1]);
_rowData.range.back() = std::make_pair(first[numMajor - 1], Index(numEntries));
}
_rowData.entries.resize(numEntries);
for (Index i = 0; i < numEntries; ++i)
_rowData.entries[i] = std::make_pair(entryMinors[i], entryValues[i]);
}
_rowData.isSorted = isSorted;
// Construct column-wise (resp. row-wise) representation.
_columnData.constructFromTransposed(_rowData, numMinor);
if (!majorRow)
_rowData.swap(_columnData);
#if !defined(NDEBUG)
ensureConsistency();
#endif /* !NDEBUG */
}
/**
* \brief Sets the contents of the matrix.
*
* Sets the contents of the matrix from a prepared data structure.
*
* \param majorRow Indicates if data is row-wise.
* \param data Matrix data.
* \param numMinor Number of columns (resp. rows).
*/
void set(bool majorRow, const Data& data, Index numMinor)
{
// We can trust the input and thus we can copy directly.
_rowData.range = data.range;
_rowData.entries = data.entries;
_rowData.isSorted = data.isSorted;
// Construct column-wise (resp. row-wise) representation.
_columnData.constructFromTransposed(_rowData, numMinor);
if (!majorRow)
_rowData.swap(_columnData);
#if !defined(NDEBUG)
ensureConsistency();
#endif /* !NDEBUG */
}
/**
* \brief Sets the contents of the matrix.
*
* Sets the contents of the matrix from a prepared data structure.
*
* \param majorRow Indicates if data is row-wise.
* \param data Matrix data.
* \param numMinor Number of columns (resp. rows).
*/
void set(bool majorRow, Data&& data, Index numMinor)
{
_rowData = std::move(data);
_columnData.constructFromTransposed(_rowData, numMinor);
if (!majorRow)
_rowData.swap(_columnData);
#if !defined(NDEBUG)
ensureConsistency();
#endif /* !NDEBUG */
}
/**
* \brief Sets the contents of the matrix.
*
* Sets the contents of the matrix from a prepared data structure.
*
* \param rowData Matrix row data.
* \param columnData Matrix column data.
*/
void set(const Data& rowData, const Data& columnData)
{
_rowData.range = rowData.range;
_rowData.entries = rowData.entries;
_rowData.isSorted = rowData.isSorted;
_rowData.ensureConsistency();
_columnData.range = columnData.range;
_columnData.entries = columnData.entries;
_columnData.isSorted = columnData.isSorted;
_columnData.ensureConsistency();
#if !defined(NDEBUG)
ensureConsistency();
#endif /* !NDEBUG */
}
/**
* \brief Sets the contents of the matrix.
*
* Sets the contents of the matrix from a prepared data structure.
*
* \param rowData Matrix row data.
* \param columnData Matrix column data.
*/
void set(Data&& rowData, Data&& columnData)
{
_rowData = std::move(rowData);
_columnData = std::move(columnData);
#if !defined(NDEBUG)
ensureConsistency();
#endif /* !NDEBUG */
}
/**
* \brief Destructor.
*/
~SparseMatrix() = default;
/**
* \brief Returns the number of rows.
*/
std::size_t numRows() const
{
return _rowData.range.size();
}
/**
* \brief Returns the number of columns.
*/
std::size_t numColumns() const
{
return _columnData.range.size();
}
/**
* \brief Indicates if the row data is sorted by column.
*/
bool hasSortedRows() const
{
return _rowData.isSorted;
}
/**
* \brief Indicates if the column data is sorted by row.
*/
bool hasSortedColumns() const
{
return _columnData.isSorted;
}
/**
* \brief Returns entry at \p row, \p column.
*
* Returns entry at \p row, \p column. If the row or column data is sorted (resp. not sorted)
* then the time is logarithmic (resp. linear) in the number of nonzeros of the row or column.
*/
const Value& get(Index row, Index column) const
{
assert(row < numRows());
assert(column < numColumns());
if (_rowData.isSorted)
{
std::size_t columnIndex = _rowData.find(row, column);
if (columnIndex < std::numeric_limits<std::size_t>::max())
return _rowData.entries[columnIndex].second;
}
else
{
std::size_t rowIndex = _columnData.find(column, row);
if (rowIndex < std::numeric_limits<std::size_t>::max())
return _columnData.entries[rowIndex].second;
}
return _zero;
}
/**
* \brief Returns the number of nonzeros.
*/
std::size_t numNonzeros() const
{
return _rowData.entries.size();
}
/**
* \brief Returns the number of nonzeros in \p row.
*/
std::size_t countRowNonzeros(Index row) const
{
return _rowData.range[row].second - _rowData.range[row].first;
}
/**
* \brief Returns the number of nonzeros in \p column.
*/
std::size_t countColumnNonzeros(Index column) const
{
return _columnData.range[column].second - _columnData.range[column].first;
}
/**
* \brief Returns a range for iterating over the nonzeros of \p row.
*/
NonzeroRowRange iterateRowNonzeros(Index row) const
{
return NonzeroRowRange(NonzeroIterator<true>(*this, row),
NonzeroIterator<true>(*this, row, 0));
}
/**
* \brief Returns a range for iterating over the nonzeros of \p column.
*/
NonzeroColumnRange iterateColumnNonzeros(Index column) const
{
return NonzeroColumnRange(NonzeroIterator<false>(*this, column),
NonzeroIterator<false>(*this, column, 0));
}
/**
* \brief Returns a copy of the matrix' transpose.
*/
SparseMatrix transposed() const
{
return SparseMatrix(_columnData, _rowData);
}
/**
* \brief Checks for consistency, raising a \ref std::runtime_error if inconsistent.
*
* Checks for consistency of row- and column-data, which includes that all entries must be
* nonzeros and that entries are sorted and free of duplicates (if stated so).
*/
void ensureConsistency() const
{
// First ensure individual consistency of row and column data.
_rowData.ensureConsistency();
_columnData.ensureConsistency();
// Copy of a nonzero.
struct NZ
{
Index row;
Index column;
Value value;
};
// Comparison for entries.
auto compare = [](const NZ& a, const NZ& b)
{
if (a.row != b.row)
return a.row < b.row;
if (a.column != b.column)
return a.column < b.column;
return a.value < b.value;
};
// Construct sorted vector of entries from row data.
std::vector<NZ> rowNonzeros;
for (Index i = 0; i < Index(_rowData.range.size()); ++i)
{
for (Index j = _rowData.range[i].first; j < _rowData.range[i].second; ++j)
{
NZ nz = { i, _rowData.entries[j].first, _rowData.entries[j].second };
rowNonzeros.push_back(nz);
}
}
std::sort(rowNonzeros.begin(), rowNonzeros.end(), compare);
// Construct sorted vector of entries from column data.
std::vector<NZ> columnNonzeros;
for (Index i = 0; i < Index(_columnData.range.size()); ++i)
{
for (Index j = _columnData.range[i].first; j < _columnData.range[i].second; ++j)
{
NZ nz = { _columnData.entries[j].first, i, _columnData.entries[j].second };
columnNonzeros.push_back(nz);
}
}
std::sort(columnNonzeros.begin(), columnNonzeros.end(), compare);
for (std::size_t i = 0; i < rowNonzeros.size(); ++i)
{
if (rowNonzeros[i].row != columnNonzeros[i].row
|| rowNonzeros[i].column != columnNonzeros[i].column
|| rowNonzeros[i].value != columnNonzeros[i].value)
{
throw std::runtime_error("Inconsistent Matrix: row and column data differ.");
}
}
}
/**
* \brief Transposes the matrix.
*
* Transposes the matrix in constant time.
*/
void transpose()
{
_rowData.swap(_columnData);
}
/**
* \brief Sort row data (by column).
*/
void sortRows()
{
_rowData.sort();
}
/**
* \brief Sort column data (by row).
*/
void sortColumns()
{
_columnData.sort();
}
/**
* \brief Sort row and column data (by column and row, respectively).
*/
void sort()
{
sortRows();
sortColumns();
}
private:
/// Data for row-wise access.
Data _rowData;
/// Data for column-wise access.
Data _columnData;
/// Zero value.
Value _zero;
/// Whether the row and column data is sorted (by columns and rows, respectively).
bool _isSorted;
};
/**
* \brief Matrix proxy for the transpose of a matrix.
*
* Matrix proxy for the transpose of a matrix. It references another matrix and does not maintain
* matrix data by itself.
*/
template <typename M>
class TransposedMatrix : public Matrix<typename M::Value>
{
public:
typedef typename M::Value Value;
typedef typename M::Index Index;
typedef typename M::Nonzero Nonzero;
template <bool Row>
class NonzeroIterator
{
public:
NonzeroIterator(const TransposedMatrix<M>& matrix, Index major)
: _matrix(matrix._matrix), _iterator(typename M::template NonzeroIterator<!Row>(matrix._matrix, major))
{
}
NonzeroIterator(const TransposedMatrix<M>& matrix, Index major, int dummy)
: _matrix(matrix._matrix), _iterator(typename M::template NonzeroIterator<!Row>(matrix._matrix, major, 0))
{
}
NonzeroIterator<Row>& operator++()
{
++_iterator;
}
Nonzero operator*() const
{
Nonzero nz = *_iterator;
std::swap(nz.row, nz.column);
return nz;
}
bool operator!=(const NonzeroIterator<Row>& other) const
{
assert(&_matrix == &other._matrix);
return _iterator != other._iterator;
}
private:
const M& _matrix;
typename M::template NonzeroIterator<!Row> _iterator;
};
typedef detail::Range<NonzeroIterator<true>> NonzeroRowRange;
typedef detail::Range<NonzeroIterator<false>> NonzeroColumnRange;
/**
* \brief Constructs from a matrix of type \p M.
*/
TransposedMatrix(M& matrix)
: _matrix(matrix)
{
}
/**
* \brief Move constructor.
*/
TransposedMatrix(TransposedMatrix&& other)
: _matrix(other._matrix)
{
}
/**
* \brief Returns the number of rows.
*/
std::size_t numRows() const
{
return _matrix.numColumns();
}
/**
* \brief Returns the number of columns.
*/
std::size_t numColumns() const
{
return _matrix.numRows();
}
/**
* \brief Indicates if the row data is sorted by column.
*/
bool hasSortedRows() const
{
return _matrix.hasSortedColumns();
}
/**
* \brief Indicates if the column data is sorted by row.
*/
bool hasSortedColumns() const
{
return _matrix.hasSortedRows();
}
/**
* \brief Returns entry at \p row, \p column.
*
* Returns entry at \p row, \p column. If the row or column data is sorted (resp. not sorted)
* then the time is logarithmic (resp. linear) in the number of nonzeros of the row or column.
*/
const Value& get(Index row, Index column) const
{
assert(row < numRows());
assert(column < numColumns());
return _matrix.get(column, row);
}
/**
* \brief Returns the number of nonzeros.
*/
std::size_t numNonzeros() const
{
return _matrix.numNonzeros();
}
/**
* \brief Returns the number of nonzeros in \p row.
*/
std::size_t countRowNonzeros(Index row) const
{
return _matrix.countColumnNonzeros(row);
}
/**
* \brief Returns the number of nonzeros in \p column.
*/
std::size_t countColumnNonzeros(Index column) const
{
return _matrix.countRowNonzeros(column);
}
/**
* \brief Returns a range for iterating over the nonzeros of \p row.
*/
NonzeroRowRange iterateRowNonzeros(Index row) const
{
return NonzeroRowRange(NonzeroIterator<true>(_matrix, row),
NonzeroIterator<true>(_matrix, row, 0));
}
/**
* \brief Returns a range for iterating over the nonzeros of \p column.
*/
NonzeroColumnRange iterateColumnNonzeros(Index column) const
{
return NonzeroColumnRange(NonzeroIterator<false>(_matrix, column),
NonzeroIterator<false>(_matrix, column, 0));
}
/**
* \brief Checks for consistency, raising a \ref std::runtime_error if inconsistent.
*/
void ensureConsistency() const
{
_matrix.ensureConsistency();
}
protected:
M& _matrix;
};
/**
* \brief Returns a \ref TransposedMatrix for \p matrix.
*/
template <typename M>
TransposedMatrix<M> transposedMatrix(M& matrix)
{
return TransposedMatrix<M>(matrix);
}
/**
* \brief Indexes a submatrix.
*/
class SubmatrixIndices
{
public:
/**
* \brief Copy constructor.
*/
CMR_EXPORT
SubmatrixIndices(const SubmatrixIndices& other);
/**
* \brief Move constructor.
*/
CMR_EXPORT
SubmatrixIndices(SubmatrixIndices&& other);
/**
* \brief Constructor from arrays \p rows and \p columns.
*/
CMR_EXPORT
SubmatrixIndices(const std::vector<std::size_t>& rows, const std::vector<std::size_t>& columns);
/**
* \brief Constructor for a 1x1 submatrix.
*
* Constructor for a 1x1 submatrix.
*/
CMR_EXPORT
SubmatrixIndices(std::size_t row, std::size_t column);
/**
* \brief Returns the number of row indices.
*/
inline
std::size_t numRows() const
{
return _rows.size();
}
/**
* \brief Returns the number of column indices.
*/
inline
std::size_t numColumns() const
{
return _columns.size();
}
/**
* \brief Returns the vector of row indices.
*/
inline
const std::vector<std::size_t>& rows() const
{
return _rows;
}
/**
* \brief Returns the vector of column indices.
*/
inline
const std::vector<std::size_t>& columns() const
{
return _columns;
}
private:
/// Array of row indices.
std::vector<std::size_t> _rows;
/// Array of column indices.
std::vector<std::size_t> _columns;
};
template <typename M>
class Submatrix : public Matrix<typename M::Value>
{
public:
typedef typename M::Index Index;
typedef typename M::Value Value;
typedef typename M::Nonzero Nonzero;
/**
* \brief Constructs submatrix of \p matrix indexed by \p indices.
*/
Submatrix(const M& matrix, const SubmatrixIndices& indices)
: _matrix(matrix), _indices(indices)
{
}
/**
* \brief Move constructor.
*/
Submatrix(Submatrix && other)
: _matrix(other._matrix), _indices(other._indices)
{
}
/**
* \brief Returns the number of rows.
*/
std::size_t numRows() const
{
return _indices.numRows();
}
/**
* \brief Returns the number of columns.
*/
std::size_t numColumns() const
{
return _indices.numColumns();
}
/**
* \brief Indicates if the row data is sorted by column.
*/
bool hasSortedRows() const
{
return false;
}
/**
* \brief Indicates if the column data is sorted by row.
*/
bool hasSortedColumns() const
{
return false;
}
/**
* \brief Returns entry at \p row, \p column.
*
* Returns entry at \p row, \p column. If the row or column data is sorted (resp. not sorted)
* then the time is logarithmic (resp. linear) in the number of nonzeros of the row or column.
*/
const Value& get(Index row, Index column) const
{
assert(row < numRows());
assert(column < numColumns());
return _matrix.get(_indices.rows()[row], _indices.columns()[column]);
}
/**
* \brief Checks for consistency, raising a \ref std::runtime_error if inconsistent.
*/
void ensureConsistency() const
{
for (auto row : _indices.rows())
{
if (row >= _matrix.numRows())
throw std::runtime_error("Inconsistent Submatrix: row index too large.");
}
for (auto column : _indices.columns())
{
if (column >= _matrix.numColumns())
throw std::runtime_error("Inconsistent Submatrix: column index too large.");
}
_matrix.ensureConsistency();
}
private:
const M& _matrix;
const SubmatrixIndices& _indices;
};
template <typename Matrix>
bool find_smallest_nonzero_matrix_entry(const Matrix& matrix, size_t row_first, size_t row_beyond, size_t column_first, size_t column_beyond,
size_t& row, size_t& column)
{
bool result = false;
int current_value = 0;
for (size_t r = row_first; r != row_beyond; ++r)
{
for (size_t c = column_first; c != column_beyond; ++c)
{
int value = matrix(r, c);
if (value == 0)
continue;
value = value >= 0 ? value : -value;
if (!result || value < current_value)
{
result = true;
row = r;
column = c;
current_value = value;
}
}
}
return result;
}
template <typename Matrix>
bool matrix_row_zero(const Matrix& matrix, size_t row, size_t column_first, size_t column_beyond)
{
for (size_t c = column_first; c != column_beyond; ++c)
if (matrix(row, c) != 0)
return false;
return true;
}
template <typename Matrix>
bool matrix_column_zero(const Matrix& matrix, size_t column, size_t row_first, size_t row_beyond)
{
return matrix_row_zero(make_transposed_matrix(matrix), column, row_first, row_beyond);
}
template <typename Matrix1, typename Matrix2>
bool equals(const Matrix1& first, const Matrix2& second)
{
if (first.size1() != second.size1())
return false;
if (first.size2() != second.size2())
return false;
for (size_t r = 0; r < first.size1(); ++r)
{
for (size_t c = 0; c < first.size2(); ++c)
{
if (first(r, c) != second(r, c))
return false;
}
}
return true;
}
/**
* Free function to permute two rows of a permuted matrix.
*
* @param matrix The permuted matrix
* @param index1 First index
* @param index2 Second index
*/
template <typename MatrixType>
inline void matrix_permute1(MatrixType& matrix, size_t index1, size_t index2)
{
for (size_t index = 0; index < matrix.size2(); ++index)
{
std::swap(matrix(index1, index), matrix(index2, index));
}
}
/**
* Free function to permute two columns of a permuted matrix.
*
* @param matrix The permuted matrix
* @param index1 First index
* @param index2 Second index
*/
template <typename MatrixType>
inline void matrix_permute2(MatrixType& matrix, size_t index1, size_t index2)
{
for (size_t index = 0; index < matrix.size1(); ++index)
{
std::swap(matrix(index, index1), matrix(index, index2));
}
}
} /* namespace tu */
| 25.236842 | 143 | 0.57399 | [
"vector"
] |
3b17860f03d53676240adec50678b9f924a0b27c | 6,250 | cpp | C++ | mudis/src/strategy_redis_sentinel.cpp | lyramilk/mudis | 7e9243bcc8d70b7cc464614558af08c8a81b1b13 | [
"Apache-2.0"
] | null | null | null | mudis/src/strategy_redis_sentinel.cpp | lyramilk/mudis | 7e9243bcc8d70b7cc464614558af08c8a81b1b13 | [
"Apache-2.0"
] | null | null | null | mudis/src/strategy_redis_sentinel.cpp | lyramilk/mudis | 7e9243bcc8d70b7cc464614558af08c8a81b1b13 | [
"Apache-2.0"
] | null | null | null | #include "strategy.h"
#include "redis_proxy.h"
#include <libmilk/dict.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
/*
#include <sys/epoll.h>
#include <sys/poll.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <cassert>
#include <netdb.h>
#include <sys/ioctl.h>
SENTINEL get-master-addr-by-name feedvideo2_master
*/
namespace lyramilk{ namespace mudis { namespace strategy
{
class redis_sentinel:public redis_proxy_strategy
{
redis_upstream_server* rinfo;
lyramilk::netio::aioproxysession_connector* endpoint;
bool is_ssdb;
public:
redis_sentinel(redis_upstream_server* ri,lyramilk::netio::aioproxysession_connector* endpoint,bool is_ssdb)
{
rinfo = ri;
rinfo->add_ref();
this->endpoint = endpoint;
this->is_ssdb = is_ssdb;
}
virtual ~redis_sentinel()
{
rinfo->release();
}
virtual bool onauth(lyramilk::data::ostream& os,redis_proxy* proxy)
{
if(proxy->async_redirect_to(endpoint)){
if(is_ssdb){
os << "2\nok\n1\n1\n\n";
}else{
os << "+OK\r\n";
}
return true;
}
return false;
}
virtual bool onrequest(const char* cache,int size,int* bytesused,lyramilk::data::ostream& os)
{
TODO();
return false;
}
};
class redis_sentinel_master:public redis_strategy
{
lyramilk::threading::mutex_rw lock;
std::vector<redis_upstream> upstreams;
std::vector<redis_upstream*> activelist;
std::vector<redis_sentinel_info> redis_sentinel_list;
public:
redis_sentinel_master()
{
}
virtual ~redis_sentinel_master()
{
}
static redis_strategy* ctr(void*)
{
return new redis_sentinel_master;
}
static void dtr(redis_strategy* p)
{
delete (redis_sentinel_master*)p;
}
virtual bool load_config(const lyramilk::data::string& groupname,const lyramilk::data::array& upstreams)
{
redis_sentinel_list.clear();
for(lyramilk::data::array::const_iterator it = upstreams.begin();it != upstreams.end();++it){
if(it->type() != lyramilk::data::var::t_map) return false;
lyramilk::data::map sm = *it;
redis_sentinel_info rsi;
rsi.host = sm["host"].str();
rsi.port = sm["port"];
rsi.password = sm["password"].str();
rsi.name = sm["name"].str();
rsi.auth = sm["auth"].str();
redis_sentinel_list.push_back(rsi);
}
redis_upstream_server* srv = redis_strategy_master::instance()->add_redis_server(groupname);
if(srv){
srv->nocheck = true;
this->upstreams.push_back(redis_upstream(srv,1));
srv->group.push_back(this);
}
return true;
}
virtual bool check_redis_sentinel(redis_upstream* ups)
{
for(std::vector<redis_sentinel_info>::iterator it = redis_sentinel_list.begin();it!=redis_sentinel_list.end();++it){
lyramilk::netio::client c;
if(c.open(it->host,it->port)){
if(it->password.empty()){
}else{
lyramilk::data::array cmd;
cmd.push_back("auth");
cmd.push_back(it->password);
bool err = false;
lyramilk::data::var r = redis_session::exec_redis(c,cmd,&err);
if(r != "OK"){
lyramilk::klog(lyramilk::log::error,"mudis.redis_upstream_server_with_redis_sentinel.check") << lyramilk::kdict("登录哨兵失败:%p:%d:%s %s",it->host.c_str(),it->port,it->password.c_str(),strerror(errno)) << std::endl;
return false;
}
}
lyramilk::data::array cmd;
cmd.push_back("sentinel");
cmd.push_back("get-master-addr-by-name");
cmd.push_back(it->name);
bool err = false;
lyramilk::data::var r = redis_session::exec_redis(c,cmd,&err);
if(r.type() == lyramilk::data::var::t_array){
lyramilk::data::array& ar = r;
if(ar.size() == 2){
lyramilk::data::string host = ar[0].str();
unsigned short port = ar[1];
hostent* h = gethostbyname(host.c_str());
if(h == nullptr){
lyramilk::klog(lyramilk::log::error,"mudis.redis_upstream_server_with_redis_sentinel.check") << lyramilk::kdict("获取%s的IP地址失败:%p,%s",host.c_str(),h,strerror(errno)) << std::endl;
return false;
}
in_addr* inaddr = (in_addr*)h->h_addr;
if(inaddr == nullptr){
lyramilk::klog(lyramilk::log::error,"mudis.redis_upstream_server_with_redis_sentinel.check") << lyramilk::kdict("获取%s的IP地址失败:%p,%s",host.c_str(),inaddr,strerror(errno)) << std::endl;
return false;
}
lyramilk::threading::mutex_sync _(lock.w());
memset(&ups->srv->saddr,0,sizeof(ups->srv->saddr));
ups->srv->saddr.sin_addr.s_addr = inaddr->s_addr;
ups->srv->saddr.sin_family = AF_INET;
ups->srv->saddr.sin_port = htons(port);
ups->srv->host = host;
ups->srv->port = port;
ups->srv->password = it->auth;
ups->srv->online = true;
return true;
}
}
}
}
return false;
}
virtual void onlistchange()
{
std::vector<redis_upstream*> tmpactivelist;
for(unsigned int idx=0;idx<upstreams.size();++idx){
if(check_redis_sentinel(&upstreams[idx])){
tmpactivelist.push_back(&upstreams[idx]);
break;
}
}
lyramilk::threading::mutex_sync _(lock.w());
activelist.swap(tmpactivelist);
}
virtual void check()
{
onlistchange();
}
virtual redis_proxy_strategy* create(bool is_ssdb,redis_proxy* proxy)
{
lyramilk::threading::mutex_sync _(lock.r());
if(!activelist.empty()){
for(unsigned int i=0;i<activelist.size();++i){
redis_upstream* pupstream = activelist[i];
redis_upstream_server* pserver = pupstream->srv;
if(!pserver->online) continue;
redis_upstream_connector* endpoint = lyramilk::netio::aiosession::__tbuilder<redis_upstream_connector>();
if(connect_upstream(false,endpoint,pserver,proxy)){
return new redis_sentinel(pserver,endpoint,false);
}
//尝试链接失败
endpoint->dtr(endpoint);
pserver->enable(false);
}
}
return nullptr;
}
virtual void destory(redis_proxy_strategy* p)
{
if(p){
redis_sentinel* sp = (redis_sentinel*)p;
delete sp;
}
}
};
static __attribute__ ((constructor)) void __init()
{
redis_strategy_master::instance()->define("redis_sentinel",redis_sentinel_master::ctr,redis_sentinel_master::dtr);
}
}}}
| 25.510204 | 218 | 0.65296 | [
"vector"
] |
3b18b6842429c41354f0b6d3caba35f82fad8792 | 1,008 | cpp | C++ | src/funcs/aim/norecoil/norecoil.cpp | UnkwUsr/hlhax | 0198368ae04c7d353d38e2f74bd30046f5b99944 | [
"MIT"
] | 5 | 2022-02-13T18:46:22.000Z | 2022-03-19T22:23:54.000Z | src/funcs/aim/norecoil/norecoil.cpp | UnkwUsr/hlhax | 0198368ae04c7d353d38e2f74bd30046f5b99944 | [
"MIT"
] | 1 | 2022-03-20T19:54:11.000Z | 2022-03-20T22:14:33.000Z | src/funcs/aim/norecoil/norecoil.cpp | UnkwUsr/hlhax | 0198368ae04c7d353d38e2f74bd30046f5b99944 | [
"MIT"
] | null | null | null | #include "funcs/aim/norecoil/norecoil.h"
#include "globals.h"
#include "utils/cvars/cvars.h"
namespace Cvars {
cvar_t* norecoil;
}
namespace NoRecoil {
DEF_HOOK(CL_CreateMove)
DEF_HOOK(V_CalcRefdef)
Vector recoil_angles;
void Init()
{
ADD_HOOK(CL_CreateMove, gp_Client)
ADD_HOOK(V_CalcRefdef, gp_Client)
Cvars::norecoil = CREATE_CVAR("norecoil", "1");
}
void V_CalcRefdef(struct ref_params_s *pparams) {
if(Cvars::norecoil->value == 0)
return CALL_ORIG(V_CalcRefdef, pparams);
pparams->punchangle[0] = 0;
pparams->punchangle[1] = 0;
pparams->punchangle[2] = 0;
return CALL_ORIG(V_CalcRefdef, pparams);
}
void CL_CreateMove(float frametime, usercmd_t *cmd, int active) {
CALL_ORIG(CL_CreateMove, frametime, cmd, active);
if(Cvars::norecoil->value == 0)
return;
cmd->viewangles = cmd->viewangles - recoil_angles;
}
} // namespace NoRecoil
| 21.446809 | 69 | 0.631944 | [
"vector"
] |
3b2a3769a8250111f1d2656a0d0155162df8c59a | 4,042 | hpp | C++ | include/GlobalNamespace/HMMainThreadDispatcher.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/HMMainThreadDispatcher.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/HMMainThreadDispatcher.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: PersistentSingleton`1
#include "GlobalNamespace/PersistentSingleton_1.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: Queue`1<T>
template<typename T>
class Queue_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// WARNING Size may be invalid!
// Autogenerated type: HMMainThreadDispatcher
class HMMainThreadDispatcher : public GlobalNamespace::PersistentSingleton_1<GlobalNamespace::HMMainThreadDispatcher*> {
public:
// Nested type: GlobalNamespace::HMMainThreadDispatcher::$$c__DisplayClass2_0
class $$c__DisplayClass2_0;
// Nested type: GlobalNamespace::HMMainThreadDispatcher::$ActionCoroutine$d__4
class $ActionCoroutine$d__4;
// Creating value type constructor for type: HMMainThreadDispatcher
HMMainThreadDispatcher() noexcept {}
// Get static field: static private System.Collections.Generic.Queue`1<System.Action> _mainThreadExecutionQueue
static System::Collections::Generic::Queue_1<System::Action*>* _get__mainThreadExecutionQueue();
// Set static field: static private System.Collections.Generic.Queue`1<System.Action> _mainThreadExecutionQueue
static void _set__mainThreadExecutionQueue(System::Collections::Generic::Queue_1<System::Action*>* value);
// protected System.Void Update()
// Offset: 0x122E14C
void Update();
// public System.Void Enqueue(System.Collections.IEnumerator action)
// Offset: 0x122E2B4
void Enqueue(System::Collections::IEnumerator* action);
// public System.Void Enqueue(System.Action action)
// Offset: 0x122E434
void Enqueue(System::Action* action);
// private System.Collections.IEnumerator ActionCoroutine(System.Action action)
// Offset: 0x122E45C
System::Collections::IEnumerator* ActionCoroutine(System::Action* action);
// public System.Void .ctor()
// Offset: 0x122E4F8
// Implemented from: PersistentSingleton`1
// Base method: System.Void PersistentSingleton_1::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static HMMainThreadDispatcher* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::HMMainThreadDispatcher::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<HMMainThreadDispatcher*, creationType>()));
}
// static private System.Void .cctor()
// Offset: 0x122E568
// Implemented from: PersistentSingleton`1
// Base method: System.Void PersistentSingleton_1::.cctor()
// Base method: System.Void Object::.cctor()
static void _cctor();
}; // HMMainThreadDispatcher
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::HMMainThreadDispatcher*, "", "HMMainThreadDispatcher");
| 47 | 123 | 0.723404 | [
"object"
] |
3b36b15a37f716b2a30c2973c5287f1d4de0b3c4 | 3,272 | hpp | C++ | Support/Modules/DGLib/DGPopUp.hpp | graphisoft-python/TextEngine | 20c2ff53877b20fdfe2cd51ce7abdab1ff676a70 | [
"Apache-2.0"
] | 3 | 2019-07-15T10:54:54.000Z | 2020-01-25T08:24:51.000Z | Support/Modules/DGLib/DGPopUp.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | null | null | null | Support/Modules/DGLib/DGPopUp.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | 1 | 2020-09-26T03:17:22.000Z | 2020-09-26T03:17:22.000Z | // *****************************************************************************
// File: DGPopUp.hpp
//
// Description: PopUp classes
//
// Project: GRAPHISOFT Dialog Manager (DGLib)
//
// Namespace: DG
//
// Contact person: AZS, BM
//
// SG compatible
// *****************************************************************************
#ifndef DGPOPUP_HPP
#define DGPOPUP_HPP
#pragma once
// --- Includes ----------------------------------------------------------------
#include "UniString.hpp"
#include "DGItemProperty.hpp"
// --- Predeclarations ---------------------------------------------------------
namespace DG {
class PopUp;
}
// --- Class declarations ------------------------------------------------------
namespace DG {
// --- PopUpChangeEvent --------------------------------------------------------
class DG_DLL_EXPORT PopUpChangeEvent: public ItemChangeEvent
{
friend class PopUpObserver; // To access protected constructor
private:
short previousSelection;
protected:
explicit PopUpChangeEvent (const ItemChangeEvent& ev);
public:
~PopUpChangeEvent ();
PopUp* GetSource (void) const;
short GetPreviousSelection (void) const;
};
// --- PopUpObserver -----------------------------------------------------------
class DG_DLL_EXPORT PopUpObserver: public ItemObserver
{
protected:
virtual short SpecChanged (const ItemChangeEvent& ev) override;
virtual void PopUpChanged (const PopUpChangeEvent& ev);
public:
PopUpObserver ();
~PopUpObserver ();
};
// --- PopUp -------------------------------------------------------------------
class DG_DLL_EXPORT PopUp: public Item,
public ItemFontProperty
{
public:
enum ItemType {
AllItems = DG_ALL_ITEMS,
TopItem = DG_POPUP_TOP,
BottomItem = DG_POPUP_BOTTOM
};
PopUp (const Panel& panel, short item);
PopUp (const Panel& panel, const Rect& rect, short vSize, short textOffset);
~PopUp ();
void Attach (PopUpObserver& observer);
void Detach (PopUpObserver& observer);
void AppendItem (void);
void InsertItem (short popupItem);
void DeleteItem (short popupItem);
short GetItemCount (void) const;
void AppendSeparator (void);
void InsertSeparator (short popupItem);
bool IsSeparator (short popupItem) const;
void SetItemText (short popupItem, const GS::UniString& text);
GS::UniString GetItemText (short popupItem) const;
void SetItemFontStyle (short popupItem, Font::Style style);
Font::Style GetItemFontStyle (short popupItem) const;
void SetItemIcon (short popupItem, const DG::Icon& icon);
DG::Icon GetItemIcon (short popupItem) const;
void EnableItem (short popupItem);
void DisableItem (short popupItem);
void SetItemStatus (short popupItem, bool enable);
bool IsItemEnabled (short popupItem) const;
void SetItemValue (short popupItem, DGUserData value);
DGUserData GetItemValue (short popupItem) const;
void SetItemObjectData (short popupItem, GS::Ref<GS::Object> object);
GS::Ref<GS::Object> GetItemObjectData (short popupItem) const;
void SetItemCharCode (short popupItem, GSCharCode charCode);
GSCharCode GetItemCharCode (short popupItem) const;
void SelectItem (short popupItem);
short GetSelectedItem (void) const;
void DisableDraw (void);
void EnableDraw (void);
};
} // namespace DG
#endif
| 24.058824 | 80 | 0.622249 | [
"object"
] |
3b39b9beda5445471841d9af8a381207eee45890 | 1,152 | cpp | C++ | convo/Pthread.cpp | navneel99/image_processing_library | c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76 | [
"MIT"
] | null | null | null | convo/Pthread.cpp | navneel99/image_processing_library | c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76 | [
"MIT"
] | null | null | null | convo/Pthread.cpp | navneel99/image_processing_library | c4a13be8a9c7b2d7b1f6373bc6b3707d0d01be76 | [
"MIT"
] | null | null | null | #include "convolution.hpp"
#include <pthread.h>
// maximum number of threads
#define MAX_THREAD 5
vector<vector<float> > matA;
vector<float> matB;
vector<float> matC;
int t;
int m;
int step_i = 0;
void* multi(void* arg)
{
int core = step_i++;
for (int i = core * t/ MAX_THREAD; i < (core + 1) * t / MAX_THREAD; i++) {
float sum = 0;
for (int k = 0; k < m; k++){
sum += matA[i][k] * matB[k];
}
matC[i] = sum;
}
}
vector<float> Pthread(vector<vector<float> > temp, vector<float> ker)
{
t =temp.size();
m = ker.size();
matA = temp;
matB = ker;
::matC.clear();
for (int k = 0; k<t;k++){
matC.push_back(0);
}
pthread_t threads[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; i++) {
int* p;
pthread_create(&threads[i], NULL, multi, (void*)(p));
}
// joining and waiting for all threads to complete
for (int i = 0; i < MAX_THREAD; i++){
pthread_join(threads[i], NULL);
}
// ::matA.clear();
// ::matB.clear();
::step_i = 0;
return matC;
} | 21.735849 | 78 | 0.502604 | [
"vector"
] |
3b3a458148dbca1302fa0e05885daf44de7d891f | 4,829 | cpp | C++ | Source/FirebaseAnalytics/Private/FirebaseAnalyticsUtils.cpp | GloryOfNight/UE4_FirebaseAnalytics | cb489a05c2d492ef15bf6ef3f674e65b91349aa0 | [
"MIT"
] | 11 | 2020-05-16T03:17:54.000Z | 2022-02-03T17:11:03.000Z | Source/FirebaseAnalytics/Private/FirebaseAnalyticsUtils.cpp | GloryOfNight/UE4_FirebaseAnalytics | cb489a05c2d492ef15bf6ef3f674e65b91349aa0 | [
"MIT"
] | 3 | 2020-05-21T11:38:24.000Z | 2021-03-10T20:41:16.000Z | Source/FirebaseAnalytics/Private/FirebaseAnalyticsUtils.cpp | GloryOfNight/UE4FirebaseAnalytics | cb489a05c2d492ef15bf6ef3f674e65b91349aa0 | [
"MIT"
] | 4 | 2020-05-19T03:00:03.000Z | 2021-05-27T13:40:25.000Z | #include "FirebaseAnalyticsUtils.h"
#include "firebase/analytics.h"
#include "firebase/analytics/event_names.h"
#include "firebase/analytics/parameter_names.h"
#include "Analytics.h"
#include "FirebaseAnalyticsProvider.h"
void UFirebaseAnalyticsUtils::SetFirebaseUserProperty(const FString& Name, const FString& Property)
{
::firebase::analytics::SetUserProperty(TCHAR_TO_UTF8(*Name), TCHAR_TO_UTF8(*Property));
}
void UFirebaseAnalyticsUtils::SetFirebaseTimeoutSessionDuration(const int32 Seconds)
{
::firebase::analytics::SetSessionTimeoutDuration(static_cast<int64_t>(Seconds * 1000));
}
void UFirebaseAnalyticsUtils::SetFirebaseAnalyticsCollectionEnabled(const bool IsEnabled)
{
::firebase::analytics::SetAnalyticsCollectionEnabled(IsEnabled);
}
void UFirebaseAnalyticsUtils::ResetFirebaseAnalyticsData()
{
::firebase::analytics::ResetAnalyticsData();
}
void UFirebaseAnalyticsUtils::SetFirebaseCurrentScreen(const FString& ScreenName, const FString& ScreenClass)
{
::firebase::analytics::SetCurrentScreen(TCHAR_TO_UTF8(*ScreenName), TCHAR_TO_UTF8(*ScreenClass));
}
void UFirebaseAnalyticsUtils::RecordFirebaseEvent(const FString& Name)
{
::firebase::analytics::LogEvent(TCHAR_TO_UTF8(*Name));
}
void UFirebaseAnalyticsUtils::RecordEventWithStringParameter(const FString& Name, const FString& ParameterName, const FString& Value)
{
::firebase::analytics::LogEvent(TCHAR_TO_UTF8(*Name), TCHAR_TO_UTF8(*ParameterName), TCHAR_TO_UTF8(*Value));
}
void UFirebaseAnalyticsUtils::RecordEventWithFloatParameter(const FString& Name, const FString& ParameterName, const float Value)
{
::firebase::analytics::LogEvent(TCHAR_TO_UTF8(*Name), TCHAR_TO_UTF8(*ParameterName), Value);
}
void UFirebaseAnalyticsUtils::RecordEventWithInt32Parameter(const FString& Name, const FString& ParameterName, const int32 Value)
{
::firebase::analytics::LogEvent(TCHAR_TO_UTF8(*Name), TCHAR_TO_UTF8(*ParameterName), Value);
}
void UFirebaseAnalyticsUtils::RecordEventWithInt64Parameter(const FString& Name, const FString& ParameterName, const int64 Value)
{
::firebase::analytics::LogEvent(TCHAR_TO_UTF8(*Name), TCHAR_TO_UTF8(*ParameterName), Value);
}
void UFirebaseAnalyticsUtils::RecordFirebaseTutorialBegin()
{
::firebase::analytics::LogEvent(::firebase::analytics::kEventTutorialBegin);
}
void UFirebaseAnalyticsUtils::RecordFirebaseTutorialEnd()
{
::firebase::analytics::LogEvent(::firebase::analytics::kEventTutorialComplete);
}
void UFirebaseAnalyticsUtils::RecordFirebaseLevelEnd(const FString& LevelName, const FString& Success)
{
// clang-format off
std::vector<::firebase::analytics::Parameter> Parameters =
{
{::firebase::analytics::kParameterLevelName, TCHAR_TO_UTF8(*LevelName)},
{::firebase::analytics::kParameterSuccess, TCHAR_TO_UTF8(*Success)}
};
// clang-format on
::firebase::analytics::LogEvent(::firebase::analytics::kEventLevelEnd, Parameters.data(), Parameters.size());
}
void UFirebaseAnalyticsUtils::RecordFirebaseLevelStart(const FString& LevelName)
{
::firebase::analytics::LogEvent(::firebase::analytics::kEventLevelStart, ::firebase::analytics::kParameterLevelName, TCHAR_TO_UTF8(*LevelName));
}
void UFirebaseAnalyticsUtils::RecordFirebaseLevelUp()
{
::firebase::analytics::LogEvent(::firebase::analytics::kEventLevelUp);
}
void UFirebaseAnalyticsUtils::RecordFirebasePurchase(const FString& Affiliation, const FString& Coupon, const FString& Currency, const TArray<FString>& Items, const float Shipping, const float Tax, const FString& TransactionID, const float Value)
{
RecordFirebasePurchase(Affiliation, Coupon, Currency, Items, static_cast<double>(Shipping), static_cast<double>(Tax), TransactionID, static_cast<double>(Value));
}
void UFirebaseAnalyticsUtils::RecordFirebasePurchase(const FString& Affiliation, const FString& Coupon, const FString& Currency, const TArray<FString>& Items, const double Shipping, const double Tax, const FString& TransactionID, const double Value)
{
std::vector<std::string> ItemsVec;
ItemsVec.reserve(Items.Num());
for (const auto& Item : Items)
{
ItemsVec.push_back(TCHAR_TO_UTF8(*Item));
}
// clang-format off
std::vector<::firebase::analytics::Parameter> Parameters =
{
{::firebase::analytics::kParameterAffiliation, TCHAR_TO_UTF8(*Affiliation)},
{::firebase::analytics::kParameterCoupon, TCHAR_TO_UTF8(*Coupon)},
{::firebase::analytics::kParameterCurrency, TCHAR_TO_UTF8(*Currency)},
{::firebase::analytics::kParameterItems, ItemsVec},
{::firebase::analytics::kParameterShipping, Shipping},
{::firebase::analytics::kParameterTax, Tax},
{::firebase::analytics::kParameterTransactionID, TCHAR_TO_UTF8(*TransactionID)},
{::firebase::analytics::kParameterValue, Value},
};
// clang-format on
::firebase::analytics::LogEvent(::firebase::analytics::kEventLevelEnd, Parameters.data(), Parameters.size());
}
| 39.909091 | 249 | 0.790433 | [
"vector"
] |
3b42ad62ab50021bcfeb294f4ae90b88743986c3 | 41,058 | cpp | C++ | dev/Code/CryEngine/RenderDll/Common/tests/Shaders/VertexTests.cpp | BadDevCode/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | 2 | 2020-06-27T12:13:44.000Z | 2020-06-27T12:13:46.000Z | dev/Code/CryEngine/RenderDll/Common/tests/Shaders/VertexTests.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | dev/Code/CryEngine/RenderDll/Common/tests/Shaders/VertexTests.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include <AzTest/AzTest.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/UnitTest/UnitTest.h>
#include "Common/Shaders/Vertex.h"
#include "DriverD3D.h"
// General vertex stream stride
int32 m_cSizeVF[eVF_Max] =
{
0,
sizeof(SVF_P3F_C4B_T2F),
sizeof(SVF_P3F_C4B_T2F_T2F),
sizeof(SVF_P3S_C4B_T2S),
sizeof(SVF_P3S_C4B_T2S_T2S),
sizeof(SVF_P3S_N4B_C4B_T2S),
sizeof(SVF_P3F_C4B_T4B_N3F2),
sizeof(SVF_TP3F_C4B_T2F),
sizeof(SVF_TP3F_T2F_T3F),
sizeof(SVF_P3F_T3F),
sizeof(SVF_P3F_T2F_T3F),
sizeof(SVF_T2F),
sizeof(SVF_W4B_I4S),
sizeof(SVF_C4B_C4B),
sizeof(SVF_P3F_P3F_I4B),
sizeof(SVF_P3F),
sizeof(SVF_C4B_T2S),
sizeof(SVF_P2F_T4F_C4F),
sizeof(SVF_P2F_T4F_T4F_C4F),
sizeof(SVF_P2S_N4B_C4B_T1F),
sizeof(SVF_P3F_C4B_T2S),
sizeof(SVF_P2F_C4B_T2F_F4B),
sizeof(SVF_P3F_C4B),
sizeof(SVF_P3F_C4F_T2F), //format number 23 (for testing verification)
sizeof(SVF_P3F_C4F_T2F_T3F),
sizeof(SVF_P3F_C4F_T2F_T1F),
sizeof(SVF_P3F_C4F_T2F_T1F_T3F),
sizeof(SVF_P3F_C4F_T4F_T2F),
sizeof(SVF_P3F_C4F_T4F_T2F_T3F),
sizeof(SVF_P3F_C4F_T4F_T2F_T1F),
sizeof(SVF_P3F_C4F_T4F_T2F_T1F_T3F), //30
sizeof(SVF_P3F_C4F_T2F_T2F_T1F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T3F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T1F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F),
sizeof(SVF_P4F_T2F_C4F_T4F_T4F), //35
sizeof(SVF_P3F_C4F_T2F_T4F),
sizeof(SVF_P3F_C4F_T2F_T3F_T4F),
sizeof(SVF_P3F_C4F_T2F_T1F_T4F),
sizeof(SVF_P3F_C4F_T2F_T1F_T3F_T4F),
sizeof(SVF_P3F_C4F_T4F_T2F_T4F), //40
sizeof(SVF_P3F_C4F_T4F_T2F_T3F_T4F),
sizeof(SVF_P3F_C4F_T4F_T2F_T1F_T4F),
sizeof(SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F), //45
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F),
sizeof(SVF_P4F_T2F_C4F_T4F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T3F_T4F_T4F), //50
sizeof(SVF_P3F_C4F_T2F_T1F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F),
sizeof(SVF_P3F_C4F_T4F_T2F_T4F_T4F),
sizeof(SVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F),
sizeof(SVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F), //55
sizeof(SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F),
sizeof(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F), //60
sizeof(SVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F),
};
// Legacy table copied from RenderMesh.cpp
#define OOFS(t, x) ((int)offsetof(t, x))
SBufInfoTable m_cBufInfoTable[eVF_Max] =
{
// { Texcoord, Color, Normal }
{
-1, -1, -1
},
{ //eVF_P3F_C4B_T2F
OOFS(SVF_P3F_C4B_T2F, st),
OOFS(SVF_P3F_C4B_T2F, color.dcolor),
-1
},
{ //eVF_P3F_C4B_T2F_T2F
OOFS(SVF_P3F_C4B_T2F_T2F, st),
OOFS(SVF_P3F_C4B_T2F_T2F, color.dcolor),
-1
},
{ //eVF_P3S_C4B_T2S
OOFS(SVF_P3S_C4B_T2S, st),
OOFS(SVF_P3S_C4B_T2S, color.dcolor),
-1
},
{ //eVF_P3S_C4B_T2S_T2S
OOFS(SVF_P3S_C4B_T2S_T2S, st),
OOFS(SVF_P3S_C4B_T2S_T2S, color.dcolor),
-1
},
{ //eVF_P3S_N4B_C4B_T2S
OOFS(SVF_P3S_N4B_C4B_T2S, st),
OOFS(SVF_P3S_N4B_C4B_T2S, color.dcolor),
OOFS(SVF_P3S_N4B_C4B_T2S, normal)
},
{ // eVF_P3F_C4B_T4B_N3F2
-1,
OOFS(SVF_P3F_C4B_T4B_N3F2, color.dcolor),
-1
},
{ // eVF_TP3F_C4B_T2F
OOFS(SVF_TP3F_C4B_T2F, st),
OOFS(SVF_TP3F_C4B_T2F, color.dcolor),
-1
},
{ // eVF_TP3F_T2F_T3F
OOFS(SVF_TP3F_T2F_T3F, st0),
-1,
-1
},
{ // eVF_P3F_T3F
OOFS(SVF_P3F_T3F, st),
-1,
-1
},
{ // eVF_P3F_T2F_T3F
OOFS(SVF_P3F_T2F_T3F, st0),
-1,
-1
},
{// eVF_T2F
OOFS(SVF_T2F, st),
-1,
-1
},
{ -1, -1, -1 },// eVF_W4B_I4S
{ -1, -1, -1 },// eVF_C4B_C4B
{ -1, -1, -1 },// eVF_P3F_P3F_I4B
{
-1,
-1,
-1
},
{ // eVF_C4B_T2S
OOFS(SVF_C4B_T2S, st),
OOFS(SVF_C4B_T2S, color.dcolor),
-1
},
{ // eVF_P2F_T4F_C4F
OOFS(SVF_P2F_T4F_C4F, st),
OOFS(SVF_P2F_T4F_C4F, color),
-1
},
{ // eVF_P2F_T4F_T4F_C4F
OOFS(SVF_P2F_T4F_T4F_C4F, st),
OOFS(SVF_P2F_T4F_T4F_C4F, color),
-1
},
{ // eVF_P2S_N4B_C4B_T1F
OOFS(SVF_P2S_N4B_C4B_T1F, z),
OOFS(SVF_P2S_N4B_C4B_T1F, color.dcolor),
OOFS(SVF_P2S_N4B_C4B_T1F, normal)
},
{ // eVF_P3F_C4B_T2S
OOFS(SVF_P3F_C4B_T2S, st),
OOFS(SVF_P3F_C4B_T2S, color.dcolor),
-1
},
{ // SVF_P2F_C4B_T2F_F4B
OOFS(SVF_P2F_C4B_T2F_F4B, st),
OOFS(SVF_P2F_C4B_T2F_F4B, color.dcolor),
-1
},
{ // eVF_P3F_C4B
-1,
OOFS(SVF_P3F_C4B, color.dcolor),
-1
},
{ // eVF_P3F_C4F_T2F
OOFS(SVF_P3F_C4F_T2F, st),
OOFS(SVF_P3F_C4F_T2F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T3F
OOFS(SVF_P3F_C4F_T2F_T3F, st0),
OOFS(SVF_P3F_C4F_T2F_T3F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T1F
OOFS(SVF_P3F_C4F_T2F_T1F, st),
OOFS(SVF_P3F_C4F_T2F_T1F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T1F_T3F
OOFS(SVF_P3F_C4F_T2F_T1F_T3F, st0),
OOFS(SVF_P3F_C4F_T2F_T1F_T3F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F
OOFS(SVF_P3F_C4F_T4F_T2F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T3F
OOFS(SVF_P3F_C4F_T4F_T2F_T3F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T3F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T1F
OOFS(SVF_P3F_C4F_T4F_T2F_T1F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T1F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T1F_T3F
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T3F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T3F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T3F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T3F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T3F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T1F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F, color),
-1
},
{ // eVF_P4F_T2F_C4F_T4F_T4F
OOFS(SVF_P4F_T2F_C4F_T4F_T4F, st0),
OOFS(SVF_P4F_T2F_C4F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T4F
OOFS(SVF_P3F_C4F_T2F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T3F_T4F
OOFS(SVF_P3F_C4F_T2F_T3F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T3F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T1F_T4F
OOFS(SVF_P3F_C4F_T2F_T1F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T1F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T1F_T3F_T4F
OOFS(SVF_P3F_C4F_T2F_T1F_T3F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T1F_T3F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T3F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T3F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T3F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T1F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F, color),
-1
},
{ // eVF_P4F_T2F_C4F_T4F_T4F_T4F
OOFS(SVF_P4F_T2F_C4F_T4F_T4F_T4F, st0),
OOFS(SVF_P4F_T2F_C4F_T4F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T3F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T3F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T3F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T1F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T1F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T1F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T4F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F, color),
-1
},
{ // eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F, st0),
OOFS(SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F, color),
-1
},
{ // eVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F
OOFS(SVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F, st0),
OOFS(SVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F, color),
-1
},
};
#undef OOFS
AZStd::vector<D3D11_INPUT_ELEMENT_DESC> Legacy_InitBaseStreamD3DVertexDeclaration(EVertexFormat nFormat)
{
//========================================================================================
// base stream declarations (stream 0)
D3D11_INPUT_ELEMENT_DESC elemPosHalf = { "POSITION", 0, DXGI_FORMAT_R16G16B16A16_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemTCHalf = { "TEXCOORD", 0, DXGI_FORMAT_R16G16_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemPos = { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemPos2 = { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemPosTR = { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // position
D3D11_INPUT_ELEMENT_DESC elemPos2Half = { "POSITION", 0, DXGI_FORMAT_R16G16_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemPos1 = { "POSITION", 1, DXGI_FORMAT_R32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemNormalB = { "NORMAL", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 };
D3D11_INPUT_ELEMENT_DESC elemTan = { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // axis/size
D3D11_INPUT_ELEMENT_DESC elemBitan = { "TEXCOORD", 1, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // axis/size
D3D11_INPUT_ELEMENT_DESC elemColor = { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // diffuse
D3D11_INPUT_ELEMENT_DESC elemColorF = { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // general color
D3D11_INPUT_ELEMENT_DESC elemTC0 = { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
D3D11_INPUT_ELEMENT_DESC elemTC1 = { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
D3D11_INPUT_ELEMENT_DESC elemTC2 = { "TEXCOORD", 2, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
D3D11_INPUT_ELEMENT_DESC elemTC1_3 = { "TEXCOORD", 1, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
D3D11_INPUT_ELEMENT_DESC elemTC0_4 = { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
D3D11_INPUT_ELEMENT_DESC elemTC0_1 = { "TEXCOORD", 0, DXGI_FORMAT_R32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
D3D11_INPUT_ELEMENT_DESC elemTC3_4 = { "TEXCOORD", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }; // texture
AZ::Vertex::Format vertexFormat = AZ::Vertex::Format((EVertexFormat)nFormat);
AZStd::vector<D3D11_INPUT_ELEMENT_DESC> decl;
uint texCoordOffset = 0;
bool hasTexCoord = vertexFormat.TryCalculateOffset(texCoordOffset, AZ::Vertex::AttributeUsage::TexCoord);
uint colorOffset = 0;
bool hasColor = vertexFormat.TryCalculateOffset(colorOffset, AZ::Vertex::AttributeUsage::Color);
uint normalOffset = 0;
bool hasNormal = vertexFormat.TryCalculateOffset(normalOffset, AZ::Vertex::AttributeUsage::Normal);
// Position
switch (nFormat)
{
case eVF_TP3F_C4B_T2F:
case eVF_TP3F_T2F_T3F:
decl.push_back(elemPosTR);
break;
case eVF_P3S_C4B_T2S:
case eVF_P3S_N4B_C4B_T2S:
decl.push_back(elemPosHalf);
break;
case eVF_P2S_N4B_C4B_T1F:
decl.push_back(elemPos2Half);
break;
case eVF_P2F_T4F_C4F:
decl.push_back(elemPos2);
break;
case eVF_T2F:
case eVF_C4B_T2S:
case eVF_Unknown:
break;
default:
decl.push_back(elemPos);
}
// Normal
if (hasNormal)
{
elemNormalB.AlignedByteOffset = normalOffset;
decl.push_back(elemNormalB);
}
#ifdef PARTICLE_MOTION_BLUR
if (nFormat == eVF_P3F_C4B_T4B_N3F2)
{
elemTC0_4.AlignedByteOffset = (int)offsetof(SVF_P3F_C4B_T4B_N3F2, prevXaxis);
elemTC0_4.SemanticIndex = 0;
decl.AddElem(elemTC0_4);
}
#endif
// eVF_P2F_T4F_C4F has special case logic below, so ignore it here
if (hasColor && nFormat != eVF_P2F_T4F_C4F)
{
elemColor.AlignedByteOffset = colorOffset;
elemColor.SemanticIndex = 0;
decl.push_back(elemColor);
}
if (nFormat == eVF_P3F_C4B_T4B_N3F2)
{
#ifdef PARTICLE_MOTION_BLUR
elemTC1_3.AlignedByteOffset = (int)offsetof(SVF_P3F_C4B_T4B_N3F2, prevPos);
elemTC1_3.SemanticIndex = 1;
decl.push_back(elemTC1_3);
#endif
elemColor.AlignedByteOffset = (int)offsetof(SVF_P3F_C4B_T4B_N3F2, st);
elemColor.SemanticIndex = 1;
decl.push_back(elemColor);
elemTan.AlignedByteOffset = (int)offsetof(SVF_P3F_C4B_T4B_N3F2, xaxis);
decl.push_back(elemTan);
elemBitan.AlignedByteOffset = (int)offsetof(SVF_P3F_C4B_T4B_N3F2, yaxis);
decl.push_back(elemBitan);
}
if (nFormat == eVF_P2F_T4F_C4F)
{
elemTC0_4.AlignedByteOffset = (int)offsetof(SVF_P2F_T4F_C4F, st);
elemTC0_4.SemanticIndex = 0;
decl.push_back(elemTC0_4);
elemColorF.AlignedByteOffset = (int)offsetof(SVF_P2F_T4F_C4F, color);
elemColorF.SemanticIndex = 0;
decl.push_back(elemColorF);
}
//handle cases where 2D texture comes before 4F Color
if (nFormat == eVF_P4F_T2F_C4F_T4F_T4F || nFormat == eVF_P4F_T2F_C4F_T4F_T4F_T4F || nFormat == eVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F)
{
elemTC2.AlignedByteOffset = (int)offsetof(SVF_P4F_T2F_C4F_T4F_T4F, st0);
elemTC2.SemanticIndex = 0;
decl.push_back(elemTC2);
elemColorF.AlignedByteOffset = (int)offsetof(SVF_P4F_T2F_C4F_T4F_T4F, color);
elemColorF.SemanticIndex = 0;
decl.push_back(elemColorF);
}
if (hasTexCoord)
{
elemTC0.AlignedByteOffset = texCoordOffset;
elemTC0.SemanticIndex = 0;
switch (nFormat)
{
case eVF_P2F_T4F_C4F:
// eVF_P2F_T4F_C4F has special case logic above, so ignore it here
break;
case eVF_P3S_C4B_T2S:
case eVF_P3S_N4B_C4B_T2S:
case eVF_C4B_T2S:
case eVF_P3F_C4B_T2S:
elemTCHalf.AlignedByteOffset = texCoordOffset;
elemTCHalf.SemanticIndex = 0;
decl.push_back(elemTCHalf);
break;
case eVF_P3F_T3F:
elemTC1_3.AlignedByteOffset = texCoordOffset;
elemTC1_3.SemanticIndex = 0;
decl.push_back(elemTC1_3);
break;
case eVF_P2S_N4B_C4B_T1F:
elemTC0_1.AlignedByteOffset = texCoordOffset;
elemTC0_1.SemanticIndex = 0;
decl.push_back(elemTC0_1);
break;
case eVF_TP3F_T2F_T3F:
case eVF_P3F_T2F_T3F:
decl.push_back(elemTC0);
//This case needs two TexCoord elements
elemTC1_3.AlignedByteOffset = texCoordOffset + 8;
elemTC1_3.SemanticIndex = 1;
decl.push_back(elemTC1_3);
break;
default:
decl.push_back(elemTC0);
}
}
if (nFormat == eVF_P2S_N4B_C4B_T1F)
{
elemPos1.AlignedByteOffset = (int)offsetof(SVF_P2S_N4B_C4B_T1F, z);
decl.push_back(elemPos1);
}
decl.shrink_to_fit();
return decl;
}
bool DeclarationsAreEqual(AZStd::vector<D3D11_INPUT_ELEMENT_DESC>& declarationA, AZStd::vector<D3D11_INPUT_ELEMENT_DESC>& declarationB)
{
if (declarationA.size() != declarationB.size())
{
return false;
}
for (uint i = 0; i < declarationA.size(); ++i)
{
D3D11_INPUT_ELEMENT_DESC elementDescriptionA = declarationA[i];
D3D11_INPUT_ELEMENT_DESC elementDescriptionB = declarationB[i];
if (elementDescriptionA.SemanticIndex != elementDescriptionB.SemanticIndex ||
elementDescriptionA.Format != elementDescriptionB.Format ||
elementDescriptionA.InputSlot != elementDescriptionB.InputSlot ||
elementDescriptionA.AlignedByteOffset != elementDescriptionB.AlignedByteOffset ||
elementDescriptionA.InputSlotClass != elementDescriptionB.InputSlotClass ||
elementDescriptionA.InstanceDataStepRate != elementDescriptionB.InstanceDataStepRate ||
strcmp(elementDescriptionA.SemanticName, elementDescriptionB.SemanticName) != 0)
{
return false;
}
}
return true;
}
class VertexFormatAssertTest
: public ::testing::Test
, public UnitTest::AllocatorsBase
{
protected:
void SetUp() override
{
UnitTest::AllocatorsBase::SetupAllocator();
}
void TearDown() override
{
UnitTest::AllocatorsBase::TeardownAllocator();
}
};
TEST_F(VertexFormatAssertTest, VertexFormatConstructor_AssertsOnInvalidInput)
{
// The vertex format constructor should assert when an invalid vertex format enum is used
AZ_TEST_START_TRACE_SUPPRESSION;
AZ::Vertex::Format(static_cast<EVertexFormat>(EVertexFormat::eVF_Max));
AZ::Vertex::Format(static_cast<EVertexFormat>(EVertexFormat::eVF_Max + 1));
// Expect 2 asserts
AZ_TEST_STOP_TRACE_SUPPRESSION(2);
}
class VertexFormatTest
: public ::testing::TestWithParam < int >
, public UnitTest::AllocatorsBase
{
public:
void SetUp() override
{
UnitTest::AllocatorsBase::SetupAllocator();
}
void TearDown() override
{
UnitTest::AllocatorsBase::TeardownAllocator();
}
};
TEST_P(VertexFormatTest, GetStride_MatchesExpected)
{
EVertexFormat eVF = (EVertexFormat)GetParam();
AZ::Vertex::Format format(eVF);
uint actualSize = format.GetStride();
uint expectedSize = m_cSizeVF[eVF];
EXPECT_EQ(actualSize, expectedSize);
}
TEST_P(VertexFormatTest, CalculateOffset_MatchesExpected)
{
EVertexFormat eVF = (EVertexFormat)GetParam();
AZ::Vertex::Format format(eVF);
// TexCoord
uint actualOffset = 0;
bool hasOffset = format.TryCalculateOffset(actualOffset, AZ::Vertex::AttributeUsage::TexCoord);
int expectedOffset = m_cBufInfoTable[eVF].OffsTC;
if (expectedOffset >= 0)
{
EXPECT_TRUE(hasOffset);
EXPECT_EQ(actualOffset, expectedOffset);
}
else
{
EXPECT_FALSE(hasOffset);
}
// Color
hasOffset = format.TryCalculateOffset(actualOffset, AZ::Vertex::AttributeUsage::Color);
expectedOffset = m_cBufInfoTable[eVF].OffsColor;
if (expectedOffset >= 0)
{
EXPECT_TRUE(hasOffset);
EXPECT_EQ(actualOffset, expectedOffset);
}
else
{
EXPECT_FALSE(hasOffset);
}
// Normal
hasOffset = format.TryCalculateOffset(actualOffset, AZ::Vertex::AttributeUsage::Normal);
expectedOffset = m_cBufInfoTable[eVF].OffsNorm;
if (expectedOffset >= 0)
{
EXPECT_TRUE(hasOffset);
EXPECT_EQ(actualOffset, expectedOffset);
}
else
{
EXPECT_FALSE(hasOffset);
}
}
TEST_F(VertexFormatTest, CalculateOffsetMultipleUVs_MatchesExpected)
{
AZ::Vertex::Format vertexFormat(eVF_P3F_C4B_T2F_T2F);
uint offset = 0;
// The first uv set exists
EXPECT_TRUE(vertexFormat.TryCalculateOffset(offset, AZ::Vertex::AttributeUsage::TexCoord, 0));
// First Texture coordinate comes after the position, which has 3 32 bit floats, and the color, which has 4 bytes
EXPECT_EQ(offset, AZ::Vertex::AttributeTypeDataTable[(int)AZ::Vertex::AttributeType::Float32_3].byteSize + AZ::Vertex::AttributeTypeDataTable[(int)AZ::Vertex::AttributeType::Byte_4].byteSize);
// The second uv set exists
EXPECT_TRUE(vertexFormat.TryCalculateOffset(offset, AZ::Vertex::AttributeUsage::TexCoord, 1));
// Second Texture coordinate comes after the position + color + the first texture coordinate
EXPECT_EQ(offset, AZ::Vertex::AttributeTypeDataTable[(int)AZ::Vertex::AttributeType::Float32_3].byteSize + AZ::Vertex::AttributeTypeDataTable[(int)AZ::Vertex::AttributeType::Byte_4].byteSize + AZ::Vertex::AttributeTypeDataTable[(int)AZ::Vertex::AttributeType::Float32_2].byteSize);
// The third uv set does not exist
EXPECT_FALSE(vertexFormat.TryCalculateOffset(offset, AZ::Vertex::AttributeUsage::TexCoord, 2));
}
TEST_P(VertexFormatTest, D3DVertexDeclarations_MatchesLegacy)
{
EVertexFormat eVF = (EVertexFormat)GetParam();
AZStd::vector<D3D11_INPUT_ELEMENT_DESC> expected = Legacy_InitBaseStreamD3DVertexDeclaration(eVF);
bool matchesLegacy = true;
//the new vertex definitions aren't legacy and never were a part of the legacy system in any way, and should be ignored for this test
//new definitions occur after entry number 22;
const unsigned int ignoredFormatsStart = aznumeric_cast<unsigned int>(eVF_P3F_C4F_T2F); //23
const unsigned int ignoredFormatsEnd = aznumeric_cast<unsigned int>(eVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F); //61
if (aznumeric_cast<unsigned int>(eVF) >= ignoredFormatsStart && aznumeric_cast<unsigned int>(eVF) <= ignoredFormatsEnd)
{
EXPECT_TRUE(matchesLegacy);
return;
}
// The legacy result of EF_InitD3DVertexDeclarations for the following formats are flat out wrong (it defaults to one D3D11_INPUT_ELEMENT_DESC that is a position, which is clearly not the case for any of these)
// eVF_W4B_I4S is really blendweights + indices
// eVF_C4B_C4B is really two spherical harmonic coefficients
// eVF_P3F_P3F_I4B is really two positions and an index
// eVF_P2F_T4F_T4F_C4F doesn't actually exist in the engine anymore
// ignore these cases
// Also ignore eVF_P2S_N4B_C4B_T1F: the T1F attribute has a POSITION semantic name in the legacy declaration, even though both the engine and shader treat it as a TEXCOORD (despite the fact that it is eventually used for a position)
// eVF_P3F_C4B_T2F_T2F, eVF_P3S_C4B_T2S_T2S, and eVF_P2F_C4B_T2F_F4B are all new
else if (eVF != eVF_W4B_I4S && eVF != eVF_C4B_C4B && eVF != eVF_P3F_P3F_I4B && eVF != eVF_P2F_T4F_T4F_C4F && eVF != eVF_P2S_N4B_C4B_T1F && eVF != eVF_P2F_C4B_T2F_F4B && eVF != eVF_P3F_C4B_T2F_T2F && eVF != eVF_P3S_C4B_T2S_T2S)
{
AZStd::vector<D3D11_INPUT_ELEMENT_DESC> actual = GetD3D11Declaration(AZ::Vertex::Format(eVF));
matchesLegacy = DeclarationsAreEqual(actual, expected);
}
EXPECT_TRUE(matchesLegacy);
}
TEST_P(VertexFormatTest, GetStride_4ByteAligned)
{
EVertexFormat eVF = (EVertexFormat)GetParam();
AZ::Vertex::Format format(eVF);
EXPECT_EQ(format.GetStride() % AZ::Vertex::VERTEX_BUFFER_ALIGNMENT, 0);
}
class VertexFormatComparisonTest
: public ::testing::TestWithParam < int >
, public UnitTest::AllocatorsBase
{
protected:
void SetUp() override
{
UnitTest::AllocatorsBase::SetupAllocator();
m_vertexFormatEnum = static_cast<EVertexFormat>(GetParam());
m_vertexFormat = AZ::Vertex::Format(m_vertexFormatEnum);
m_nextVertexFormatEnum = static_cast<EVertexFormat>((m_vertexFormatEnum + 1) % eVF_Max);
m_nextVertexFormat = AZ::Vertex::Format(m_nextVertexFormatEnum);
}
void TearDown() override
{
UnitTest::AllocatorsBase::TeardownAllocator();
}
EVertexFormat m_vertexFormatEnum;
AZ::Vertex::Format m_vertexFormat;
AZ::Vertex::Format m_nextVertexFormat;
EVertexFormat m_nextVertexFormatEnum;
};
TEST_P(VertexFormatComparisonTest, EqualTo_SameVertexFormat_True)
{
EXPECT_TRUE(m_vertexFormat == m_vertexFormatEnum);
EXPECT_TRUE(m_vertexFormat == m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, EqualTo_NextVertexFormat_False)
{
EXPECT_FALSE(m_vertexFormat == m_nextVertexFormatEnum);
EXPECT_FALSE(m_vertexFormat == m_nextVertexFormat);
}
TEST_P(VertexFormatComparisonTest, EqualTo_PreviousVertexFormat_False)
{
EXPECT_FALSE(m_nextVertexFormat == m_vertexFormatEnum);
EXPECT_FALSE(m_nextVertexFormat == m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, NotEqualTo_SameVertexFormat_False)
{
EXPECT_FALSE(m_vertexFormat != m_vertexFormatEnum);
EXPECT_FALSE(m_vertexFormat != m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, NotEqualTo_NextVertexFormat_True)
{
EXPECT_TRUE(m_vertexFormat != m_nextVertexFormatEnum);
EXPECT_TRUE(m_vertexFormat != m_nextVertexFormat);
}
TEST_P(VertexFormatComparisonTest, NotEqualTo_PreviousVertexFormat_True)
{
EXPECT_TRUE(m_nextVertexFormat != m_vertexFormatEnum);
EXPECT_TRUE(m_nextVertexFormat != m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, GreaterThan_SameVertexFormat_False)
{
EXPECT_FALSE(m_vertexFormat > m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, GreaterThan_NextVertexFormat_False)
{
EXPECT_FALSE(m_vertexFormat > m_nextVertexFormat);
}
TEST_P(VertexFormatComparisonTest, GreaterThan_PreviousVertexFormat_True)
{
EXPECT_TRUE(m_nextVertexFormat > m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, GreaterThanOrEqualTo_SameVertexFormat_True)
{
EXPECT_TRUE(m_vertexFormat >= m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, GreaterThanOrEqualTo_NextVertexFormat_False)
{
EXPECT_FALSE(m_vertexFormat >= m_nextVertexFormat);
}
TEST_P(VertexFormatComparisonTest, GreaterThanOrEqualTo_PreviousVertexFormat_True)
{
EXPECT_TRUE(m_nextVertexFormat >= m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, LessThan_SameVertexFormat_False)
{
EXPECT_FALSE(m_vertexFormat < m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, LessThan_NextVertexFormat_True)
{
EXPECT_TRUE(m_vertexFormat < m_nextVertexFormat);
}
TEST_P(VertexFormatComparisonTest, LessThan_PreviousVertexFormat_False)
{
EXPECT_FALSE(m_nextVertexFormat < m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, LessThanOrEqualTo_SameVertexFormat_True)
{
EXPECT_TRUE(m_vertexFormat <= m_vertexFormat);
}
TEST_P(VertexFormatComparisonTest, LessThanOrEqualTo_NextVertexFormat_True)
{
EXPECT_TRUE(m_vertexFormat <= m_nextVertexFormat);
}
TEST_P(VertexFormatComparisonTest, LessThanOrEqualTo_PreviousVertexFormat_False)
{
EXPECT_FALSE(m_nextVertexFormat <= m_vertexFormat);
}
TEST_P(VertexFormatTest, GetEnum_MatchesExpected)
{
EVertexFormat eVF = static_cast<EVertexFormat>(GetParam());
AZ::Vertex::Format vertexFormat(eVF);
EXPECT_EQ(vertexFormat.GetEnum(), eVF);
}
TEST_F(VertexFormatTest, GetAttributeUsageCount_MatchesExpected)
{
AZ::Vertex::Format vertexFormatP3F_C4B_T2F(eVF_P3F_C4B_T2F);
// eVF_P3F_C4B_T2F has one position, one color, one uv set, and no normal attribute
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeUsageCount(AZ::Vertex::AttributeUsage::Position), 1);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeUsageCount(AZ::Vertex::AttributeUsage::Color), 1);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeUsageCount(AZ::Vertex::AttributeUsage::TexCoord), 1);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeUsageCount(AZ::Vertex::AttributeUsage::Normal), 0);
// eVF_P3S_C4B_T2S and eVF_P3F_C4B_T2F_T2F actually have two uv sets
EXPECT_EQ(AZ::Vertex::Format(eVF_P3S_C4B_T2S_T2S).GetAttributeUsageCount(AZ::Vertex::AttributeUsage::TexCoord), 2);
EXPECT_EQ(AZ::Vertex::Format(eVF_P3F_C4B_T2F_T2F).GetAttributeUsageCount(AZ::Vertex::AttributeUsage::TexCoord), 2);
}
TEST_P(VertexFormatTest, IsSupersetOf_EquivalentVertexFormat_True)
{
EVertexFormat eVF = static_cast<EVertexFormat>(GetParam());
EXPECT_TRUE(AZ::Vertex::Format(eVF).IsSupersetOf(AZ::Vertex::Format(eVF)));
}
TEST_F(VertexFormatTest, IsSupersetOf_TargetHasExtraUVs_OnlyTargetIsSuperset)
{
AZ::Vertex::Format vertexFormatP3F_C4B_T2F(eVF_P3F_C4B_T2F);
AZ::Vertex::Format vertexFormatP3F_C4B_T2F_T2F(eVF_P3F_C4B_T2F_T2F);
// eVF_P3F_C4B_T2F_T2F contains everything in eVF_P3F_C4B_T2F plus an extra uv set
EXPECT_TRUE(vertexFormatP3F_C4B_T2F_T2F.IsSupersetOf(vertexFormatP3F_C4B_T2F));
EXPECT_FALSE(vertexFormatP3F_C4B_T2F.IsSupersetOf(vertexFormatP3F_C4B_T2F_T2F));
}
TEST_F(VertexFormatTest, TryGetAttributeOffsetAndType_MatchesExpected)
{
uint expectedOffset = 0;
uint offset = 0;
AZ::Vertex::AttributeType type = AZ::Vertex::AttributeType::NumTypes;
AZ::Vertex::Format vertexFormatP3F_C4B_T2F_T2F(eVF_P3F_C4B_T2F_T2F);
// eVF_P3F_C4B_T2F_T2F has a position at offset 0 that is a Float32_3
EXPECT_TRUE(vertexFormatP3F_C4B_T2F_T2F.TryGetAttributeOffsetAndType(AZ::Vertex::AttributeUsage::Position, 0, offset, type));
EXPECT_EQ(offset, expectedOffset);
EXPECT_EQ(type, AZ::Vertex::AttributeType::Float32_3);
expectedOffset += AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float32_3)].byteSize;
// eVF_P3F_C4B_T2F_T2F does not have a second position
EXPECT_FALSE(vertexFormatP3F_C4B_T2F_T2F.TryGetAttributeOffsetAndType(AZ::Vertex::AttributeUsage::Position, 1, offset, type));
// eVF_P3F_C4B_T2F_T2F has a color, offset by 12 bytes, that is a Byte_4
EXPECT_TRUE(vertexFormatP3F_C4B_T2F_T2F.TryGetAttributeOffsetAndType(AZ::Vertex::AttributeUsage::Color, 0, offset, type));
EXPECT_EQ(offset, expectedOffset);
EXPECT_EQ(type, AZ::Vertex::AttributeType::Byte_4);
expectedOffset += AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Byte_4)].byteSize;
// eVF_P3F_C4B_T2F_T2F has a TexCoord, offset by 16 bytes, that is a Float32_2
EXPECT_TRUE(vertexFormatP3F_C4B_T2F_T2F.TryGetAttributeOffsetAndType(AZ::Vertex::AttributeUsage::TexCoord, 0, offset, type));
EXPECT_EQ(offset, expectedOffset);
EXPECT_EQ(type, AZ::Vertex::AttributeType::Float32_2);
expectedOffset += AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float32_2)].byteSize;
// eVF_P3F_C4B_T2F_T2F has a second TexCoord, offset by 24 bytes, that is a Float32_2
EXPECT_TRUE(vertexFormatP3F_C4B_T2F_T2F.TryGetAttributeOffsetAndType(AZ::Vertex::AttributeUsage::TexCoord, 1, offset, type));
EXPECT_EQ(offset, expectedOffset);
EXPECT_EQ(type, AZ::Vertex::AttributeType::Float32_2);
expectedOffset += AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float32_2)].byteSize;
// eVF_P3F_C4B_T2F_T2F does not have a third TexCoord
EXPECT_FALSE(vertexFormatP3F_C4B_T2F_T2F.TryGetAttributeOffsetAndType(AZ::Vertex::AttributeUsage::TexCoord, 2, offset, type));
}
TEST_F(VertexFormatTest, GetAttributeByteLength_MatchesExpected)
{
AZ::Vertex::Format vertexFormatP3F_C4B_T2F(eVF_P3F_C4B_T2F);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeByteLength(AZ::Vertex::AttributeUsage::Position), AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float32_3)].byteSize);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeByteLength(AZ::Vertex::AttributeUsage::Color), AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Byte_4)].byteSize);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeByteLength(AZ::Vertex::AttributeUsage::TexCoord), AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float32_2)].byteSize);
EXPECT_EQ(vertexFormatP3F_C4B_T2F.GetAttributeByteLength(AZ::Vertex::AttributeUsage::Normal), 0);
AZ::Vertex::Format vertexFormatP3S_C4B_T2S(eVF_P3S_C4B_T2S);
EXPECT_EQ(vertexFormatP3S_C4B_T2S.GetAttributeByteLength(AZ::Vertex::AttributeUsage::Position), AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float16_4)].byteSize);// vec3f16 is backed by a CryHalf4, so 16 bit positions use Float16_4
EXPECT_EQ(vertexFormatP3S_C4B_T2S.GetAttributeByteLength(AZ::Vertex::AttributeUsage::Color), AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Byte_4)].byteSize);
EXPECT_EQ(vertexFormatP3S_C4B_T2S.GetAttributeByteLength(AZ::Vertex::AttributeUsage::TexCoord), AZ::Vertex::AttributeTypeDataTable[static_cast<uint8>(AZ::Vertex::AttributeType::Float16_2)].byteSize);
EXPECT_EQ(vertexFormatP3S_C4B_T2S.GetAttributeByteLength(AZ::Vertex::AttributeUsage::Normal), 0);
}
TEST_F(VertexFormatTest, Has16BitFloatPosition_MatchesExpected)
{
// Vertex formats with 16 bit positions should return true
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3S_C4B_T2S).Has16BitFloatPosition());
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3S_C4B_T2S_T2S).Has16BitFloatPosition());
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3S_N4B_C4B_T2S).Has16BitFloatPosition());
// Vertex formats with 32 bit positions should return false
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T2F).Has16BitFloatPosition());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T2F_T2F).Has16BitFloatPosition());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T4B_N3F2).Has16BitFloatPosition());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_T3F).Has16BitFloatPosition());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T2S).Has16BitFloatPosition());
// Vertex formats with no positions should return false
EXPECT_FALSE(AZ::Vertex::Format(eVF_T2F).Has16BitFloatPosition());
EXPECT_FALSE(AZ::Vertex::Format(eVF_W4B_I4S).Has16BitFloatPosition());
}
TEST_F(VertexFormatTest, Has16BitFloatTextureCoordinates_MatchesExpected)
{
// Vertex formats with 16 bit texture coordinates should return true
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3S_C4B_T2S).Has16BitFloatTextureCoordinates());
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3S_C4B_T2S_T2S).Has16BitFloatTextureCoordinates());
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3F_C4B_T2S).Has16BitFloatTextureCoordinates());
EXPECT_TRUE(AZ::Vertex::Format(eVF_C4B_T2S).Has16BitFloatTextureCoordinates());
// Vertex formats with 32 bit texture coordinates should return false
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T2F).Has16BitFloatTextureCoordinates());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T2F_T2F).Has16BitFloatTextureCoordinates());
EXPECT_FALSE(AZ::Vertex::Format(eVF_T2F).Has16BitFloatTextureCoordinates());
// Vertex formats with no texture coordinates should return false
EXPECT_FALSE(AZ::Vertex::Format(eVF_W4B_I4S).Has16BitFloatTextureCoordinates());
}
TEST_F(VertexFormatTest, Has32BitFloatTextureCoordinates_MatchesExpected)
{
// Vertex formats with 16 bit texture coordinates should return false
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3S_C4B_T2S).Has32BitFloatTextureCoordinates());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3S_C4B_T2S_T2S).Has32BitFloatTextureCoordinates());
EXPECT_FALSE(AZ::Vertex::Format(eVF_P3F_C4B_T2S).Has32BitFloatTextureCoordinates());
EXPECT_FALSE(AZ::Vertex::Format(eVF_C4B_T2S).Has32BitFloatTextureCoordinates());
// Vertex formats with 32 bit texture coordinates should return true
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3F_C4B_T2F).Has32BitFloatTextureCoordinates());
EXPECT_TRUE(AZ::Vertex::Format(eVF_P3F_C4B_T2F_T2F).Has32BitFloatTextureCoordinates());
EXPECT_TRUE(AZ::Vertex::Format(eVF_T2F).Has32BitFloatTextureCoordinates());
// Vertex formats with no texture coordinates should return false
EXPECT_FALSE(AZ::Vertex::Format(eVF_W4B_I4S).Has32BitFloatTextureCoordinates());
}
TEST_F(VertexFormatTest, VertFormatForComponents_StandardWithOneUVSet_eVF_P3S_C4B_T2S)
{
// Standard vertex format
bool hasTextureCoordinate = true;
bool hasTextureCoordinate2 = false;
bool isParticle = false;
bool hasNormal = false;
EXPECT_EQ(AZ::Vertex::VertFormatForComponents(false, hasTextureCoordinate, hasTextureCoordinate2, isParticle, hasNormal), eVF_P3S_C4B_T2S);
}
TEST_F(VertexFormatTest, VertFormatForComponents_StandardWithTwoUVSets_eVF_P3F_C4B_T2F_T2F)
{
// Multi-uv set vertex format
bool hasTextureCoordinate = true;
bool hasTextureCoordinate2 = true;
bool isParticle = false;
bool hasNormal = false;
EXPECT_EQ(AZ::Vertex::VertFormatForComponents(false, hasTextureCoordinate, hasTextureCoordinate2, isParticle, hasNormal), eVF_P3F_C4B_T2F_T2F);
}
TEST_F(VertexFormatTest, VertFormatForComponents_IsParticle_eVF_P3F_C4B_T4B_N3F2)
{
// Particle vertex format
bool hasTextureCoordinate = true;
bool hasTextureCoordinate2 = false;
bool isParticle = true;
bool hasNormal = false;
EXPECT_EQ(AZ::Vertex::VertFormatForComponents(false, hasTextureCoordinate, hasTextureCoordinate2, isParticle, hasNormal), eVF_P3F_C4B_T4B_N3F2);
}
TEST_F(VertexFormatTest, VertFormatForComponents_HasNormal_eVF_P3S_N4B_C4B_T2S)
{
// Vertex format with normals
bool hasTextureCoordinate = true;
bool hasTextureCoordinate2 = false;
bool isParticle = false;
bool hasNormal = true;
EXPECT_EQ(AZ::Vertex::VertFormatForComponents(false, hasTextureCoordinate, hasTextureCoordinate2, isParticle, hasNormal), eVF_P3S_N4B_C4B_T2S);
}
// Instantiate tests
// Start with 1 to skip eVF_Unknown
INSTANTIATE_TEST_CASE_P(EVertexFormatValues, VertexFormatTest, ::testing::Range<int>(1, eVF_Max));
// Start with 1 to skip eVF_Unknown, up to but not including eVF_Max - 1 so we always know that the current value + 1 is within the range of valid vertex formats
INSTANTIATE_TEST_CASE_P(EVertexFormatValues, VertexFormatComparisonTest, ::testing::Range<int>(1, eVF_Max - 1));
| 38.300373 | 285 | 0.716182 | [
"vector"
] |
3b446beeb9c4502b09c933aa37f66a57f6b83d4a | 1,990 | hpp | C++ | 2019/day17/cpp/include/asci.hpp | ivobatkovic/advent-of-code | e43489bcd2307f0f3ac8b0ec4e850f0a201f9944 | [
"MIT"
] | 3 | 2019-12-14T16:24:50.000Z | 2020-12-06T16:40:13.000Z | 2019/day17/cpp/include/asci.hpp | ivobatkovic/advent-of-code | e43489bcd2307f0f3ac8b0ec4e850f0a201f9944 | [
"MIT"
] | 4 | 2019-12-03T14:18:13.000Z | 2020-12-03T08:29:32.000Z | 2019/day17/cpp/include/asci.hpp | ivobatkovic/advent-of-code | e43489bcd2307f0f3ac8b0ec4e850f0a201f9944 | [
"MIT"
] | 2 | 2019-12-06T07:25:57.000Z | 2020-12-08T12:42:37.000Z | #ifndef _ASCI_H_
#define _ASCI_H_
#include <map>
#include <utility>
#include "2019/day5/cpp/include/intcode.hpp"
class Asci {
public:
std::string m_file_name;
Intcode m_intcode;
std::map<std::pair<int, int>, int> m_mp;
/**
* @brief Construct a new Asci object
*
* @param file_name
*/
Asci(std::string file_name);
/**
* @brief Initialize the map
*
* @return std::map<std::pair<int, int>, int>
*/
std::map<std::pair<int, int>, int> get_map();
/**
* @brief Find all intersections on the map
*
* @param print_map
* @return int
*/
int compute_intersections(bool print_map = true);
/**
* @brief Print map
*
*/
void print_map();
/**
* @brief Go through the map and figure out starting pose
*
* @param x
* @param y
* @param theta
*/
void find_start_pose(int &x, int &y, double &theta);
/**
* @brief Use the starting pose to prone the map and return the input
* instructions needed to reach the end
*
* @return std::string
*/
std::string traverse_scaffold();
/**
* @brief Compute the routine and sub-routines A,B,C
*
* @param routine
* @param A
* @param B
* @param C
*/
void find_movement_routine(std::string &routine, std::string &A,
std::string &B, std::string &C);
/**
* @brief Compute the intcode input
*
* @param print_iterations
* @return std::vector<int64_t>
*/
std::vector<int64_t> construct_input(bool print_iterations = false);
/**
* @brief Solve part two by using the input routine and subroutines
*
* @param print_iterations
* @return int
*/
int collect_dust(bool print_iterations = false);
/**
* @brief Print the robot collecting dust
*
* @return * int
*/
int print_video_feed();
/**
* @brief Catch a ctrl-c event
*
* @param s
*/
[[noreturn]] static void catch_ctrlc(int s);
};
#endif
#ifndef SOURCE_DIR
#define SOURCE_DIR ".."
#endif | 18.773585 | 71 | 0.607538 | [
"object",
"vector"
] |
3b462307f43db207f730abd663cb94bc3371a0e1 | 4,304 | cpp | C++ | master/geometrize-master/geometrize-master/geometrize/dialog/scriptconsole.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | master/geometrize-master/geometrize-master/geometrize/dialog/scriptconsole.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | master/geometrize-master/geometrize-master/geometrize/dialog/scriptconsole.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | #include "scriptconsole.h"
#include "ui_scriptconsole.h"
#include <QEvent>
#include "chaiscript/chaiscript.hpp"
#include "logger/logger.h"
#include "logger/logmessageevents.h"
#include "script/scriptrunner.h"
#include "script/scriptutil.h"
namespace geometrize
{
namespace dialog
{
class ScriptConsole::ScriptConsoleImpl
{
public:
ScriptConsoleImpl(ScriptConsole* pQ) : q{pQ}, ui{std::make_unique<Ui::ScriptConsole>()}, m_engine{nullptr}
{
ui->setupUi(q);
ui->outputView->append("ChaiScript " + QString(chaiscript::compiler_name));
ui->outputView->append(tr("Type 'help' in console for a list of commands", "Instructional text shown in the command/scripting console. The 'help' string should not be translated"));
populateUi();
connect(ui->commandLine, &geometrize::dialog::CommandLineEdit::signal_commandSubmitted, [this](const std::string& command) {
ui->outputView->append(QString::fromStdString(command));
if(command.empty()) {
return;
}
if(m_engine != nullptr) {
if(command == "help") {
const std::vector<std::string> functions{script::getEngineFunctionNames(*m_engine)};
for(const std::string& f : functions) {
append(QString::fromStdString(f));
}
} else if(command == "clearHistory") {
ui->commandLine->clearHistory();
} else if(command == "history") {
const std::vector<std::string> history{ui->commandLine->getHistory()};
for(const std::string& command : history) {
ui->outputView->append(QString::fromStdString(command));
}
} else if(command == "clear") {
ui->outputView->clear();
} else {
script::runScript(command, *m_engine);
}
}
});
}
ScriptConsoleImpl operator=(const ScriptConsoleImpl&) = delete;
ScriptConsoleImpl(const ScriptConsoleImpl&) = delete;
~ScriptConsoleImpl()
{
}
void setEngine(chaiscript::ChaiScript* engine)
{
m_engine = engine;
setCompletionList(engine);
}
std::vector<std::string> getHistory() const
{
return ui->commandLine->getHistory();
}
void setHistory(const std::vector<std::string>& history)
{
ui->commandLine->setHistory(history);
}
void append(const QString& message)
{
ui->outputView->append(message);
}
void onLanguageChange()
{
ui->retranslateUi(q);
populateUi();
}
private:
void populateUi()
{
}
void setCompletionList(chaiscript::ChaiScript* engine)
{
if(m_engine == nullptr) {
ui->commandLine->setCompletionList({});
} else {
ui->commandLine->setCompletionList(script::getEngineFunctionNames(*engine));
}
}
ScriptConsole* q;
std::unique_ptr<Ui::ScriptConsole> ui;
chaiscript::ChaiScript* m_engine;
std::vector<std::string> m_history;
};
ScriptConsole::ScriptConsole(QWidget* parent) : QWidget(parent), d{std::make_unique<ScriptConsole::ScriptConsoleImpl>(this)}
{
}
ScriptConsole::~ScriptConsole()
{
}
void ScriptConsole::setEngine(chaiscript::ChaiScript* engine)
{
d->setEngine(engine);
}
std::vector<std::string> ScriptConsole::getHistory() const
{
return d->getHistory();
}
void ScriptConsole::setHistory(const std::vector<std::string>& history)
{
d->setHistory(history);
}
bool ScriptConsole::event(QEvent* event)
{
if(event->type() == geometrize::log::LogMessageEvent::textualWidgetEventType) {
geometrize::log::TextualWidgetMessageEvent* message{static_cast<geometrize::log::TextualWidgetMessageEvent*>(event)};
d->append(message->getMessage());
return true;
} else {
return QWidget::event(event);
}
}
void ScriptConsole::changeEvent(QEvent* event)
{
if (event->type() == QEvent::LanguageChange) {
d->onLanguageChange();
}
QWidget::changeEvent(event);
}
const std::string ScriptConsole::launchConsoleHistoryFilename = "launch_console_command_history.json";
}
}
| 26.732919 | 189 | 0.613383 | [
"vector"
] |
8dca3aa60bed98bf68122586169b306e796e0a7b | 5,862 | cpp | C++ | tcb/src/v20180608/model/CloudBaseRunVolumeMount.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | tcb/src/v20180608/model/CloudBaseRunVolumeMount.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | tcb/src/v20180608/model/CloudBaseRunVolumeMount.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcb/v20180608/model/CloudBaseRunVolumeMount.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcb::V20180608::Model;
using namespace std;
CloudBaseRunVolumeMount::CloudBaseRunVolumeMount() :
m_nameHasBeenSet(false),
m_mountPathHasBeenSet(false),
m_readOnlyHasBeenSet(false),
m_nfsVolumesHasBeenSet(false)
{
}
CoreInternalOutcome CloudBaseRunVolumeMount::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Name") && !value["Name"].IsNull())
{
if (!value["Name"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CloudBaseRunVolumeMount.Name` IsString=false incorrectly").SetRequestId(requestId));
}
m_name = string(value["Name"].GetString());
m_nameHasBeenSet = true;
}
if (value.HasMember("MountPath") && !value["MountPath"].IsNull())
{
if (!value["MountPath"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CloudBaseRunVolumeMount.MountPath` IsString=false incorrectly").SetRequestId(requestId));
}
m_mountPath = string(value["MountPath"].GetString());
m_mountPathHasBeenSet = true;
}
if (value.HasMember("ReadOnly") && !value["ReadOnly"].IsNull())
{
if (!value["ReadOnly"].IsBool())
{
return CoreInternalOutcome(Core::Error("response `CloudBaseRunVolumeMount.ReadOnly` IsBool=false incorrectly").SetRequestId(requestId));
}
m_readOnly = value["ReadOnly"].GetBool();
m_readOnlyHasBeenSet = true;
}
if (value.HasMember("NfsVolumes") && !value["NfsVolumes"].IsNull())
{
if (!value["NfsVolumes"].IsArray())
return CoreInternalOutcome(Core::Error("response `CloudBaseRunVolumeMount.NfsVolumes` is not array type"));
const rapidjson::Value &tmpValue = value["NfsVolumes"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
CloudBaseRunNfsVolumeSource item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_nfsVolumes.push_back(item);
}
m_nfsVolumesHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void CloudBaseRunVolumeMount::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_nameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Name";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator);
}
if (m_mountPathHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "MountPath";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_mountPath.c_str(), allocator).Move(), allocator);
}
if (m_readOnlyHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ReadOnly";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_readOnly, allocator);
}
if (m_nfsVolumesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "NfsVolumes";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_nfsVolumes.begin(); itr != m_nfsVolumes.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
}
string CloudBaseRunVolumeMount::GetName() const
{
return m_name;
}
void CloudBaseRunVolumeMount::SetName(const string& _name)
{
m_name = _name;
m_nameHasBeenSet = true;
}
bool CloudBaseRunVolumeMount::NameHasBeenSet() const
{
return m_nameHasBeenSet;
}
string CloudBaseRunVolumeMount::GetMountPath() const
{
return m_mountPath;
}
void CloudBaseRunVolumeMount::SetMountPath(const string& _mountPath)
{
m_mountPath = _mountPath;
m_mountPathHasBeenSet = true;
}
bool CloudBaseRunVolumeMount::MountPathHasBeenSet() const
{
return m_mountPathHasBeenSet;
}
bool CloudBaseRunVolumeMount::GetReadOnly() const
{
return m_readOnly;
}
void CloudBaseRunVolumeMount::SetReadOnly(const bool& _readOnly)
{
m_readOnly = _readOnly;
m_readOnlyHasBeenSet = true;
}
bool CloudBaseRunVolumeMount::ReadOnlyHasBeenSet() const
{
return m_readOnlyHasBeenSet;
}
vector<CloudBaseRunNfsVolumeSource> CloudBaseRunVolumeMount::GetNfsVolumes() const
{
return m_nfsVolumes;
}
void CloudBaseRunVolumeMount::SetNfsVolumes(const vector<CloudBaseRunNfsVolumeSource>& _nfsVolumes)
{
m_nfsVolumes = _nfsVolumes;
m_nfsVolumesHasBeenSet = true;
}
bool CloudBaseRunVolumeMount::NfsVolumesHasBeenSet() const
{
return m_nfsVolumesHasBeenSet;
}
| 29.457286 | 151 | 0.679973 | [
"vector",
"model"
] |
8dd38e96581fe6cd40b598683071ccb245887ad1 | 2,263 | cpp | C++ | 1-100/94. Binary Tree Inorder Traversal.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1-100/94. Binary Tree Inorder Traversal.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1-100/94. Binary Tree Inorder Traversal.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// version 1 Generic version
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
stack<pair<TreeNode *, bool>> s;
vector<int> ret;
if (!root) {
return ret;
}
s.emplace(root, false);
while (!s.empty()) {
auto cur = s.top();
s.pop();
if (cur.second) {
ret.push_back(cur.first->val);
} else {
if (cur.first->right) {
s.emplace(cur.first->right, false);
}
s.emplace(cur.first, true);
if (cur.first->left) {
s.emplace(cur.first->left, false);
}
}
}
return ret;
}
};
// version 2
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode *> s;
vector<int> ret;
if (!root) {
return ret;
}
auto cur = root;
s.push(cur);
while (cur->left) {
s.push(cur->left);
cur = cur->left;
}
while (!s.empty()) {
auto cur = s.top();
s.pop();
ret.push_back(cur->val);
if (cur->right) {
s.push(cur->right);
cur = s.top();
while (cur->left) {
s.push(cur->left);
cur = cur->left;
}
}
}
return ret;
}
};
// version 3
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
stack<TreeNode *> s;
vector<int> ret;
if (!root)
return ret;
TreeNode *last = root;
if (root->right)
s.push(root->right);
s.push(root);
if (root->left)
s.push(root->left);
while (!s.empty()) {
auto cur = s.top();
s.pop();
if (last->left == cur || last->right == cur) {
if (cur->right)
s.push(cur->right);
s.push(cur);
if (cur->left)
s.push(cur->left);
} else {
ret.push_back(cur->val);
}
last = cur;
}
return ret;
}
};
| 20.205357 | 59 | 0.496244 | [
"vector"
] |
8dd4909b2d5e2ab4ac7c4ab7c7c7892ebcc14122 | 1,265 | cpp | C++ | 11327.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 11327.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | 11327.cpp | felikjunvianto/kfile-uvaoj-submissions | 5bd8b3b413ca8523abe412b0a0545f766f70ce63 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
int prime[510],x,y,N;
vector<int> num;
LL K,tot;
int euler(int N)
{
if(N==1) return 2;
int ans = N;
for(int i=0;i<num.size();i++) if(N%num[i]==0)
{
ans-=ans/num[i];
while(N%num[i]==0) N/=num[i];
if(N==1) break;
}
if(N!=1) ans-=ans/N;
return ans;
}
int main()
{
memset(prime,true,sizeof(prime));
for(x=2;x*x<=500;x++) if(prime[x])
for(y=2;x*y<=500;y++) prime[x*y]=false;
for(x=2;x<=500;x++) if(prime[x]) num.pb(x);
while(1)
{
scanf("%lld",&K);
if(!K) break;
tot=0LL;
N=1;
y=euler(N);
while(tot+(LL)y<K)
{
tot+=(LL)y;
//cout << tot << " " << K << endl;
N++;
y=euler(N);
}
for(x=0;x<N;x++) if(__gcd(x,N)==1)
{
tot++;
if(tot==K) break;
}
printf("%d/%d\n",x,N);
}
return 0;
}
| 16.428571 | 47 | 0.549407 | [
"vector"
] |
8dd84faa932f59add14a55999bd0dcdf91e758d0 | 2,119 | hpp | C++ | sources/Framework/Tools/spStoryboardEvent.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/Framework/Tools/spStoryboardEvent.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/Framework/Tools/spStoryboardEvent.hpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2020-02-15T09:17:41.000Z | 2020-05-21T14:10:40.000Z | /*
* Storyboard trigger header
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#ifndef __SP_STORYBOARD_EVENT_H__
#define __SP_STORYBOARD_EVENT_H__
#include "Base/spStandard.hpp"
#ifdef SP_COMPILE_WITH_STORYBOARD
#include "Framework/Tools/spStoryboardTrigger.hpp"
#include "Base/spTimer.hpp"
#include <vector>
namespace sp
{
namespace tool
{
/**
A storyboard operator connects events and facts with a consequence.
\see StoryboardEvent, StoryboardFact, StoryboardConsequence
\since Version 3.2
*/
class SP_EXPORT Event : public Trigger
{
public:
virtual ~Event();
/* === Functions === */
virtual void update() = 0;
protected:
Event();
};
class SP_EXPORT EventTimer : public Event
{
public:
EventTimer(u64 Duration);
~EventTimer();
/* === Functions === */
void update();
void onTriggered();
private:
io::Timer Timer_;
};
class SP_EXPORT TriggerCounter : public Trigger
{
public:
TriggerCounter(u32 Counter = 1);
~TriggerCounter();
/* === Functions === */
bool canTrigger() const;
void onTriggered();
void reset();
void reset(u32 Counter);
private:
/* === Members === */
u32 OrigCounter_;
u32 Counter_;
};
class SP_EXPORT TriggerSwitch : public Trigger
{
public:
TriggerSwitch(u32 Selection = 0);
~TriggerSwitch();
/* === Functions === */
void onTriggered();
void onUntriggered();
private:
/* === Members === */
u32 Selection_;
};
} // /namespace tool
} // /namespace sp
#endif
#endif
// ================================================================================
| 16.05303 | 85 | 0.505427 | [
"vector"
] |
8dd8a45ece002f9da04624ccdae68911951ad7a1 | 734 | cpp | C++ | codes/Leetcode/leetcode023.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/Leetcode/leetcode023.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/Leetcode/leetcode023.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode head = ListNode(0);
ListNode* ans = &head;
ListNode* move = ans;
priority_queue<pair<int, int>> que;
for (int i = 0; i < lists.size(); i++) {
if (lists[i] != NULL)
que.push(make_pair(-lists[i]->val, i));
}
while (!que.empty()) {
int t = que.top().second; que.pop();
move->next = lists[t];
lists[t] = lists[t]->next;
if (lists[t] != NULL)
que.push(make_pair(-lists[t]->val, t));
move = move->next;
}
return ans->next;
}
};
| 21.588235 | 51 | 0.551771 | [
"vector"
] |
8dd8cd1626186f4a4d625bb79264c4c61da56cae | 4,773 | cpp | C++ | Deprecated/Project1/inspectorwidget.cpp | jesusdz/AGP | fc6401f1432313324d6fd07f7aeec411c0857276 | [
"Unlicense"
] | null | null | null | Deprecated/Project1/inspectorwidget.cpp | jesusdz/AGP | fc6401f1432313324d6fd07f7aeec411c0857276 | [
"Unlicense"
] | null | null | null | Deprecated/Project1/inspectorwidget.cpp | jesusdz/AGP | fc6401f1432313324d6fd07f7aeec411c0857276 | [
"Unlicense"
] | null | null | null | #include "inspectorwidget.h"
#include "entitywidget.h"
#include "transformwidget.h"
#include "shaperendererwidget.h"
#include "backgroundrendererwidget.h"
#include "componentwidget.h"
#include "scene.h"
#include "mainwindow.h"
#include <QLayout>
#include <QVBoxLayout>
#include <QSpacerItem>
#include <QPushButton>
InspectorWidget::InspectorWidget(QWidget *parent) :
QWidget(parent)
{
// Create subwidgets independently
transformWidget = new TransformWidget;
shapeRendererWidget = new ShapeRendererWidget;
backgroundRendererWidget = new BackgroundRendererWidget;
QSpacerItem *spacer = new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Expanding);
// Add all elements to the layout
entityWidget = new EntityWidget;
transformComponentWidget = new ComponentWidget;
transformComponentWidget->setWidget(transformWidget);
shapeRendererComponentWidget = new ComponentWidget;
shapeRendererComponentWidget->setWidget(shapeRendererWidget);
backgroundRendererComponentWidget = new ComponentWidget;
backgroundRendererComponentWidget->setWidget(backgroundRendererWidget);
buttonAddShapeRenderer = new QPushButton("Add Shape Renderer");
buttonAddBackgroundRenderer = new QPushButton("Add Background Renderer");
// Create a vertical layout for this widget
layout = new QVBoxLayout;
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(entityWidget);
layout->addWidget(transformComponentWidget);
layout->addWidget(shapeRendererComponentWidget);
layout->addWidget(backgroundRendererComponentWidget);
layout->addWidget(buttonAddShapeRenderer);
layout->addWidget(buttonAddBackgroundRenderer);
layout->addItem(spacer);
// Set the layout for this widget
setLayout(layout);
showEntity(nullptr);
connect(entityWidget, SIGNAL(entityChanged(Entity*)), this, SLOT(onEntityChanged(Entity *)));
connect(transformWidget, SIGNAL(componentChanged(Component*)), this, SLOT(onComponentChanged(Component *)));
connect(shapeRendererWidget, SIGNAL(componentChanged(Component*)), this, SLOT(onComponentChanged(Component *)));
connect(backgroundRendererWidget, SIGNAL(componentChanged(Component*)), this, SLOT(onComponentChanged(Component *)));
connect(entityWidget, SIGNAL(entityChanged(Entity*)), this, SLOT(onEntityChanged(Entity *)));
connect(buttonAddShapeRenderer, SIGNAL(clicked()), this, SLOT(onAddShapeRendererClicked()));
connect(buttonAddBackgroundRenderer, SIGNAL(clicked()), this, SLOT(onAddBackgroundRendererClicked()));
connect(shapeRendererComponentWidget, SIGNAL(removeClicked(Component*)), this, SLOT(onRemoveComponent(Component *)));
connect(backgroundRendererComponentWidget, SIGNAL(removeClicked(Component*)), this, SLOT(onRemoveComponent(Component *)));
}
InspectorWidget::~InspectorWidget()
{
}
void InspectorWidget::showEntity(Entity *e)
{
entity = e;
updateLayout();
}
void InspectorWidget::onEntityChanged(Entity *entity)
{
emit entityChanged(entity);
}
void InspectorWidget::onComponentChanged(Component *)
{
emit entityChanged(entity);
}
void InspectorWidget::onAddShapeRendererClicked()
{
if (entity == nullptr) return;
entity->addShapeRendererComponent();
updateLayout();
emit entityChanged(entity);
}
void InspectorWidget::onAddBackgroundRendererClicked()
{
if (entity == nullptr) return;
entity->addBackgroundRendererComponent();
updateLayout();
emit entityChanged(entity);
}
void InspectorWidget::onRemoveComponent(Component *c)
{
if (entity == nullptr) return;
entity->removeComponent(c);
updateLayout();
emit entityChanged(entity);
}
void InspectorWidget::updateLayout()
{
entityWidget->setVisible(entity != nullptr);
transformComponentWidget->setVisible(entity != nullptr && entity->transform != nullptr);
shapeRendererComponentWidget->setVisible(entity != nullptr && entity->shapeRenderer != nullptr);
backgroundRendererComponentWidget->setVisible(entity != nullptr && entity->backgroundRenderer != nullptr);
buttonAddShapeRenderer->setVisible(entity != nullptr && entity->shapeRenderer == nullptr);
buttonAddBackgroundRenderer->setVisible(entity != nullptr && entity->backgroundRenderer == nullptr);
if (entity == nullptr) return;
transformComponentWidget->setComponent(entity->transform);
shapeRendererComponentWidget->setComponent(entity->shapeRenderer);
backgroundRendererComponentWidget->setComponent(entity->backgroundRenderer);
entityWidget->setEntity(entity);
transformWidget->setTransform(entity->transform);
shapeRendererWidget->setShapeRenderer(entity->shapeRenderer);
backgroundRendererWidget->setBackgroundRenderer(entity->backgroundRenderer);
}
| 36.715385 | 126 | 0.764299 | [
"shape",
"transform"
] |
8ddf92dea4a05405e01413295ad3fa486454ccab | 459 | hpp | C++ | BookingManager.hpp | Aliw7979/UTRIP | 7c6153fb185f7dc3a87ac456157319d83dd8669f | [
"MIT"
] | null | null | null | BookingManager.hpp | Aliw7979/UTRIP | 7c6153fb185f7dc3a87ac456157319d83dd8669f | [
"MIT"
] | null | null | null | BookingManager.hpp | Aliw7979/UTRIP | 7c6153fb185f7dc3a87ac456157319d83dd8669f | [
"MIT"
] | null | null | null | #ifndef BOOKINGMANAGER_H
#define BOOKINGMANAGER_H "BOOKINGMANAGER_H"
#include"BookedItem.hpp"
#include<vector>
class BookingManager
{
public:
void add_item(std::string id_init,
std::string hotel_id_init, std::string room_type_init,
int quantity_init, int cost_init,
int check_in_init, int check_out_init);
void delete_item(std::string id);
protected:
std::vector<BookedItem> items;
};
#endif | 25.5 | 72 | 0.688453 | [
"vector"
] |
8de487330bed2d88a43fe208d023102208e1325a | 1,057 | hpp | C++ | Packt_CreatingGamesWithAI/BattleCity/BattleCityGameWorld.hpp | mcihanozer/Hands-On-Game-AI-Development | 36453b678cfeb644aeeccf4e77069fa6531684d2 | [
"MIT"
] | 6 | 2018-12-04T04:39:42.000Z | 2022-03-01T09:36:39.000Z | Packt_CreatingGamesWithAI/BattleCity/BattleCityGameWorld.hpp | mcihanozer/Hands-On-Game-AI-Development | 36453b678cfeb644aeeccf4e77069fa6531684d2 | [
"MIT"
] | 1 | 2019-07-25T19:52:35.000Z | 2019-07-25T19:52:35.000Z | Packt_CreatingGamesWithAI/BattleCity/BattleCityGameWorld.hpp | PacktPublishing/Hands-On-Game-AI-Development | 27328e4658bfd1606abe51cc14a8adbe8c752d76 | [
"MIT"
] | 4 | 2018-11-08T09:29:02.000Z | 2020-05-09T21:21:28.000Z | //
// GameWorld.hpp
// Packt_CreatingGamesWithAI
//
// Created by Cihan Ozer on 17/05/2018.
// Copyright © 2018 Cihan Ozer. All rights reserved.
//
#ifndef GameWorld_hpp
#define GameWorld_hpp
#include "AbstractGameWorld.hpp"
#include "Player.hpp"
#include "TankAI.hpp"
#include "Wall.hpp"
class BattleCityGameWorld : public AbstractGameWorld
{
public:
BattleCityGameWorld();
virtual ~BattleCityGameWorld();
std::vector<Texture*>& getObjectTextures() override;
void callOnFrame() override;
protected:
void generateTerrain() override;
void generateNPCs() override;
void generatePlayers() override;
private:
std::string mTankImagePath;
std::unique_ptr< LegacyCollisionGrid<LegacyCollider> > mLegacyCollisionGrid;
std::vector<VisualObject*> mTerrainVector;
std::vector<MovingObject*> mNpcVector;
std::unique_ptr<Player> mPlayer;
std::vector< std::unique_ptr<TankAI>> mAIs;
std::vector< std::unique_ptr<Wall> > mWalls;
};
#endif /* GameWorld_hpp */
| 20.326923 | 80 | 0.694418 | [
"vector"
] |
8dedf4ea6b024b634c4cbe2cc4b1c3fc8a2fc83e | 13,865 | cpp | C++ | project-2/src/application.cpp | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | [
"MIT"
] | 1 | 2022-02-08T10:39:40.000Z | 2022-02-08T10:39:40.000Z | project-2/src/application.cpp | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | [
"MIT"
] | null | null | null | project-2/src/application.cpp | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | [
"MIT"
] | null | null | null | #include "application.h"
#include "gl_utils.h"
#include "dynamic_scene/ambient_light.h"
#include "dynamic_scene/directional_light.h"
#include "dynamic_scene/area_light.h"
#include "dynamic_scene/point_light.h"
#include "dynamic_scene/spot_light.h"
#include "dynamic_scene/sphere.h"
#include "dynamic_scene/mesh.h"
#include "CS248/lodepng.h"
//#define GLFW_INCLUDE_GLCOREARB
#include "GLFW/glfw3.h"
#include <sstream>
#include <chrono>
#include <thread>
using namespace std;
namespace CS248 {
using Collada::CameraInfo;
using Collada::LightInfo;
using Collada::PolymeshInfo;
using Collada::SceneInfo;
using Collada::SphereInfo;
Application::Application() {
scene = nullptr;
}
Application::~Application() {
if (scene != nullptr)
delete scene;
}
void Application::init() {
if (scene != nullptr) {
delete scene;
scene = nullptr;
}
const GLubyte* vendor = glGetString(GL_VENDOR);
const GLubyte* version = glGetString(GL_VERSION);
checkGLError("before OpenGL version detection");
printf("Detected OpenGL version=%s, vendor=%s\n", version, vendor);
// GLint num_exts;
// glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts);
// printf("Detected OpenGL Extensions:\n");
// for (GLint i = 0; i < num_exts; ++i) {
// printf("%s\n", glGetStringi(GL_EXTENSIONS, i));
// }
checkGLError("begin Application::init");
textManager.init(use_hdpi);
textColor = Color(1.0, 1.0, 1.0);
// Setup all the basic internal state to default values,
// as well as some basic OpenGL state (like depth testing
// and lighting).
// Set the integer bit vector representing which keys are down.
leftDown = false;
rightDown = false;
middleDown = false;
showHUD = true;
scene = nullptr;
visualizeShadowMap = false;
discoModeOn = false;
// Make a dummy camera so resize() doesn't crash before the scene has been
// loaded.
// NOTE: there's a chicken-and-egg problem here, because load()
// requires init, and init requires init_camera (which is only called by
// load()).
screenW = screenH = 600; // Default value
CameraInfo cameraInfo;
cameraInfo.hFov = 20;
cameraInfo.vFov = 28;
cameraInfo.nClip = 0.1;
cameraInfo.fClip = 100;
camera.configure(cameraInfo, screenW, screenH);
canonicalCamera.configure(cameraInfo, screenW, screenH);
checkGLError("end of Application::init");
}
void Application::render() {
//printf("Top of application::render\n");
checkGLError("start of Application::render");
// Call resize() every time we draw, since it doesn't seem
// to get called by the Viewer upon initial window creation
// FIXME(kayvonf): look into and fix this
GLint view[4];
glGetIntegerv(GL_VIEWPORT, view);
if (view[2] != screenW || view[3] != screenH) {
resize(view[2], view[3]);
}
if (discoModeOn) {
scene->rotateSpotLights();
}
// pass 1, generate shadow map for the spotlights
if (scene->needsShadowPass()) {
for (int i=0; i<scene->getNumShadowedLights(); i++) {
scene->renderShadowPass(i);
}
}
// pass 2, beauty pass, render the scene (using the shadow map)
checkGLError("pre beauty pass");
glViewport(0, 0, screenW, screenH);
glClearColor(0., 0., 0., 0.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
if (visualizeShadowMap && scene->needsShadowPass()) {
scene->visualizeShadowMap();
} else {
scene->render();
if (showHUD)
drawHUD();
}
//printf("End of application::render\n");
checkGLError("end of Application::render");
}
void Application::resize(size_t w, size_t h) {
screenW = w;
screenH = h;
camera.setScreenSize(w, h);
textManager.resize(w, h);
}
string Application::name() {
return "Shader Assignment";
}
string Application::info() {
return "";
}
void Application::load(SceneInfo* sceneInfo) {
// save camera position to update camera control later
CameraInfo* camInfo;
Vector3D camPos, camDir;
vector<DynamicScene::SceneLight*> lights;
vector<DynamicScene::SceneObject*> objects;
vector<Collada::Node>& nodes = sceneInfo->nodes;
for (size_t i=0; i<nodes.size(); i++) {
Collada::Node& node = nodes[i];
Collada::Instance* instance = node.instance;
const Matrix4x4& transform = node.transform;
switch (instance->type) {
case Collada::Instance::CAMERA: {
// printf("Creating camera\n"); fflush(stdout);
camInfo = static_cast<CameraInfo*>(instance);
camPos = (transform * Vector4D(camInfo->pos, 1)).to3D();
camDir = (transform * Vector4D(camInfo->view_dir, 1)).to3D().unit();
initCamera(*camInfo, transform);
break;
}
case Collada::Instance::LIGHT: {
// printf("Creating light\n"); fflush(stdout);
lights.push_back(
initLight(static_cast<LightInfo&>(*instance), transform));
break;
}
case Collada::Instance::POLYMESH: {
// printf("Creating mesh\n"); fflush(stdout);
objects.push_back(
initPolymesh(static_cast<PolymeshInfo&>(*instance), transform));
break;
}
default:
// unsupported instance type
break;
}
}
// create the scene
scene = new DynamicScene::Scene(objects, lights, sceneInfo->base_shader_dir);
scene->setCamera(&camera);
// given the size of the scene, determine a "canonical" camera position that's
// outside the bounds of the scene's geometry
BBox bbox = scene->getBBox();
if (!bbox.empty()) {
Vector3D target = bbox.centroid();
canonicalViewDistance = bbox.extent.norm() / 2.0 * 1.5;
double viewDistance = canonicalViewDistance * 2;
double minViewDistance = canonicalViewDistance / 10.0;
double maxViewDistance = canonicalViewDistance * 20.0;
canonicalCamera.place(target, acos(camDir.y), atan2(camDir.x, camDir.z),
viewDistance, minViewDistance, maxViewDistance);
if (!camInfo->default_flag) {
target = camPos;
viewDistance = camInfo->view_dir.norm();
}
camera.place(target, acos(camDir.y), atan2(camDir.x, camDir.z),
viewDistance, minViewDistance, maxViewDistance);
setScrollRate();
}
}
void Application::initCamera(CameraInfo& cameraInfo, const Matrix4x4& transform) {
camera.configure(cameraInfo, screenW, screenH);
canonicalCamera.configure(cameraInfo, screenW, screenH);
}
void Application::resetCamera() {
camera.copyPlacement(canonicalCamera);
}
DynamicScene::SceneLight* Application::initLight(LightInfo& light, const Matrix4x4& transform) {
switch (light.light_type) {
case Collada::LightType::NONE:
break;
case Collada::LightType::AMBIENT:
return new DynamicScene::AmbientLight(light);
case Collada::LightType::DIRECTIONAL:
return new DynamicScene::DirectionalLight(light, transform);
case Collada::LightType::AREA:
return new DynamicScene::AreaLight(light, transform);
case Collada::LightType::POINT:
return new DynamicScene::PointLight(light, transform);
case Collada::LightType::SPOT:
return new DynamicScene::SpotLight(light, transform);
default:
break;
}
return nullptr;
}
/**
* The transform is assumed to be composed of translation, rotation, and
* scaling, where the scaling is uniform across the three dimensions; these
* assumptions are necessary to ensure the sphere is still spherical. Rotation
* is ignored since it's a sphere, translation is determined by transforming the
* origin, and scaling is determined by transforming an arbitrary unit vector.
*/
DynamicScene::SceneObject* Application::initPolymesh(PolymeshInfo& polymesh, const Matrix4x4& transform) {
return new DynamicScene::Mesh(polymesh, transform);
}
void Application::setScrollRate() {
scrollRate = canonicalViewDistance / 10;
}
void Application::cursor_event(float x, float y) {
if (leftDown && !middleDown && !rightDown) {
mouse1_dragged(x, y);
} else if (!leftDown && !middleDown && rightDown) {
mouse2_dragged(x, y);
} else if (!leftDown && !middleDown && !rightDown) {
mouse_moved(x, y);
}
mouseX = x;
mouseY = y;
}
void Application::scroll_event(float offset_x, float offset_y) {
camera.moveForward(-offset_y * scrollRate);
}
void Application::mouse_event(int key, int event, unsigned char mods) {
switch (event) {
case EVENT_PRESS:
switch (key) {
case MOUSE_LEFT:
mouse_pressed(LEFT);
break;
case MOUSE_RIGHT:
mouse_pressed(RIGHT);
break;
case MOUSE_MIDDLE:
mouse_pressed(MIDDLE);
break;
}
break;
case EVENT_RELEASE:
switch (key) {
case MOUSE_LEFT:
mouse_released(LEFT);
break;
case MOUSE_RIGHT:
mouse_released(RIGHT);
break;
case MOUSE_MIDDLE:
mouse_released(MIDDLE);
break;
}
break;
}
}
void Application::char_event(unsigned int ch) {
switch (ch) {
case 'v':
case 'V':
visualizeShadowMap = !visualizeShadowMap;
break;
case 'c':
case 'C':
printf("Current camera info:\n");
cout << "Pos: " << camera.getPosition() << endl;
cout << "Lookat: " << camera.getViewPoint() << endl;
cout << "Up: " << camera.getUpDir() << endl;
cout << "aspect_ratio: " << camera.getAspectRatio() << endl;
cout << "near_clip: " << camera.getNearClip() << endl;
cout << "far_clip: " << camera.getFarClip() << endl;
break;
case 'r':
case 'R':
resetCamera();
break;
case 's':
case 'S':
scene->reloadShaders();
break;
case 'd':
case 'D':
discoModeOn = !discoModeOn;
break;
}
}
void Application::keyboard_event(int key, int event, unsigned char mods) {
switch (key) {
case GLFW_KEY_TAB:
if (event == GLFW_PRESS)
showHUD = !showHUD;
break;
default:
break;
}
}
Vector3D Application::getMouseProjection(double dist) {
// get projection matrix from OpenGL stack.
GLdouble projection[16];
glGetDoublev(GL_PROJECTION_MATRIX, projection);
Matrix4x4 projectionMatrix(projection);
// get view matrix from OpenGL stack.
GLdouble modelview[16];
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
Matrix4x4 modelviewMatrix(modelview);
// ray in clip coordinates
double x = mouseX * 2 / screenW - 1;
double y = screenH - mouseY; // y is upside down
y = y * 2 / screenH - 1;
Vector4D rayClip(x, y, -1.0, 1.0);
// ray in eye coordinates
Vector4D rayEye = projectionMatrix.inv() * rayClip;
// ray is into the screen and not a point.
rayEye.z = -1.0;
rayEye.w = 0.0;
// ray in world coordinates
Vector4D rayWor4 = modelviewMatrix * rayEye;
Vector3D rayWor(rayWor4.x, rayWor4.y, rayWor4.z);
Vector3D rayOrig(camera.getPosition());
double t = dot(rayOrig, -rayWor);
if (std::isfinite(dist)) {
// If a distance was given, use that instead
rayWor = rayWor.unit();
t = dist;
}
Vector3D intersect = rayOrig + t * rayWor;
return intersect;
}
void Application::mouse_pressed(e_mouse_button b) {
switch (b) {
case LEFT:
leftDown = true;
break;
case RIGHT:
rightDown = true;
break;
case MIDDLE:
middleDown = true;
break;
}
}
void Application::mouse_released(e_mouse_button b) {
switch (b) {
case LEFT:
leftDown = false;
break;
case RIGHT:
rightDown = false;
break;
case MIDDLE:
middleDown = false;
break;
}
}
/*
When in edit mode and there is a selection, move the selection.
When in visualization mode, rotate.
*/
void Application::mouse1_dragged(float x, float y) {
float dx = (x - mouseX);
float dy = (y - mouseY);
camera.rotateBy(dy * (PI / screenH), dx * (PI / screenW));
}
/*
When the mouse is dragged with the right button held down, translate.
*/
void Application::mouse2_dragged(float x, float y) {
float dx = (x - mouseX);
float dy = (y - mouseY);
// don't negate y because up is down.
camera.moveBy(-dx, dy, canonicalViewDistance);
}
void Application::mouse_moved(float x, float y) {
y = screenH - y; // Because up is down.
// Converts x from [0, w] to [-1, 1], and similarly for y.
// Vector2D p(x * 2 / screenW - 1, y * 2 / screenH - 1);
Vector2D p(x, y);
//updateCamera();
}
/*
Matrix4x4 Application::getWorldTo3DH() {
Matrix4x4 P, M;
glGetDoublev(GL_PROJECTION_MATRIX, &P(0, 0));
glGetDoublev(GL_MODELVIEW_MATRIX, &M(0, 0));
return P * M;
}
*/
inline void Application::drawString(float x, float y, string str, size_t size, const Color& c) {
int line_index = textManager.add_line((x * 2 / screenW) - 1.0, (-y * 2 / screenH) + 1.0, str, size, c);
messages.push_back(line_index);
}
void Application::drawHUD() {
textManager.clear();
messages.clear();
const size_t size = 16;
const float x0 = use_hdpi ? screenW - 300 * 2 : screenW - 300;
const float y0 = use_hdpi ? 128 : 64;
const int inc = use_hdpi ? 48 : 24;
float y = y0 + inc - size;
textManager.render();
checkGLError("end Application::drawHUD");
}
} // namespace CS248
| 27.564612 | 107 | 0.62308 | [
"mesh",
"geometry",
"render",
"vector",
"transform"
] |
8dee779453be6d94fc90262e4e78f2c0c1819e2c | 40,575 | cpp | C++ | esidl/v8api/test/dom.test.cpp | rvedam/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 2 | 2020-11-30T18:38:20.000Z | 2021-06-07T07:44:03.000Z | esidl/v8api/test/dom.test.cpp | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 1 | 2019-01-14T03:09:45.000Z | 2019-01-14T03:09:45.000Z | esidl/v8api/test/dom.test.cpp | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <esjsapi.h>
#include <assert.h>
#include <iostream>
#include <org/w3c/dom/bootstrap/AnonXMLHttpRequestImp.h>
#include <org/w3c/dom/bootstrap/ApplicationCacheImp.h>
#include <org/w3c/dom/bootstrap/ArrayBufferImp.h>
#include <org/w3c/dom/bootstrap/ArrayBufferViewImp.h>
#include <org/w3c/dom/bootstrap/AttrImp.h>
#include <org/w3c/dom/bootstrap/AudioTrackImp.h>
#include <org/w3c/dom/bootstrap/AudioTrackListImp.h>
#include <org/w3c/dom/bootstrap/BarPropImp.h>
#include <org/w3c/dom/bootstrap/BeforeUnloadEventImp.h>
#include <org/w3c/dom/bootstrap/BlobCallbackImp.h>
#include <org/w3c/dom/bootstrap/BlobImp.h>
#include <org/w3c/dom/bootstrap/CSS2PropertiesImp.h>
#include <org/w3c/dom/bootstrap/CSSCharsetRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSColorComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSFontFaceRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSIdentifierComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSImportRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSKeywordComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSLengthComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSMapValueImp.h>
#include <org/w3c/dom/bootstrap/CSSMediaRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSNamespaceRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSPageRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSPercentageComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSPrimitiveValueImp.h>
#include <org/w3c/dom/bootstrap/CSSPropertyValueImp.h>
#include <org/w3c/dom/bootstrap/CSSPropertyValueListImp.h>
#include <org/w3c/dom/bootstrap/CSSRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSStringComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSStyleDeclarationImp.h>
#include <org/w3c/dom/bootstrap/CSSStyleDeclarationValueImp.h>
#include <org/w3c/dom/bootstrap/CSSStyleRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSStyleSheetImp.h>
#include <org/w3c/dom/bootstrap/CSSURLComponentValueImp.h>
#include <org/w3c/dom/bootstrap/CSSUnknownRuleImp.h>
#include <org/w3c/dom/bootstrap/CSSValueImp.h>
#include <org/w3c/dom/bootstrap/CSSValueListImp.h>
#include <org/w3c/dom/bootstrap/CanvasGradientImp.h>
#include <org/w3c/dom/bootstrap/CanvasPatternImp.h>
#include <org/w3c/dom/bootstrap/CanvasPixelArrayImp.h>
#include <org/w3c/dom/bootstrap/CanvasRenderingContext2DImp.h>
#include <org/w3c/dom/bootstrap/CaretPositionImp.h>
#include <org/w3c/dom/bootstrap/CharacterDataImp.h>
#include <org/w3c/dom/bootstrap/ClientRectImp.h>
#include <org/w3c/dom/bootstrap/ClientRectListImp.h>
#include <org/w3c/dom/bootstrap/CommentImp.h>
#include <org/w3c/dom/bootstrap/CompositionEventImp.h>
#include <org/w3c/dom/bootstrap/CounterImp.h>
#include <org/w3c/dom/bootstrap/CustomEventImp.h>
#include <org/w3c/dom/bootstrap/CustomEventInitImp.h>
#include <org/w3c/dom/bootstrap/DOMElementMapImp.h>
#include <org/w3c/dom/bootstrap/DOMImplementationCSSImp.h>
#include <org/w3c/dom/bootstrap/DOMImplementationImp.h>
#include <org/w3c/dom/bootstrap/DOMSettableTokenListImp.h>
#include <org/w3c/dom/bootstrap/DOMStringListImp.h>
#include <org/w3c/dom/bootstrap/DOMStringMapImp.h>
#include <org/w3c/dom/bootstrap/DOMTokenListImp.h>
#include <org/w3c/dom/bootstrap/DataTransferImp.h>
#include <org/w3c/dom/bootstrap/DataTransferItemImp.h>
#include <org/w3c/dom/bootstrap/DataTransferItemListImp.h>
#include <org/w3c/dom/bootstrap/DataViewImp.h>
#include <org/w3c/dom/bootstrap/DocumentCSSImp.h>
#include <org/w3c/dom/bootstrap/DocumentFragmentImp.h>
#include <org/w3c/dom/bootstrap/DocumentImp.h>
#include <org/w3c/dom/bootstrap/DocumentRangeImp.h>
#include <org/w3c/dom/bootstrap/DocumentTraversalImp.h>
#include <org/w3c/dom/bootstrap/DocumentTypeImp.h>
#include <org/w3c/dom/bootstrap/DragEventImp.h>
#include <org/w3c/dom/bootstrap/ElementCSSInlineStyleImp.h>
#include <org/w3c/dom/bootstrap/ElementImp.h>
#include <org/w3c/dom/bootstrap/EventImp.h>
#include <org/w3c/dom/bootstrap/EventInitImp.h>
#include <org/w3c/dom/bootstrap/EventListenerImp.h>
#include <org/w3c/dom/bootstrap/EventSourceImp.h>
#include <org/w3c/dom/bootstrap/EventTargetImp.h>
#include <org/w3c/dom/bootstrap/ExternalImp.h>
#include <org/w3c/dom/bootstrap/FileCallbackImp.h>
#include <org/w3c/dom/bootstrap/FileErrorImp.h>
#include <org/w3c/dom/bootstrap/FileImp.h>
#include <org/w3c/dom/bootstrap/FileListImp.h>
#include <org/w3c/dom/bootstrap/FileReaderImp.h>
#include <org/w3c/dom/bootstrap/FileReaderSyncImp.h>
#include <org/w3c/dom/bootstrap/Float32ArrayImp.h>
#include <org/w3c/dom/bootstrap/Float64ArrayImp.h>
#include <org/w3c/dom/bootstrap/FocusEventImp.h>
#include <org/w3c/dom/bootstrap/FormDataImp.h>
#include <org/w3c/dom/bootstrap/FunctionImp.h>
#include <org/w3c/dom/bootstrap/FunctionStringCallbackImp.h>
#include <org/w3c/dom/bootstrap/HTMLAllCollectionImp.h>
#include <org/w3c/dom/bootstrap/HTMLAnchorElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLAppletElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLAreaElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLAudioElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLBRElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLBaseElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLBaseFontElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLBodyElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLButtonElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLCanvasElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLCollectionImp.h>
#include <org/w3c/dom/bootstrap/HTMLCommandElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLDListElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLDataListElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLDetailsElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLDirectoryElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLDivElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLDocumentImp.h>
#include <org/w3c/dom/bootstrap/HTMLElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLEmbedElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLFieldSetElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLFontElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLFormControlsCollectionImp.h>
#include <org/w3c/dom/bootstrap/HTMLFormElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLFrameElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLFrameSetElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLHRElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLHeadElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLHeadingElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLHtmlElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLIFrameElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLImageElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLInputElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLKeygenElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLLIElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLLabelElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLLegendElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLLinkElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLMapElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLMarqueeElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLMediaElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLMenuElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLMetaElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLMeterElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLModElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLOListElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLObjectElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLOptGroupElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLOptionElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLOptionsCollectionImp.h>
#include <org/w3c/dom/bootstrap/HTMLOutputElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLParagraphElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLParamElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLPreElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLProgressElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLPropertiesCollectionImp.h>
#include <org/w3c/dom/bootstrap/HTMLQuoteElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLScriptElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLSelectElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLSourceElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLSpanElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLStyleElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableCaptionElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableCellElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableColElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableDataCellElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableHeaderCellElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableRowElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTableSectionElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTextAreaElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTimeElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTitleElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLTrackElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLUListElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLUnknownElementImp.h>
#include <org/w3c/dom/bootstrap/HTMLVideoElementImp.h>
#include <org/w3c/dom/bootstrap/HashChangeEventImp.h>
#include <org/w3c/dom/bootstrap/HistoryImp.h>
#include <org/w3c/dom/bootstrap/ImageDataImp.h>
#include <org/w3c/dom/bootstrap/Int16ArrayImp.h>
#include <org/w3c/dom/bootstrap/Int32ArrayImp.h>
#include <org/w3c/dom/bootstrap/Int8ArrayImp.h>
#include <org/w3c/dom/bootstrap/KeyboardEventImp.h>
#include <org/w3c/dom/bootstrap/LinkStyleImp.h>
// #include <org/w3c/dom/bootstrap/LocalMediaStreamImp.h>
#include <org/w3c/dom/bootstrap/LocationImp.h>
#include <org/w3c/dom/bootstrap/MediaControllerImp.h>
#include <org/w3c/dom/bootstrap/MediaErrorImp.h>
#include <org/w3c/dom/bootstrap/MediaListImp.h>
#include <org/w3c/dom/bootstrap/MediaQueryListImp.h>
#include <org/w3c/dom/bootstrap/MediaQueryListListenerImp.h>
// #include <org/w3c/dom/bootstrap/MediaStreamImp.h>
#include <org/w3c/dom/bootstrap/MediaStreamRecorderImp.h>
#include <org/w3c/dom/bootstrap/MessageChannelImp.h>
#include <org/w3c/dom/bootstrap/MessageEventImp.h>
#include <org/w3c/dom/bootstrap/MessagePortImp.h>
#include <org/w3c/dom/bootstrap/MouseEventImp.h>
#include <org/w3c/dom/bootstrap/MutableTextTrackImp.h>
#include <org/w3c/dom/bootstrap/MutationEventImp.h>
#include <org/w3c/dom/bootstrap/MutationNameEventImp.h>
#include <org/w3c/dom/bootstrap/NavigatorImp.h>
#include <org/w3c/dom/bootstrap/NavigatorUserMediaErrorCallbackImp.h>
#include <org/w3c/dom/bootstrap/NavigatorUserMediaErrorImp.h>
// #include <org/w3c/dom/bootstrap/NavigatorUserMediaSuccessCallbackImp.h>
#include <org/w3c/dom/bootstrap/NodeFilterImp.h>
#include <org/w3c/dom/bootstrap/NodeImp.h>
#include <org/w3c/dom/bootstrap/NodeIteratorImp.h>
#include <org/w3c/dom/bootstrap/NodeListImp.h>
#include <org/w3c/dom/bootstrap/PageTransitionEventImp.h>
// #include <org/w3c/dom/bootstrap/PeerConnectionImp.h>
#include <org/w3c/dom/bootstrap/PopStateEventImp.h>
#include <org/w3c/dom/bootstrap/ProcessingInstructionImp.h>
#include <org/w3c/dom/bootstrap/ProgressEventImp.h>
#include <org/w3c/dom/bootstrap/PropertyNodeListImp.h>
#include <org/w3c/dom/bootstrap/RGBColorImp.h>
#include <org/w3c/dom/bootstrap/RadioNodeListImp.h>
#include <org/w3c/dom/bootstrap/RangeImp.h>
#include <org/w3c/dom/bootstrap/RectImp.h>
#include <org/w3c/dom/bootstrap/ScreenImp.h>
#include <org/w3c/dom/bootstrap/SignalingCallbackImp.h>
// #include <org/w3c/dom/bootstrap/StreamEventImp.h>
#include <org/w3c/dom/bootstrap/StreamTrackImp.h>
#include <org/w3c/dom/bootstrap/StyleSheetImp.h>
#include <org/w3c/dom/bootstrap/TextEventImp.h>
#include <org/w3c/dom/bootstrap/TextImp.h>
#include <org/w3c/dom/bootstrap/TextMetricsImp.h>
#include <org/w3c/dom/bootstrap/TextTrackCueImp.h>
#include <org/w3c/dom/bootstrap/TextTrackCueListImp.h>
#include <org/w3c/dom/bootstrap/TextTrackImp.h>
#include <org/w3c/dom/bootstrap/TimeRangesImp.h>
#include <org/w3c/dom/bootstrap/TransferableImp.h>
#include <org/w3c/dom/bootstrap/TreeWalkerImp.h>
#include <org/w3c/dom/bootstrap/UIEventImp.h>
#include <org/w3c/dom/bootstrap/Uint16ArrayImp.h>
#include <org/w3c/dom/bootstrap/Uint32ArrayImp.h>
#include <org/w3c/dom/bootstrap/Uint8ArrayImp.h>
#include <org/w3c/dom/bootstrap/UndoManagerEventImp.h>
#include <org/w3c/dom/bootstrap/UndoManagerImp.h>
#include <org/w3c/dom/bootstrap/ValidityStateImp.h>
#include <org/w3c/dom/bootstrap/VideoTrackImp.h>
#include <org/w3c/dom/bootstrap/VideoTrackListImp.h>
#include <org/w3c/dom/bootstrap/WheelEventImp.h>
#include <org/w3c/dom/bootstrap/WindowImp.h>
#include <org/w3c/dom/bootstrap/WindowModalImp.h>
#include <org/w3c/dom/bootstrap/XMLHttpRequestEventTargetImp.h>
#include <org/w3c/dom/bootstrap/XMLHttpRequestImp.h>
#include <org/w3c/dom/bootstrap/XMLHttpRequestUploadImp.h>
using namespace org::w3c::dom::bootstrap;
using namespace org::w3c::dom;
html::Window window(0);
static JSClass globalClass = {
"global", JSCLASS_GLOBAL_FLAGS | JSCLASS_HAS_PRIVATE,
JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
JSCLASS_NO_OPTIONAL_MEMBERS
};
void reportError(JSContext* cx, const char* message, JSErrorReport* report)
{
std::cerr << (report->filename ? report->filename : "<no filename>") << report->lineno << message;
}
void registerClasses(JSContext* cx, JSObject* global)
{
// Base classes have to be registered firstly.
DOMTokenListImp::setStaticPrivate(new NativeClass(cx, global, DOMTokenListImp::getMetaData()));
EventTargetImp::setStaticPrivate(new NativeClass(cx, global, EventTargetImp::getMetaData()));
XMLHttpRequestEventTargetImp::setStaticPrivate(new NativeClass(cx, global, XMLHttpRequestEventTargetImp::getMetaData()));
EventImp::setStaticPrivate(new NativeClass(cx, global, EventImp::getMetaData()));
UIEventImp::setStaticPrivate(new NativeClass(cx, global, UIEventImp::getMetaData()));
MouseEventImp::setStaticPrivate(new NativeClass(cx, global, MouseEventImp::getMetaData()));
EventInitImp::setStaticPrivate(new NativeClass(cx, global, EventInitImp::getMetaData()));
NodeImp::setStaticPrivate(new NativeClass(cx, global, NodeImp::getMetaData()));
ElementImp::setStaticPrivate(new NativeClass(cx, global, ElementImp::getMetaData()));
HTMLElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLElementImp::getMetaData()));
HTMLMediaElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLMediaElementImp::getMetaData()));
HTMLCollectionImp::setStaticPrivate(new NativeClass(cx, global, HTMLCollectionImp::getMetaData()));
StyleSheetImp::setStaticPrivate(new NativeClass(cx, global, StyleSheetImp::getMetaData()));
CSSRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSRuleImp::getMetaData()));
CSSValueImp::setStaticPrivate(new NativeClass(cx, global, CSSValueImp::getMetaData()));
XMLHttpRequestImp::setStaticPrivate(new NativeClass(cx, global, XMLHttpRequestImp::getMetaData()));
TextTrackImp::setStaticPrivate(new NativeClass(cx, global, TextTrackImp::getMetaData()));
AnonXMLHttpRequestImp::setStaticPrivate(new NativeClass(cx, global, AnonXMLHttpRequestImp::getMetaData()));
ApplicationCacheImp::setStaticPrivate(new NativeClass(cx, global, ApplicationCacheImp::getMetaData()));
ArrayBufferImp::setStaticPrivate(new NativeClass(cx, global, ArrayBufferImp::getMetaData()));
ArrayBufferViewImp::setStaticPrivate(new NativeClass(cx, global, ArrayBufferViewImp::getMetaData()));
AttrImp::setStaticPrivate(new NativeClass(cx, global, AttrImp::getMetaData()));
AudioTrackImp::setStaticPrivate(new NativeClass(cx, global, AudioTrackImp::getMetaData()));
AudioTrackListImp::setStaticPrivate(new NativeClass(cx, global, AudioTrackListImp::getMetaData()));
BarPropImp::setStaticPrivate(new NativeClass(cx, global, BarPropImp::getMetaData()));
BeforeUnloadEventImp::setStaticPrivate(new NativeClass(cx, global, BeforeUnloadEventImp::getMetaData()));
BlobCallbackImp::setStaticPrivate(new NativeClass(cx, global, BlobCallbackImp::getMetaData()));
BlobImp::setStaticPrivate(new NativeClass(cx, global, BlobImp::getMetaData()));
CSS2PropertiesImp::setStaticPrivate(new NativeClass(cx, global, CSS2PropertiesImp::getMetaData()));
CSSCharsetRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSCharsetRuleImp::getMetaData()));
CSSColorComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSColorComponentValueImp::getMetaData()));
CSSComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSComponentValueImp::getMetaData()));
CSSFontFaceRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSFontFaceRuleImp::getMetaData()));
CSSIdentifierComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSIdentifierComponentValueImp::getMetaData()));
CSSImportRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSImportRuleImp::getMetaData()));
CSSKeywordComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSKeywordComponentValueImp::getMetaData()));
CSSLengthComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSLengthComponentValueImp::getMetaData()));
CSSMapValueImp::setStaticPrivate(new NativeClass(cx, global, CSSMapValueImp::getMetaData()));
CSSMediaRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSMediaRuleImp::getMetaData()));
CSSNamespaceRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSNamespaceRuleImp::getMetaData()));
CSSPageRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSPageRuleImp::getMetaData()));
CSSPercentageComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSPercentageComponentValueImp::getMetaData()));
CSSPrimitiveValueImp::setStaticPrivate(new NativeClass(cx, global, CSSPrimitiveValueImp::getMetaData()));
CSSPropertyValueImp::setStaticPrivate(new NativeClass(cx, global, CSSPropertyValueImp::getMetaData()));
CSSPropertyValueListImp::setStaticPrivate(new NativeClass(cx, global, CSSPropertyValueListImp::getMetaData()));
CSSStringComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSStringComponentValueImp::getMetaData()));
CSSStyleDeclarationImp::setStaticPrivate(new NativeClass(cx, global, CSSStyleDeclarationImp::getMetaData()));
CSSStyleDeclarationValueImp::setStaticPrivate(new NativeClass(cx, global, CSSStyleDeclarationValueImp::getMetaData()));
CSSStyleRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSStyleRuleImp::getMetaData()));
CSSStyleSheetImp::setStaticPrivate(new NativeClass(cx, global, CSSStyleSheetImp::getMetaData()));
CSSURLComponentValueImp::setStaticPrivate(new NativeClass(cx, global, CSSURLComponentValueImp::getMetaData()));
CSSUnknownRuleImp::setStaticPrivate(new NativeClass(cx, global, CSSUnknownRuleImp::getMetaData()));
CSSValueListImp::setStaticPrivate(new NativeClass(cx, global, CSSValueListImp::getMetaData()));
CanvasGradientImp::setStaticPrivate(new NativeClass(cx, global, CanvasGradientImp::getMetaData()));
CanvasPatternImp::setStaticPrivate(new NativeClass(cx, global, CanvasPatternImp::getMetaData()));
CanvasPixelArrayImp::setStaticPrivate(new NativeClass(cx, global, CanvasPixelArrayImp::getMetaData()));
CanvasRenderingContext2DImp::setStaticPrivate(new NativeClass(cx, global, CanvasRenderingContext2DImp::getMetaData()));
CaretPositionImp::setStaticPrivate(new NativeClass(cx, global, CaretPositionImp::getMetaData()));
CharacterDataImp::setStaticPrivate(new NativeClass(cx, global, CharacterDataImp::getMetaData()));
ClientRectImp::setStaticPrivate(new NativeClass(cx, global, ClientRectImp::getMetaData()));
ClientRectListImp::setStaticPrivate(new NativeClass(cx, global, ClientRectListImp::getMetaData()));
CommentImp::setStaticPrivate(new NativeClass(cx, global, CommentImp::getMetaData()));
CompositionEventImp::setStaticPrivate(new NativeClass(cx, global, CompositionEventImp::getMetaData()));
CounterImp::setStaticPrivate(new NativeClass(cx, global, CounterImp::getMetaData()));
CustomEventImp::setStaticPrivate(new NativeClass(cx, global, CustomEventImp::getMetaData()));
CustomEventInitImp::setStaticPrivate(new NativeClass(cx, global, CustomEventInitImp::getMetaData()));
DOMElementMapImp::setStaticPrivate(new NativeClass(cx, global, DOMElementMapImp::getMetaData()));
DOMImplementationCSSImp::setStaticPrivate(new NativeClass(cx, global, DOMImplementationCSSImp::getMetaData()));
DOMImplementationImp::setStaticPrivate(new NativeClass(cx, global, DOMImplementationImp::getMetaData()));
DOMSettableTokenListImp::setStaticPrivate(new NativeClass(cx, global, DOMSettableTokenListImp::getMetaData()));
DOMStringListImp::setStaticPrivate(new NativeClass(cx, global, DOMStringListImp::getMetaData()));
DOMStringMapImp::setStaticPrivate(new NativeClass(cx, global, DOMStringMapImp::getMetaData()));
DataTransferImp::setStaticPrivate(new NativeClass(cx, global, DataTransferImp::getMetaData()));
DataTransferItemImp::setStaticPrivate(new NativeClass(cx, global, DataTransferItemImp::getMetaData()));
DataTransferItemListImp::setStaticPrivate(new NativeClass(cx, global, DataTransferItemListImp::getMetaData()));
DataViewImp::setStaticPrivate(new NativeClass(cx, global, DataViewImp::getMetaData()));
DocumentCSSImp::setStaticPrivate(new NativeClass(cx, global, DocumentCSSImp::getMetaData()));
DocumentFragmentImp::setStaticPrivate(new NativeClass(cx, global, DocumentFragmentImp::getMetaData()));
DocumentImp::setStaticPrivate(new NativeClass(cx, global, DocumentImp::getMetaData()));
DocumentRangeImp::setStaticPrivate(new NativeClass(cx, global, DocumentRangeImp::getMetaData()));
DocumentTraversalImp::setStaticPrivate(new NativeClass(cx, global, DocumentTraversalImp::getMetaData()));
DocumentTypeImp::setStaticPrivate(new NativeClass(cx, global, DocumentTypeImp::getMetaData()));
DragEventImp::setStaticPrivate(new NativeClass(cx, global, DragEventImp::getMetaData()));
ElementCSSInlineStyleImp::setStaticPrivate(new NativeClass(cx, global, ElementCSSInlineStyleImp::getMetaData()));
EventListenerImp::setStaticPrivate(new NativeClass(cx, global, EventListenerImp::getMetaData()));
EventSourceImp::setStaticPrivate(new NativeClass(cx, global, EventSourceImp::getMetaData()));
ExternalImp::setStaticPrivate(new NativeClass(cx, global, ExternalImp::getMetaData()));
FileCallbackImp::setStaticPrivate(new NativeClass(cx, global, FileCallbackImp::getMetaData()));
FileErrorImp::setStaticPrivate(new NativeClass(cx, global, FileErrorImp::getMetaData()));
FileImp::setStaticPrivate(new NativeClass(cx, global, FileImp::getMetaData()));
FileListImp::setStaticPrivate(new NativeClass(cx, global, FileListImp::getMetaData()));
FileReaderImp::setStaticPrivate(new NativeClass(cx, global, FileReaderImp::getMetaData()));
FileReaderSyncImp::setStaticPrivate(new NativeClass(cx, global, FileReaderSyncImp::getMetaData()));
Float32ArrayImp::setStaticPrivate(new NativeClass(cx, global, Float32ArrayImp::getMetaData()));
Float64ArrayImp::setStaticPrivate(new NativeClass(cx, global, Float64ArrayImp::getMetaData()));
FocusEventImp::setStaticPrivate(new NativeClass(cx, global, FocusEventImp::getMetaData()));
FormDataImp::setStaticPrivate(new NativeClass(cx, global, FormDataImp::getMetaData()));
FunctionImp::setStaticPrivate(new NativeClass(cx, global, FunctionImp::getMetaData()));
FunctionStringCallbackImp::setStaticPrivate(new NativeClass(cx, global, FunctionStringCallbackImp::getMetaData()));
HTMLAllCollectionImp::setStaticPrivate(new NativeClass(cx, global, HTMLAllCollectionImp::getMetaData()));
HTMLAnchorElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLAnchorElementImp::getMetaData()));
HTMLAppletElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLAppletElementImp::getMetaData()));
HTMLAreaElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLAreaElementImp::getMetaData()));
HTMLAudioElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLAudioElementImp::getMetaData()));
HTMLBRElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLBRElementImp::getMetaData()));
HTMLBaseElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLBaseElementImp::getMetaData()));
HTMLBaseFontElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLBaseFontElementImp::getMetaData()));
HTMLBodyElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLBodyElementImp::getMetaData()));
HTMLButtonElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLButtonElementImp::getMetaData()));
HTMLCanvasElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLCanvasElementImp::getMetaData()));
HTMLCommandElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLCommandElementImp::getMetaData()));
HTMLDListElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLDListElementImp::getMetaData()));
HTMLDataListElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLDataListElementImp::getMetaData()));
HTMLDetailsElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLDetailsElementImp::getMetaData()));
HTMLDirectoryElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLDirectoryElementImp::getMetaData()));
HTMLDivElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLDivElementImp::getMetaData()));
HTMLDocumentImp::setStaticPrivate(new NativeClass(cx, global, HTMLDocumentImp::getMetaData()));
HTMLEmbedElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLEmbedElementImp::getMetaData()));
HTMLFieldSetElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLFieldSetElementImp::getMetaData()));
HTMLFontElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLFontElementImp::getMetaData()));
HTMLFormControlsCollectionImp::setStaticPrivate(new NativeClass(cx, global, HTMLFormControlsCollectionImp::getMetaData()));
HTMLFormElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLFormElementImp::getMetaData()));
HTMLFrameElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLFrameElementImp::getMetaData()));
HTMLFrameSetElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLFrameSetElementImp::getMetaData()));
HTMLHRElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLHRElementImp::getMetaData()));
HTMLHeadElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLHeadElementImp::getMetaData()));
HTMLHeadingElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLHeadingElementImp::getMetaData()));
HTMLHtmlElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLHtmlElementImp::getMetaData()));
HTMLIFrameElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLIFrameElementImp::getMetaData()));
HTMLImageElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLImageElementImp::getMetaData()));
HTMLInputElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLInputElementImp::getMetaData()));
HTMLKeygenElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLKeygenElementImp::getMetaData()));
HTMLLIElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLLIElementImp::getMetaData()));
HTMLLabelElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLLabelElementImp::getMetaData()));
HTMLLegendElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLLegendElementImp::getMetaData()));
HTMLLinkElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLLinkElementImp::getMetaData()));
HTMLMapElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLMapElementImp::getMetaData()));
HTMLMarqueeElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLMarqueeElementImp::getMetaData()));
HTMLMenuElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLMenuElementImp::getMetaData()));
HTMLMetaElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLMetaElementImp::getMetaData()));
HTMLMeterElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLMeterElementImp::getMetaData()));
HTMLModElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLModElementImp::getMetaData()));
HTMLOListElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLOListElementImp::getMetaData()));
HTMLObjectElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLObjectElementImp::getMetaData()));
HTMLOptGroupElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLOptGroupElementImp::getMetaData()));
HTMLOptionElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLOptionElementImp::getMetaData()));
HTMLOptionsCollectionImp::setStaticPrivate(new NativeClass(cx, global, HTMLOptionsCollectionImp::getMetaData()));
HTMLOutputElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLOutputElementImp::getMetaData()));
HTMLParagraphElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLParagraphElementImp::getMetaData()));
HTMLParamElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLParamElementImp::getMetaData()));
HTMLPreElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLPreElementImp::getMetaData()));
HTMLProgressElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLProgressElementImp::getMetaData()));
HTMLPropertiesCollectionImp::setStaticPrivate(new NativeClass(cx, global, HTMLPropertiesCollectionImp::getMetaData()));
HTMLQuoteElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLQuoteElementImp::getMetaData()));
HTMLScriptElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLScriptElementImp::getMetaData()));
HTMLSelectElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLSelectElementImp::getMetaData()));
HTMLSourceElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLSourceElementImp::getMetaData()));
HTMLSpanElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLSpanElementImp::getMetaData()));
HTMLStyleElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLStyleElementImp::getMetaData()));
HTMLTableCaptionElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableCaptionElementImp::getMetaData()));
HTMLTableCellElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableCellElementImp::getMetaData()));
HTMLTableColElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableColElementImp::getMetaData()));
HTMLTableDataCellElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableDataCellElementImp::getMetaData()));
HTMLTableElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableElementImp::getMetaData()));
HTMLTableHeaderCellElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableHeaderCellElementImp::getMetaData()));
HTMLTableRowElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableRowElementImp::getMetaData()));
HTMLTableSectionElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTableSectionElementImp::getMetaData()));
HTMLTextAreaElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTextAreaElementImp::getMetaData()));
HTMLTimeElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTimeElementImp::getMetaData()));
HTMLTitleElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTitleElementImp::getMetaData()));
HTMLTrackElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLTrackElementImp::getMetaData()));
HTMLUListElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLUListElementImp::getMetaData()));
HTMLUnknownElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLUnknownElementImp::getMetaData()));
HTMLVideoElementImp::setStaticPrivate(new NativeClass(cx, global, HTMLVideoElementImp::getMetaData()));
HashChangeEventImp::setStaticPrivate(new NativeClass(cx, global, HashChangeEventImp::getMetaData()));
HistoryImp::setStaticPrivate(new NativeClass(cx, global, HistoryImp::getMetaData()));
ImageDataImp::setStaticPrivate(new NativeClass(cx, global, ImageDataImp::getMetaData()));
Int16ArrayImp::setStaticPrivate(new NativeClass(cx, global, Int16ArrayImp::getMetaData()));
Int32ArrayImp::setStaticPrivate(new NativeClass(cx, global, Int32ArrayImp::getMetaData()));
Int8ArrayImp::setStaticPrivate(new NativeClass(cx, global, Int8ArrayImp::getMetaData()));
KeyboardEventImp::setStaticPrivate(new NativeClass(cx, global, KeyboardEventImp::getMetaData()));
LinkStyleImp::setStaticPrivate(new NativeClass(cx, global, LinkStyleImp::getMetaData()));
// LocalMediaStreamImp::setStaticPrivate(new NativeClass(cx, global, LocalMediaStreamImp::getMetaData()));
LocationImp::setStaticPrivate(new NativeClass(cx, global, LocationImp::getMetaData()));
MediaControllerImp::setStaticPrivate(new NativeClass(cx, global, MediaControllerImp::getMetaData()));
MediaErrorImp::setStaticPrivate(new NativeClass(cx, global, MediaErrorImp::getMetaData()));
MediaListImp::setStaticPrivate(new NativeClass(cx, global, MediaListImp::getMetaData()));
MediaQueryListImp::setStaticPrivate(new NativeClass(cx, global, MediaQueryListImp::getMetaData()));
MediaQueryListListenerImp::setStaticPrivate(new NativeClass(cx, global, MediaQueryListListenerImp::getMetaData()));
// MediaStreamImp::setStaticPrivate(new NativeClass(cx, global, MediaStreamImp::getMetaData()));
MediaStreamRecorderImp::setStaticPrivate(new NativeClass(cx, global, MediaStreamRecorderImp::getMetaData()));
MessageChannelImp::setStaticPrivate(new NativeClass(cx, global, MessageChannelImp::getMetaData()));
MessageEventImp::setStaticPrivate(new NativeClass(cx, global, MessageEventImp::getMetaData()));
MessagePortImp::setStaticPrivate(new NativeClass(cx, global, MessagePortImp::getMetaData()));
MutableTextTrackImp::setStaticPrivate(new NativeClass(cx, global, MutableTextTrackImp::getMetaData()));
MutationEventImp::setStaticPrivate(new NativeClass(cx, global, MutationEventImp::getMetaData()));
MutationNameEventImp::setStaticPrivate(new NativeClass(cx, global, MutationNameEventImp::getMetaData()));
NavigatorImp::setStaticPrivate(new NativeClass(cx, global, NavigatorImp::getMetaData()));
NavigatorUserMediaErrorCallbackImp::setStaticPrivate(new NativeClass(cx, global, NavigatorUserMediaErrorCallbackImp::getMetaData()));
NavigatorUserMediaErrorImp::setStaticPrivate(new NativeClass(cx, global, NavigatorUserMediaErrorImp::getMetaData()));
// NavigatorUserMediaSuccessCallbackImp::setStaticPrivate(new NativeClass(cx, global, NavigatorUserMediaSuccessCallbackImp::getMetaData()));
NodeFilterImp::setStaticPrivate(new NativeClass(cx, global, NodeFilterImp::getMetaData()));
NodeIteratorImp::setStaticPrivate(new NativeClass(cx, global, NodeIteratorImp::getMetaData()));
NodeListImp::setStaticPrivate(new NativeClass(cx, global, NodeListImp::getMetaData()));
PageTransitionEventImp::setStaticPrivate(new NativeClass(cx, global, PageTransitionEventImp::getMetaData()));
// PeerConnectionImp::setStaticPrivate(new NativeClass(cx, global, PeerConnectionImp::getMetaData()));
PopStateEventImp::setStaticPrivate(new NativeClass(cx, global, PopStateEventImp::getMetaData()));
ProcessingInstructionImp::setStaticPrivate(new NativeClass(cx, global, ProcessingInstructionImp::getMetaData()));
ProgressEventImp::setStaticPrivate(new NativeClass(cx, global, ProgressEventImp::getMetaData()));
PropertyNodeListImp::setStaticPrivate(new NativeClass(cx, global, PropertyNodeListImp::getMetaData()));
RGBColorImp::setStaticPrivate(new NativeClass(cx, global, RGBColorImp::getMetaData()));
RadioNodeListImp::setStaticPrivate(new NativeClass(cx, global, RadioNodeListImp::getMetaData()));
RangeImp::setStaticPrivate(new NativeClass(cx, global, RangeImp::getMetaData()));
RectImp::setStaticPrivate(new NativeClass(cx, global, RectImp::getMetaData()));
ScreenImp::setStaticPrivate(new NativeClass(cx, global, ScreenImp::getMetaData()));
SignalingCallbackImp::setStaticPrivate(new NativeClass(cx, global, SignalingCallbackImp::getMetaData()));
// StreamEventImp::setStaticPrivate(new NativeClass(cx, global, StreamEventImp::getMetaData()));
StreamTrackImp::setStaticPrivate(new NativeClass(cx, global, StreamTrackImp::getMetaData()));
TextEventImp::setStaticPrivate(new NativeClass(cx, global, TextEventImp::getMetaData()));
TextImp::setStaticPrivate(new NativeClass(cx, global, TextImp::getMetaData()));
TextMetricsImp::setStaticPrivate(new NativeClass(cx, global, TextMetricsImp::getMetaData()));
TextTrackCueImp::setStaticPrivate(new NativeClass(cx, global, TextTrackCueImp::getMetaData()));
TextTrackCueListImp::setStaticPrivate(new NativeClass(cx, global, TextTrackCueListImp::getMetaData()));
TimeRangesImp::setStaticPrivate(new NativeClass(cx, global, TimeRangesImp::getMetaData()));
TransferableImp::setStaticPrivate(new NativeClass(cx, global, TransferableImp::getMetaData()));
TreeWalkerImp::setStaticPrivate(new NativeClass(cx, global, TreeWalkerImp::getMetaData()));
Uint16ArrayImp::setStaticPrivate(new NativeClass(cx, global, Uint16ArrayImp::getMetaData()));
Uint32ArrayImp::setStaticPrivate(new NativeClass(cx, global, Uint32ArrayImp::getMetaData()));
Uint8ArrayImp::setStaticPrivate(new NativeClass(cx, global, Uint8ArrayImp::getMetaData()));
UndoManagerEventImp::setStaticPrivate(new NativeClass(cx, global, UndoManagerEventImp::getMetaData()));
UndoManagerImp::setStaticPrivate(new NativeClass(cx, global, UndoManagerImp::getMetaData()));
ValidityStateImp::setStaticPrivate(new NativeClass(cx, global, ValidityStateImp::getMetaData()));
VideoTrackImp::setStaticPrivate(new NativeClass(cx, global, VideoTrackImp::getMetaData()));
VideoTrackListImp::setStaticPrivate(new NativeClass(cx, global, VideoTrackListImp::getMetaData()));
WheelEventImp::setStaticPrivate(new NativeClass(cx, global, WheelEventImp::getMetaData()));
WindowImp::setStaticPrivate(new NativeClass(cx, global, WindowImp::getMetaData()));
WindowModalImp::setStaticPrivate(new NativeClass(cx, global, WindowModalImp::getMetaData()));
XMLHttpRequestUploadImp::setStaticPrivate(new NativeClass(cx, global, XMLHttpRequestUploadImp::getMetaData()));
}
int main(int argc, const char* argv[])
{
JSRuntime* rt = JS_NewRuntime(8L * 1024L * 1024L);
if (!rt)
return EXIT_FAILURE;
jscontext = JS_NewContext(rt, 8192);
if (!jscontext)
return EXIT_FAILURE;
JS_SetOptions(jscontext, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
JS_SetVersion(jscontext, JSVERSION_LATEST);
JS_SetErrorReporter(jscontext, reportError);
JSObject* global = JS_NewCompartmentAndGlobalObject(jscontext, &globalClass, NULL);
if (!global)
return EXIT_FAILURE;
if (!JS_InitStandardClasses(jscontext, global))
return EXIT_FAILURE;
// Register classes
registerClasses(jscontext, global);
// Set up Window as the global object
Reflect::Interface globalMeta(html::Window::getMetaData());
std::string name = Reflect::getIdentifier(globalMeta.getName());
if (0 < name.length()) {
jsval val;
if (JS_GetProperty(jscontext, global, name.c_str(), &val) && JSVAL_IS_OBJECT(val)) {
JSObject* parent = JSVAL_TO_OBJECT(val);
if (JS_GetProperty(jscontext, parent, "prototype", &val) && JSVAL_IS_OBJECT(val)) {
JSObject* proto = JSVAL_TO_OBJECT(val);
JS_SetPrototype(jscontext, global, proto);
}
}
}
window = new WindowImp;
static_cast<WindowImp*>(window.self())->setPrivate(global);
JS_SetPrivate(jscontext, global, window.self());
JS_DestroyContext(jscontext);
JS_DestroyRuntime(rt);
JS_ShutDown();
return 0;
}
| 71.560847 | 144 | 0.79581 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.