text
stringlengths 8
6.88M
|
|---|
#pragma once
#include "Shape.h"
#include "Triangle.h"
#include "Sphere.h"
#include <vector>
namespace RayTracer
{
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace std;
struct intersections
{
float distance;
int indice;
} intersection;
public ref class RayTracer : public System::Windows::Forms::Form
{
public:
RayTracer(void)
{
InitializeComponent();
}
protected:
~RayTracer()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::PictureBox^ surfacePictureBox;
protected:
private:
System::ComponentModel::Container ^components;
public:
public:
public:
int rotLeft = 0;
private: System::Windows::Forms::Button^ button1;
public:
public:
public:
int rotRight = 0;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->surfacePictureBox = (gcnew System::Windows::Forms::PictureBox());
this->button1 = (gcnew System::Windows::Forms::Button());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->surfacePictureBox))->BeginInit();
this->SuspendLayout();
//
// surfacePictureBox
//
this->surfacePictureBox->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->surfacePictureBox->Location = System::Drawing::Point(16, 15);
this->surfacePictureBox->Margin = System::Windows::Forms::Padding(4, 4, 4, 4);
this->surfacePictureBox->Name = L"surfacePictureBox";
this->surfacePictureBox->Size = System::Drawing::Size(800, 450);
this->surfacePictureBox->TabIndex = 0;
this->surfacePictureBox->TabStop = false;
//
// button1
//
this->button1->Location = System::Drawing::Point(367, 484);
this->button1->Margin = System::Windows::Forms::Padding(4, 4, 4, 4);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(100, 28);
this->button1->TabIndex = 1;
this->button1->Text = L"Solution";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &RayTracer::button1_Click);
//
// RayTracer
//
this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(828, 522);
this->Controls->Add(this->button1);
this->Controls->Add(this->surfacePictureBox);
this->KeyPreview = true;
this->Margin = System::Windows::Forms::Padding(4, 4, 4, 4);
this->Name = L"RayTracer";
this->Text = L"Interactive Ray Tracing "
L" Use :"
L" W, A, S, D, Z, X";
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->surfacePictureBox))->EndInit();
this->ResumeLayout(false);
}
#pragma endregion
#pragma region ShadeDiffuse ShadeSpecular ShadingModel
Color ShadeDiffuse(Shape* S, Vertex intersectionPoint)
{
Vertex light = Vertex(0, 80, 60);
Vertex toLight = (light - intersectionPoint).Normalize();
Vertex normal = S->NormalAt(intersectionPoint).Normalize();
Color c = S->ShapeColor;
float diffuseKatsayi = normal * toLight;
if (diffuseKatsayi < 0.0f) return Color::Black;
float r = 0, g = 0, b = 0;
r += diffuseKatsayi * c.R;
g += diffuseKatsayi * c.G;
b += diffuseKatsayi * c.B;
r = r > 255 ? 255 : r; r = r < 0 ? 0 : r;
g = g > 255 ? 255 : g; g = g < 0 ? 0 : g;
b = b > 255 ? 255 : b; b = b < 0 ? 0 : b;
return Color::FromArgb((int)r, (int)g, (int)b);
}
Color ShadeSpecular(Shape* S, Vertex intersectionPoint, Vertex camera)
{
Vertex light = Vertex(0, 80, 60);
Vertex fromLight = (intersectionPoint - light).Normalize();
Vertex normal = S->NormalAt(intersectionPoint).Normalize();
Vertex toCamera = (camera - intersectionPoint).Normalize();
Color Lamba = Color::White;
Vertex reflected = (fromLight - 2 * (normal * fromLight) * normal).Normalize();
float dotProduct = reflected * toCamera;
if (dotProduct < 0.0f) return Color::Black;
float specularKatsayi = (float)Math::Pow((double)(dotProduct), (double)8);
float r = 0, g = 0, b = 0;
r += specularKatsayi * Lamba.R;
g += specularKatsayi * Lamba.G;
b += specularKatsayi * Lamba.B;
r = r > 255 ? 255 : r; r = r < 0 ? 0 : r;
g = g > 255 ? 255 : g; g = g < 0 ? 0 : g;
b = b > 255 ? 255 : b; b = b < 0 ? 0 : b;
return Color::FromArgb((int)r, (int)g, (int)b);
}
Color ShadingModel(Shape* S, Color diffuseColor, Color specularColor, Color reflectedColor, Color transmittedColor, Color refractedColor, float amb, float dif, float spec, float refl, float trans, float refrac)
{
Color ambientcolor = S->ShapeColor;
int r = Math::Min(255, (int)(amb * ambientcolor.R + dif * diffuseColor.R + spec * specularColor.R + refl * reflectedColor.R + trans * transmittedColor.R + refrac * refractedColor.R));
int g = Math::Min(255, (int)(amb * ambientcolor.G + dif * diffuseColor.G + spec * specularColor.G + refl * reflectedColor.G + trans * transmittedColor.G + refrac * refractedColor.G));
int b = Math::Min(255, (int)(amb * ambientcolor.B + dif * diffuseColor.B + spec * specularColor.B + refl * reflectedColor.B + trans * transmittedColor.B + refrac * refractedColor.B));
return Color::FromArgb(r, g, b);
}
#pragma endregion
#pragma region Calculate Reflection Transmission Refraction
Vertex CalculateReflection(Shape* S, Vertex intersectionPoint, Vertex Rd)
{
Vertex normal = S->NormalAt(intersectionPoint).Normalize();
return (Rd - 2 * (normal * Rd) * normal).Normalize();
}
Vertex CalculateTransmission(Shape* S, Vertex intersectionPoint, Vertex Rd)
{
return Rd;
}
Vertex CalculateRefraction(Shape* S, Vertex intersectionPoint, Vertex Rd, float n1, float n2)
{
// Real-Time Rendering (2nd Edition) page : 246
//
// Rd \ Rd : gelen ışının doğrultusu
// \ n1 : 1. ortamın kırılma indisi
// _______\__________
// |
// | n2 : 2. ortamın kırılma indisi
// |
// t t : refracted direction
//
// r = n1 / n2
// w = -(Rd*n)r
// k = sqrt(1+(w-r)(w+r))
// t = r*Rd + (w-k)n (refracted direction)
Vertex normal = S->NormalAt(intersectionPoint).Normalize();
float r = n1 / n2;
float w = -(Rd * normal) * r;
float k = (float)Math::Sqrt((double)(1 + (w - r) * (w + r)));
return (r * Rd + normal * (w - k)).Normalize(); // t
}
#pragma endregion
#pragma region rotateLeft
// Counterclockwise rotation around y-axis
// http://www.mathworks.com/help/phased/ref/roty.html
Vertex rotateLeft(Vertex P, Vertex camera)
{
P = P - camera;
float tmpX = P.X;
P.X = P.X * 0.966F - P.Z * 0.259F;
P.Z = tmpX * 0.259F + P.Z * 0.966F;
P = P + camera;
return P;
}
#pragma endregion
#pragma region rotateRight
// Clockwise rotation around y-axis
Vertex rotateRight(Vertex P, Vertex camera)
{
P = P - camera;
float tmpX = P.X;
P.X = P.X * 0.966F + P.Z * 0.259F;
P.Z = -tmpX * 0.259F + P.Z * 0.966F;
P = P + camera;
return P;
}
#pragma endregion
Color TraceRay(Vertex Ro, Vertex Rd, Shape* Shapes[], Vertex camera, int depth, Shape* prevShape)
{
if (depth > 2)
{
return prevShape->ShapeColor;
//return Color::Black;
}
vector<intersections> Intersections;
for (int i = 0; i < 4; i++)
{
float t = Shapes[i]->Intersect(Ro, Rd);
if (t > 0.1F)
{
intersection.distance = t;
intersection.indice = i;
Intersections.push_back(intersection);
}
}
if (Intersections.size() > 0)
{
float min_distance = FLT_MAX;
int min_indis = -1;
for (int i = 0; i < Intersections.size(); i++)
{
if (Intersections[i].distance < min_distance)
{
min_indis = Intersections[i].indice;
min_distance = Intersections[i].distance;
}
}
Vertex intersectionPoint = Ro + min_distance * Rd;
Shape* S = Shapes[min_indis];
Color reflectedColor;
if (S->Refl != 0.0F)
{
Vertex reflectedDirection = CalculateReflection(S, intersectionPoint, Rd);
reflectedColor = TraceRay(intersectionPoint, reflectedDirection, Shapes, camera, depth + 1, S);
}
Color transmittedColor;
if (S->Trans != 0.0F)
{
Vertex transmittedDirection = CalculateTransmission(S, intersectionPoint, Rd);
transmittedColor = TraceRay(intersectionPoint, transmittedDirection, Shapes, camera, depth + 1, S);
}
Color refractedColor;
if (S->Refrac != 0.0F)
{
Vertex refractedDirection = CalculateRefraction(S, intersectionPoint, Rd, 1.0F, 1.33F);
refractedColor = TraceRay(intersectionPoint, refractedDirection, Shapes, camera, depth + 1, S);
}
Color diffuseColor = ShadeDiffuse(S, intersectionPoint);
Color specularColor = ShadeSpecular(S, intersectionPoint, camera);
return ShadingModel(S, diffuseColor, specularColor, reflectedColor, transmittedColor, refractedColor, S->Ambient, S->Dif, S->Spec, S->Refl, S->Trans, S->Refrac);
}
return Color::Black;
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
//
// 2017 BAHAR VIZE 3. SORU SOLUTION
//
Vertex N(0, 0.6, -0.8);
Vertex camera(0, 0, 0);
Vertex Rd(0, 0, 1);
Vertex iPoint(0, 0, 100);
Vertex P0(-8, 4.5, 10);
Vertex P1( 8, 4.5, 10);
Vertex P2( 8, -4.5, 10);
Vertex P3(-8, -4.5, 10);
P0 = P0 + 80 * Rd;
P1 = P1 + 80 * Rd;
P2 = P2 + 80 * Rd;
P3 = P3 + 80 * Rd;
float P_Length = 13.5739;
//float P_Length = (iPoint - P0).Length();
String^ message = " camera P Distance = " + P_Length + "\n";
MessageBox::Show(message);
P0 = Vertex( 0.5894, -0.3315, 0.7367);
P1 = Vertex(-0.5894, -0.3315, 0.7367);
P2 = Vertex(-0.5894, 0.3315, 0.7367);
P3 = Vertex( 0.5894, 0.3315, 0.7367);
//P0 = (iPoint - P0).Normalize();
//P1 = (iPoint - P1).Normalize();
//P2 = (iPoint - P2).Normalize();
//P3 = (iPoint - P3).Normalize();
message =
"(iPoint - P0).Normalize() = ( " + P0.X.ToString() + ", " + P0.Y.ToString() + ", " + P0.Z.ToString() + " ) \n" +
"(iPoint - P1).Normalize() = ( " + P1.X.ToString() + ", " + P1.Y.ToString() + ", " + P1.Z.ToString() + " ) \n" +
"(iPoint - P2).Normalize() = ( " + P2.X.ToString() + ", " + P2.Y.ToString() + ", " + P2.Z.ToString() + " ) \n" +
"(iPoint - P3).Normalize() = ( " + P3.X.ToString() + ", " + P3.Y.ToString() + ", " + P3.Z.ToString() + " )";
MessageBox::Show(message);
P0 = Vertex( 0.5894, 0.6145, -0.5246);
P1 = Vertex(-0.5894, 0.6145, -0.5246);
P2 = Vertex(-0.5894, 0.8001, 0.1119);
P3 = Vertex( 0.5894, 0.8001, 0.1119);
//P0 = P0 - 2 * (P0*N) * N;
//P1 = P1 - 2 * (P1*N) * N;
//P2 = P2 - 2 * (P2*N) * N;
//P3 = P3 - 2 * (P3*N) * N;
message =
"reflected_P0 = ( " + P0.X.ToString() + ", " + P0.Y.ToString() + ", " + P0.Z.ToString() + " ) \n" +
"reflected_P1 = ( " + P1.X.ToString() + ", " + P1.Y.ToString() + ", " + P1.Z.ToString() + " ) \n" +
"reflected_P2 = ( " + P2.X.ToString() + ", " + P2.Y.ToString() + ", " + P2.Z.ToString() + " ) \n" +
"reflected_P3 = ( " + P3.X.ToString() + ", " + P3.Y.ToString() + ", " + P3.Z.ToString() + " )";
MessageBox::Show(message);
P0 = iPoint + P_Length * P0;
P1 = iPoint + P_Length * P1;
P2 = iPoint + P_Length * P2;
P3 = iPoint + P_Length * P3;
message =
"new P0, P1, P2, P3 vectors : \n\n" +
"P0 = ( " + P0.X.ToString() + ", " + P0.Y.ToString() + ", " + P0.Z.ToString() + " ) \n" +
"P1 = ( " + P1.X.ToString() + ", " + P1.Y.ToString() + ", " + P1.Z.ToString() + " ) \n" +
"P2 = ( " + P2.X.ToString() + ", " + P2.Y.ToString() + ", " + P2.Z.ToString() + " ) \n" +
"P3 = ( " + P3.X.ToString() + ", " + P3.Y.ToString() + ", " + P3.Z.ToString() + " )";
MessageBox::Show(message);
}
};
}
|
#include <unordered_set>
#include <vector>
#include "gmock/gmock.h"
#include "perm.h"
#include "test_utility.h"
#include "test_main.cc"
using cgtl::Perm;
using testing::UnorderedElementsAreArray;
TEST(PermTest, CanConstructPerm)
{
Perm perm;
EXPECT_TRUE(perm_equal({1}, perm))
<< "Default construction produces identity permutation.";
Perm perm_id(5);
EXPECT_TRUE(perm_equal({1, 2, 3, 4, 5}, perm_id))
<< "Identity construction produces identity permutation.";
Perm perm_explicit({1, 3, 4, 5, 2});
EXPECT_TRUE(perm_equal({1, 3, 4, 5, 2}, perm_explicit))
<< "Explicit construction produces correct permutation.";
Perm perm_empty_cycle(6, {});
EXPECT_TRUE(perm_equal({1, 2, 3, 4, 5, 6}, perm_empty_cycle))
<< "No-cycles construction produces correct permutation.";
Perm perm_single_cycle(6, {{3, 2, 5}});
EXPECT_TRUE(perm_equal({1, 5, 2, 4, 3, 6}, perm_single_cycle))
<< "Single-cycle construction produces correct permutation.";
Perm perm_multi_cycles(6, {{6, 2, 4}, {2, 5, 4}, {3, 2, 5}});
EXPECT_TRUE(perm_equal({1, 5, 2, 6, 4, 3}, perm_multi_cycles))
<< "Multi-cycle construction produces correct permutation.";
}
TEST(PermTest, CanInvertPerm)
{
Perm perm({3, 2, 4, 1});
EXPECT_TRUE(perm_equal({4, 2, 1, 3}, ~perm))
<< "Inverting permutation works.";
}
TEST(PermTest, CanMultiplyPerms)
{
Perm perm0(7, {{1, 2, 4}});
perm0 *= Perm(7, {{4, 5}});
EXPECT_TRUE(perm_equal({2, 5, 3, 1, 4, 6, 7}, perm0))
<< "Multiplying plus assigning permutation produces correct result.";
Perm perm1(6, {{2, 5, 4}});
Perm perm2(6, {{3, 2, 5}});
Perm perm_mult1 = perm1 * perm2;
EXPECT_TRUE(perm_equal({1, 3, 2, 5, 4, 6}, perm_mult1))
<< "Multiplying permutations produces correct result.";
}
TEST(PermTest, PermStringRepresentation)
{
Perm perm1({2, 3, 1, 5, 4});
std::stringstream ss1;
ss1 << perm1;
EXPECT_EQ("(1, 2, 3)(4, 5)", ss1.str())
<< "Correct permutation string representation.";
Perm perm2({1, 5, 3, 6, 2, 7, 4, 8});
std::stringstream ss2;
ss2 << perm2;
EXPECT_EQ("(2, 5)(4, 6, 7)", ss2.str())
<< "Permutation string representation ignores single element cycles.";
Perm perm3({1, 2, 3});
std::stringstream ss3;
ss3 << perm3;
EXPECT_EQ("()", ss3.str())
<< "Identity permutation string representation correct.";
}
TEST(PermTest, CanHashPerm)
{
std::vector<Perm> perms = {
Perm(5, {{1, 2, 3}}),
Perm(5, {{2, 3}, {4, 5}}),
Perm(5, {{1, 2, 3, 4}}),
Perm(5, {{1, 2}}),
Perm(5, {{1, 2, 3}, {4, 5}})
};
std::unordered_set<Perm> permset;
unsigned const repetitions = 10u;
for (unsigned i = 0u; i < repetitions; ++i) {
for (Perm const &p : perms)
permset.insert(p);
}
ASSERT_EQ(perms.size(), permset.size())
<< "Hashed permutation set has correct size.";
std::vector<Perm>hashed_perms(permset.begin(), permset.end());
EXPECT_THAT(hashed_perms, UnorderedElementsAreArray(perms))
<< "Hashed permutation set has correct elements.";
}
TEST(PermTest, CanExtendPerm)
{
Perm perm(5, {{2, 5}, {3, 1, 4}});
std::vector<std::vector<unsigned>> expected_extended_perms {
{4, 5, 1, 3, 2},
{4, 5, 1, 3, 2, 6},
{4, 5, 1, 3, 2, 6, 7},
{4, 5, 1, 3, 2, 6, 7, 8}
};
for (auto i = 0u; i < expected_extended_perms.size(); ++i) {
EXPECT_TRUE(perm_equal(expected_extended_perms[i],
perm.extended(perm.degree() + i)))
<< "Permutation extension yields original permutation.";
}
}
// TODO: CanNormalizePerm
TEST(PermTest, CanShiftPerm)
{
Perm perm(5, {{2, 5}, {3, 1, 4}});
std::vector<std::vector<unsigned>> expected_shifted_perms {
{4, 5, 1, 3, 2},
{1, 5, 6, 2, 4, 3},
{1, 2, 6, 7, 3, 5, 4},
{1, 2, 3, 7, 8, 4, 6, 5},
{1, 2, 3, 4, 8, 9, 5, 7, 6},
{1, 2, 3, 4, 5, 9, 10, 6, 8, 7},
{1, 2, 3, 4, 5, 6, 10, 11, 7, 9, 8},
{1, 2, 3, 4, 5, 6, 7, 11, 12, 8, 10, 9}
};
for (auto i = 0u; i < expected_shifted_perms.size(); ++i) {
EXPECT_TRUE(perm_equal(expected_shifted_perms[i], perm.shifted(i)))
<< "Permutation shift yields original permutation (shift was " << i << ")";
}
}
TEST(PermTest, CanRestrictPerm)
{
struct PermRestriction {
PermRestriction(
Perm const &perm, std::vector<unsigned> const &domain,
Perm const &expected) : perm(perm), domain(domain), expected(expected) {}
Perm perm;
std::vector<unsigned> domain;
Perm expected;
};
PermRestriction perm_restrictions[] = {
PermRestriction(
Perm(4, {{1, 2, 3}}),
{1, 2, 3},
Perm(4, {{1, 2, 3}})),
PermRestriction(
Perm(9, {{2, 4}, {3, 5}, {1, 7, 8}}),
{2, 3, 4, 5},
Perm(9, {{2, 4}, {3, 5}})),
PermRestriction(
Perm(12, {{6, 3, 2, 1}, {4, 7}, {9, 8}, {10, 11}}),
{4, 7, 8, 9, 10, 11},
Perm(12, {{4, 7}, {8, 9}, {10, 11}})),
PermRestriction(
Perm(3, {{1, 2}}),
{3},
Perm(3)),
PermRestriction(
Perm(5, {{1, 2, 3}}),
{4, 5},
Perm(5))
};
for (auto const &pr : perm_restrictions) {
EXPECT_EQ(pr.expected, pr.perm.restricted(pr.domain.begin(), pr.domain.end()))
<< "Restricting permutation yields correct result.";
}
}
|
/// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "GameFramework/SpringArmComponent.h"
#include "GameFramework/PlayerController.h"
#include "TimerManager.h"
#include "Engine/EngineTypes.h"
#include "Camera/CameraComponent.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Kismet/GameplayStatics.h"
#include "SLOldGod.generated.h"
class UStaticMeshComponent;
class UCameraComponent;
class USpringArmComponent;
class UGameplayStatics;
class APlayerController;
class UCharacterMovementComponent;
class FTimerManager;
struct FTimerHandle;
UCLASS()
class SMITELABS_API ASLOldGod : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
ASLOldGod();
void LookUp(float val);
void TurnRight(float val);
void MoveForward(float val);
void MoveRight(float val);
void MoveDiagonally(int valX, int valY);
UFUNCTION()
void SetIsBasicAttacking(bool val);
void SetMovementSpeed(float val);
void SetBasicAttackSpeed(float val);
void OnJump();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Mesh")
UStaticMeshComponent* StaticMeshComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Mesh")
UCameraComponent* CameraComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Camera")
USpringArmComponent* SpringArmComponent;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Statistics")
float UndiminishedMovementSpeed;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Statistics")
float DiminishedMovementSpeed;
APlayerController* PlayerController;
float BasicAttackSpeed;
FColor consoleColor;
bool bIsBasicAttacking;
bool bIsRangedBasicAttack;
FTimerHandle BasicAttackTimerHandle;
FTimerDelegate BasicAttackTimerDelegate;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};
|
#include "Node.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define COMM_RANGE 60
double distance2(double x1, double y1, double x2, double y2){
return(sqrt((pow((x1-x2),2)+pow((y1-y2),2))));
}
int main(void){
srand( (unsigned)time( NULL ) );
Node n1;
Node n2;
double timer1, timer2;
//double xtarget, ytarget;
bool reach;
double sum_of_mt = 0;
for(int i=0; i<25000; i++){
//initialize the iteration
//sim_time = 0;
timer1=0;
timer2=0;
n1.Initialize(1);
n2.Initialize(2);
//play with the comm here
for(int i=0; i<2; i++){
for(int j=0;j<2; j++){
n1.comm_x[i][j] = 120.0;
n1.comm_y[i][j] = 120.0;
n1.comm_xupper[i][j] = 280.0;
n1.comm_yupper[i][j] = 280.0;
n2.comm_x[i][j] = 720.0;
n2.comm_y[i][j] = 720.0;
n2.comm_xupper[i][j] = 880.0;
n2.comm_yupper[i][j] = 880.0;
}
}
//printf("comm node1 (%lf %lf)-(%lf %lf) node2 (%lf %lf) - (%lf %lf)\n", n1.comm_x[0][0], n1.comm_y[0][0], n1.comm_xupper[0][0], n1.comm_yupper[0][0], n2.comm_x[0][0], n2.comm_y[0][0], n2.comm_xupper[0][0], n2.comm_yupper[0][0]);
reach = false;
while(!reach){
if(n1.next_event_time<n2.next_event_time){
timer1 = n1.ExecuteEvent(timer1);
//printf("N1 , %lf\n", sim_time);
}else{
timer2 = n2.ExecuteEvent(timer2);
//printf("N2 , %lf\n", sim_time);
}
//printf("time:%lf %lf node1:(%lf %lf) node2:(%lf %lf)\n", timer1, timer2,n1.currentx, n1.currenty, n2.currentx, n2.currenty);
if(distance2(n1.currentx, n1.currenty, n2.currentx, n2.currenty)<COMM_RANGE){
reach=true;
break;
}
}
if(timer1<timer2){
sum_of_mt+=timer1;
}else{
sum_of_mt+=timer2;
}
printf("%lf\n", sum_of_mt/(i+1));
}
}
|
#include <iostream>
#include "CloudGenerator.h"
#include "../Utils/RandomUtils.h"
#include "../OpenGL/ComputeShader.h"
#include "../OpenGL/Texture3D.h"
CloudGenerator::CloudGenerator(glm::ivec3 dims, glm::f32 freq)
{
_cloudVolumeDims = dims;
_groupDims = _cloudVolumeDims / 8;
_frequency = freq;
// just a single channel 32bit float texture for now
_cloudVolume = std::make_shared<Texture3D>(nullptr, dims, GL_RGBA32F, GL_RGBA, GL_FLOAT, false);
_cloudVolume->bind();
_cloudVolume->setFilter(GL_LINEAR);
_cloudVolume->setWrapping(GL_REPEAT);
_cloudGenerator = std::make_shared<ComputeShader>("shaders/cloudGenerator.comp", false);
}
CloudGenerator::~CloudGenerator()
{
}
//std::shared_ptr<Buffer> CloudGenerator::CreateWorleyNoisePointBuffer(glm::i32 numCellsPerAxis)
//{
// auto numTotalCells = numCellsPerAxis * numCellsPerAxis * numCellsPerAxis;
// // USE VEC4 BECAUSE COMPUTE BUFFERS DON'T WORK WITH VEC3
// auto points = new glm::vec4[numTotalCells];
// auto cellSize = glm::float32(1.0f) / numCellsPerAxis;
//
// Utils::SeedRandom();
//
// for (glm::i32 x = 0; x < numCellsPerAxis; x++) {
// for (glm::i32 y = 0; y < numCellsPerAxis; y++) {
// for (glm::i32 z = 0; z < numCellsPerAxis; z++) {
// auto randomOffset = Utils::Random(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f));
// auto position = (glm::vec3(x, y, z) + randomOffset) * cellSize;
// auto index = x + numCellsPerAxis * (y + z * numCellsPerAxis);
// points[index] = glm::vec4(position, 0.0);
// }
// }
// }
//
// // Create the buffer with the random point data
// auto pointBuffer = std::make_shared<Buffer>(GL_SHADER_STORAGE_BUFFER, numTotalCells * sizeof(glm::vec4), &points[0], GL_STATIC_READ);
// return pointBuffer;
//}
std::shared_ptr<Texture3D> CloudGenerator::Generate()
{
// Generate random point buffer for worley noise
//auto worleyNoisePointBuffer = CreateWorleyNoisePointBuffer(_numCellDivisions);
// all code relating to a shader should be between start and end
_cloudGenerator->Start();
// bind the volume to 0 so the compute shader can write to it
_cloudVolume->bindTo(0);
// bind the random point buffer to 2 so the compute shader can access it
//worleyNoisePointBuffer->bindTo(2);
_cloudGenerator->Set("volumeDims", _cloudVolumeDims);
_cloudGenerator->Set("freq", _frequency);
_cloudGenerator->Set("invert", true);
// dispatch the compute shader using 1/8 the size of the texture
// the compute shader is using work groups of size 8^3(512)
// this may need to be reduced for different hardware!
_cloudGenerator->Dispatch(_groupDims);
_cloudGenerator->End();
return _cloudVolume;
}
void CloudGenerator::SetFreq(glm::f32 freq)
{
_frequency = freq;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef OP_SCOPE_SELFTEST_LISTENER_H
#define OP_SCOPE_SELFTEST_LISTENER_H
#ifdef SELFTEST
/**
* Use this class to report events related to selftests.
*/
class OpScopeSelftestListener
{
public:
/**
* Call this when output from a selftest or group of
* selftests is ready.
*
* @param output The output from the selftest.
* @return OpStatus::OK or Opstatus::ERR_NO_MEMORY.
*/
static OP_STATUS OnSelftestOutput(const uni_char *output);
/**
* Call this when the running of selftests have finished.
*
* Don't call this after *each* selftest completes, but after
* the *selection* of tests have finished. If only the scope
* module is chosen, for instance, call this when the tests
* in the scope module are finished.
*
* @return OpStatus::OK or Opstatus::ERR_NO_MEMORY.
*/
static OP_STATUS OnSelftestFinished();
}; // OpScopeSelftestListener
#endif // SELFTEST
#endif // OP_SCOPE_SELFTEST_LISTENER_H
|
#ifndef _SPRITE_GL_H_
#define _SPRITE_GL_H_
#include <AlgebraLib.h>
#include "PrimitiveBase.h"
#include "TextureGL.h"
#include "Mesh.h"
class CSpriteGL : public PrimitiveBase
{
public:
void Create() override;
void Transform( float *t ) override;
void Draw( float *t, const SRenderAttributes& renderAttribs ) override;
void Draw();
void Destroy() override;
void SetFilename( std::string fn );
void SetTexture( int iTextureID );
//TextureGL texture;
private:
QuadMeshGL mesh;
TextureGL* texture{ nullptr };
int texturesLocs[8]{};
int lightColorsLoc = -1;
int lightPositionsLoc = -1;
int WVPLightLoc = -1;
int cameraInfoLoc = -1;
int lightCamInfoLoc = -1;
int WVPInverseLoc = -1;
int CamPosLoc = -1;
int m_iTextureID = -1;
Mat4D::CMatrix4D transform;
Mat4D::CVector4D resolution{ 1.f, 1.f, 0, 1.f };
};
#endif //_SPRITE_GL_H_
|
/**
* @copyright 2013 Christoph Woester
* @author Christoph Woester
*
* 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.
*/
#ifndef EFFICIENTPORTFOLIO_H_
#define EFFICIENTPORTFOLIO_H_
#include <Eigen/Dense>
namespace fpo {
class EfficientPortfolio {
public:
enum Coefficient {
ALPHA,
BETA,
GAMMA,
DELTA
};
protected:
size_t dim;
Eigen::VectorXd& mean;
Eigen::MatrixXd& variance;
double alpha;
double beta;
double gamma;
double delta;
public:
EfficientPortfolio(size_t dim, Eigen::VectorXd& mean, Eigen::MatrixXd& variance);
virtual ~EfficientPortfolio();
virtual double portfolioReturn(const Eigen::VectorXd& portfolio) = 0;
virtual double portfolioVariance(const Eigen::VectorXd& portfolio) = 0;
virtual double portfolioVariance(const double expectedReturn) = 0;
virtual Eigen::VectorXd efficientPortfolio(const double expectedReturn) = 0;
virtual Eigen::VectorXd minimumVariancePortfolio() = 0;
virtual Eigen::VectorXd performanceIncreasingPortfolio() = 0;
};
} /* namespace fpo */
#endif /* EFFICIENTPORTFOLIO_H_ */
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "OpenGLES3Renderer/State/PipelineState.h"
#include "OpenGLES3Renderer/Shader/ProgramGlsl.h"
#include "OpenGLES3Renderer/OpenGLES3Renderer.h"
#include "OpenGLES3Renderer/Mapping.h"
#include <Renderer/IAllocator.h>
#include <Renderer/RenderTarget/IRenderPass.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace OpenGLES3Renderer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
PipelineState::PipelineState(OpenGLES3Renderer& openGLES3Renderer, const Renderer::PipelineState& pipelineState) :
IPipelineState(openGLES3Renderer),
mOpenGLES3PrimitiveTopology(Mapping::getOpenGLES3Type(pipelineState.primitiveTopology)),
mProgram(pipelineState.program),
mRenderPass(pipelineState.renderPass),
mRasterizerState(pipelineState.rasterizerState),
mDepthStencilState(pipelineState.depthStencilState),
mBlendState(pipelineState.blendState)
{
// Add a reference to the given program and render pass
mProgram->addReference();
mRenderPass->addReference();
}
PipelineState::~PipelineState()
{
// Release the program and render pass reference
mProgram->releaseReference();
mRenderPass->releaseReference();
}
void PipelineState::bindPipelineState() const
{
static_cast<OpenGLES3Renderer&>(getRenderer()).setProgram(mProgram);
// Set the OpenGL ES 3 rasterizer state
mRasterizerState.setOpenGLES3RasterizerStates();
// Set OpenGL ES 3 depth stencil state
mDepthStencilState.setOpenGLES3DepthStencilStates();
// Set OpenGL ES 3 blend state
mBlendState.setOpenGLES3BlendStates();
}
const Renderer::RasterizerState& PipelineState::getRasterizerState() const
{
return mRasterizerState.getRasterizerState();
}
const Renderer::DepthStencilState& PipelineState::getDepthStencilState() const
{
return mDepthStencilState.getDepthStencilState();
}
const Renderer::BlendState& PipelineState::getBlendState() const
{
return mBlendState.getBlendState();
}
//[-------------------------------------------------------]
//[ Protected virtual Renderer::RefCount methods ]
//[-------------------------------------------------------]
void PipelineState::selfDestruct()
{
RENDERER_DELETE(getRenderer().getContext(), PipelineState, this);
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // OpenGLES3Renderer
|
// Copyright 2012 Yandex
#ifndef LTR_DATA_PREPROCESSORS_DATA_SAMPLER_H_
#define LTR_DATA_PREPROCESSORS_DATA_SAMPLER_H_
#include <algorithm>
#include <vector>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <boost/lexical_cast.hpp> //NOLINT
#include "ltr/utility/shared_ptr.h" //NOLINT
#include "ltr/data/data_set.h"
#include "ltr/data_preprocessors/data_preprocessor.h"
#include "ltr/utility/indices.h"
using std::set;
using std::string;
using std::vector;
using std::logic_error;
using std::max_element;
using ltr::utility::Indices;
using ltr::utility::IndicesPtr;
namespace ltr {
/**
* \brief Samples elements with specififed indices from input DataSet.
* Duplication of indices leads to duplication of elements in the result sample.
*/
template <class TElement>
class DataSampler : public DataPreprocessor<TElement> {
public:
typedef ltr::utility::shared_ptr<DataSampler> Ptr;
/**
* \param indices indices of elements to sample,
* duplication of indices leads to duplication of elements in the result sample
*/
explicit DataSampler(IndicesPtr indices = IndicesPtr(new Indices));
explicit DataSampler(const ParametersContainer& parameters);
virtual void setDefaultParameters();
virtual void checkParameters() const;
virtual string toString() const;
GET_SET(IndicesPtr, indices);
private:
virtual void applyImpl(const DataSet<TElement>& input,
DataSet<TElement>* output) const;
virtual void setParametersImpl(const ParametersContainer& parameters);
virtual string getDefaultAlias() const {return "DataSampler";}
IndicesPtr indices_;
};
// template realizations
template <typename TElement>
DataSampler<TElement>::DataSampler(IndicesPtr indices) {
set_indices(indices);
}
template <typename TElement>
DataSampler<TElement>::DataSampler(const ParametersContainer& parameters) {
this->setParameters(parameters);
}
template <typename TElement>
void DataSampler<TElement>::setDefaultParameters() {
indices_ = IndicesPtr(new Indices);
}
template <typename TElement>
void DataSampler<TElement>::checkParameters() const {
// DON'T NEED
}
template <typename TElement>
void DataSampler<TElement>::setParametersImpl(
const ParametersContainer& parameters) {
// \TODO(sameg) Create indices from string representation like [1:3], 5, 6
indices_ = parameters.Get<IndicesPtr>("INDICES");
}
template <class TElement>
void DataSampler<TElement>::applyImpl(const DataSet<TElement>& input,
DataSet<TElement>* output) const {
// \TODO(sameg) Is it logic?
if (indices_->size() != 0) {
*output = input.lightSubset(*indices_);
} else {
*output = input;
}
}
template <typename TElement>
string DataSampler<TElement>::toString() const {
std::stringstream str;
str << "DataSampler: indices = [";
for (int index = 0; index < (int)indices_->size(); ++index) {
if (index != 0) {
str << ", ";
}
str << indices_->at(index);
}
str << "]";
return str.str();
}
};
#endif // LTR_DATA_PREPROCESSORS_DATA_SAMPLER_H_
|
/*Tests for cc_shared::thread_pool.*/
#include "cc/shared/thread_pool.h"
#include "gtest/gtest.h"
#include <set>
using std::set;
namespace cc_shared {
class ThreadPoolTest : public testing::Test {
protected:
struct Info {
bool visited;
pthread_t processing_thread;
Info() {
visited = false;
}
};
// We need a relatively large number of tasks to expect some distribution of
// the tasks to the threads.
static const int kTaskCount = 2000;
Info info[kTaskCount];
static void test_thread_func(void* parameter) {
Info* info = static_cast<Info*>(parameter);
info->visited = true;
info->processing_thread = pthread_self();
// Sleep a little, let another thread from the pool pick up another job.
usleep(ThreadPool::kSleepMilliSeconds * 2);
}
void reset_info() {
for (int i = 0; i < kTaskCount; ++i) {
info[i].visited = false;
}
info->processing_thread = 0;
}
bool all_visited() {
for (int i = 0; i < kTaskCount; ++i) {
if (!(info[i].visited)) return false;
}
return true;
}
void wait_for_all_visited() {
static const int kMaxIters = 100;
int i = 0;
while (true) {
++i;
ASSERT_GE(kMaxIters, i);
if (all_visited()) {
break;
}
usleep(10000);
}
}
void validate_threads(int expected_min_threads, int expected_max_threads) {
set<pthread_t> threads;
for (int i = 0; i < kTaskCount; ++i) {
threads.insert(info[i].processing_thread);
}
int thread_count = static_cast<int>(threads.size());
ASSERT_LE(expected_min_threads, thread_count);
ASSERT_GE(expected_max_threads, thread_count);
}
void enqueue_tasks(ThreadPool* thread_pool) {
for (int i = 0; i < kTaskCount; ++i) {
thread_pool->enqueue(
ThreadPoolPayload(test_thread_func, static_cast<void*>(info + i)));
}
}
int get_wake_count(ThreadPool* thread_pool) {
return thread_pool->wake_count_;
}
void wait_for_threads_to_sleep(ThreadPool* thread_pool) {
while (thread_pool->num_threads_ !=
thread_pool->waiting_count_.get_snapshot()) {
usleep(100);
}
}
};
TEST_F(ThreadPoolTest, simple_test) {
for (int thread_count = 1; thread_count <= 10; ++thread_count) {
reset_info();
{
ThreadPool thread_pool(thread_count);
enqueue_tasks(&thread_pool);
// Threadpool destructor calls join. This means we wait for all queued
// items to be processed.
}
ASSERT_TRUE(all_visited());
int expected_min_threads = thread_count > 3 ? (thread_count / 2) : 1;
int expected_max_threads = thread_count;
validate_threads(expected_min_threads, expected_max_threads);
}
}
TEST_F(ThreadPoolTest, multi_batch_test) {
static const int kThreadCount = 4;
ThreadPool thread_pool(kThreadCount);
for (int i = 0; i < 4; ++i) {
if (i > 0) {
wait_for_threads_to_sleep(&thread_pool);
}
reset_info();
enqueue_tasks(&thread_pool);
wait_for_all_visited();
ASSERT_LE(i, get_wake_count(&thread_pool));
}
}
} // cc_shared
|
// Copyright (c) 2013 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepMesh_GeomTool_HeaderFile
#define _BRepMesh_GeomTool_HeaderFile
#include <BRepAdaptor_Surface.hxx>
#include <GCPnts_TangentialDeflection.hxx>
#include <GeomAbs_IsoType.hxx>
#include <TopoDS_Edge.hxx>
#include <Precision.hxx>
class BRepAdaptor_Curve;
class gp_Pnt2d;
class BRepMesh_DefaultRangeSplitter;
//! Tool class accumulating common geometrical functions as well as
//! functionality using shape geometry to produce data necessary for
//! tessellation.
//! General aim is to calculate discretization points for the given
//! curve or iso curve of surface according to the specified parameters.
class BRepMesh_GeomTool
{
public:
//! Enumerates states of segments intersection check.
enum IntFlag
{
NoIntersection,
Cross,
EndPointTouch,
PointOnSegment,
Glued,
Same
};
public:
DEFINE_STANDARD_ALLOC
//! Constructor.
//! Initiates discretization of the given geometric curve.
//! @param theCurve curve to be discretized.
//! @param theFirstParam first parameter of the curve.
//! @param theLastParam last parameter of the curve.
//! @param theLinDeflection linear deflection.
//! @param theAngDeflection angular deflection.
//! @param theMinPointsNb minimum number of points to be produced.
Standard_EXPORT BRepMesh_GeomTool(
const BRepAdaptor_Curve& theCurve,
const Standard_Real theFirstParam,
const Standard_Real theLastParam,
const Standard_Real theLinDeflection,
const Standard_Real theAngDeflection,
const Standard_Integer theMinPointsNb = 2,
const Standard_Real theMinSize = Precision::Confusion());
//! Constructor.
//! Initiates discretization of geometric curve corresponding
//! to iso curve of the given surface.
//! @param theSurface surface the iso curve to be taken from.
//! @param theIsoType type of iso curve to be used, U or V.
//! @param theParamIso parameter on the surface specifying the iso curve.
//! @param theFirstParam first parameter of the curve.
//! @param theLastParam last parameter of the curve.
//! @param theLinDeflection linear deflection.
//! @param theAngDeflection angular deflection.
//! @param theMinPointsNb minimum number of points to be produced.
Standard_EXPORT BRepMesh_GeomTool(
const Handle(BRepAdaptor_Surface)& theSurface,
const GeomAbs_IsoType theIsoType,
const Standard_Real theParamIso,
const Standard_Real theFirstParam,
const Standard_Real theLastParam,
const Standard_Real theLinDeflection,
const Standard_Real theAngDeflection,
const Standard_Integer theMinPointsNb = 2,
const Standard_Real theMinSize = Precision::Confusion());
//! Adds point to already calculated points (or replaces existing).
//! @param thePoint point to be added.
//! @param theParam parameter on the curve corresponding to the given point.
//! @param theIsReplace if TRUE replaces existing point lying within
//! parameteric tolerance of the given point.
//! @return index of new added point or found with parametric tolerance
Standard_Integer AddPoint(const gp_Pnt& thePoint,
const Standard_Real theParam,
const Standard_Boolean theIsReplace = Standard_True)
{
return myDiscretTool.AddPoint(thePoint, theParam, theIsReplace);
}
//! Returns number of discretization points.
Standard_Integer NbPoints() const
{
return myDiscretTool.NbPoints();
}
//! Gets parameters of discretization point with the given index.
//! @param theIndex index of discretization point.
//! @param theIsoParam parameter on surface to be used as second coordinate
//! of resulting 2d point.
//! @param theParam[out] parameter of the point on the iso curve.
//! @param thePoint[out] discretization point.
//! @param theUV[out] discretization point in parametric space of the surface.
//! @return TRUE on success, FALSE elsewhere.
Standard_EXPORT Standard_Boolean Value(const Standard_Integer theIndex,
const Standard_Real theIsoParam,
Standard_Real& theParam,
gp_Pnt& thePoint,
gp_Pnt2d& theUV) const;
//! Gets parameters of discretization point with the given index.
//! @param theIndex index of discretization point.
//! @param theSurface surface the curve is lying onto.
//! @param theParam[out] parameter of the point on the curve.
//! @param thePoint[out] discretization point.
//! @param theUV[out] discretization point in parametric space of the surface.
//! @return TRUE on success, FALSE elsewhere.
Standard_EXPORT Standard_Boolean Value(const Standard_Integer theIndex,
const Handle(BRepAdaptor_Surface)& theSurface,
Standard_Real& theParam,
gp_Pnt& thePoint,
gp_Pnt2d& theUV) const;
public: //! @name static API
//! Computes normal to the given surface at the specified
//! position in parametric space.
//! @param theSurface surface the normal should be found for.
//! @param theParamU U parameter in parametric space of the surface.
//! @param theParamV V parameter in parametric space of the surface.
//! @param[out] thePoint 3d point corresponding to the given parameters.
//! @param[out] theNormal normal vector at the point specified by the parameters.
//! @return FALSE if the normal can not be computed, TRUE elsewhere.
Standard_EXPORT static Standard_Boolean Normal(
const Handle(BRepAdaptor_Surface)& theSurface,
const Standard_Real theParamU,
const Standard_Real theParamV,
gp_Pnt& thePoint,
gp_Dir& theNormal);
//! Checks intersection between two lines defined by two points.
//! @param theStartPnt1 start point of first line.
//! @param theEndPnt1 end point of first line.
//! @param theStartPnt2 start point of second line.
//! @param theEndPnt2 end point of second line.
//! @param[out] theIntPnt point of intersection.
//! @param[out] theParamOnSegment parameters of intersection point
//! corresponding to first and second segment.
//! @return status of intersection check.
Standard_EXPORT static IntFlag IntLinLin(
const gp_XY& theStartPnt1,
const gp_XY& theEndPnt1,
const gp_XY& theStartPnt2,
const gp_XY& theEndPnt2,
gp_XY& theIntPnt,
Standard_Real (&theParamOnSegment)[2]);
//! Checks intersection between the two segments.
//! Checks that intersection point lies within ranges of both segments.
//! @param theStartPnt1 start point of first segment.
//! @param theEndPnt1 end point of first segment.
//! @param theStartPnt2 start point of second segment.
//! @param theEndPnt2 end point of second segment.
//! @param isConsiderEndPointTouch if TRUE EndPointTouch status will be
//! returned in case if segments are touching by end points, if FALSE
//! returns NoIntersection flag.
//! @param isConsiderPointOnSegment if TRUE PointOnSegment status will be
//! returned in case if end point of one segment lies onto another one,
//! if FALSE returns NoIntersection flag.
//! @param[out] theIntPnt point of intersection.
//! @return status of intersection check.
Standard_EXPORT static IntFlag IntSegSeg(
const gp_XY& theStartPnt1,
const gp_XY& theEndPnt1,
const gp_XY& theStartPnt2,
const gp_XY& theEndPnt2,
const Standard_Boolean isConsiderEndPointTouch,
const Standard_Boolean isConsiderPointOnSegment,
gp_Pnt2d& theIntPnt);
//! Compute deflection of the given segment.
static Standard_Real SquareDeflectionOfSegment(
const gp_Pnt& theFirstPoint,
const gp_Pnt& theLastPoint,
const gp_Pnt& theMidPoint)
{
// 23.03.2010 skl for OCC21645 - change precision for comparison
if (theFirstPoint.SquareDistance(theLastPoint) > Precision::SquareConfusion())
{
gp_Lin aLin(theFirstPoint, gp_Dir(gp_Vec(theFirstPoint, theLastPoint)));
return aLin.SquareDistance(theMidPoint);
}
return theFirstPoint.SquareDistance(theMidPoint);
}
// For better meshing performance we try to estimate the acceleration circles grid structure sizes:
// For each parametric direction (U, V) we estimate firstly an approximate distance between the future points -
// this estimation takes into account the required face deflection and the complexity of the face.
// Particularly, the complexity of the faces based on BSpline curves and surfaces requires much more points.
// At the same time, for planar faces and linear parts of the arbitrary surfaces usually no intermediate points
// are necessary.
// The general idea for each parametric direction:
// cells_count = 2 ^ log10 ( estimated_points_count )
// For linear parametric direction we fall back to the initial vertex count:
// cells_count = 2 ^ log10 ( initial_vertex_count )
Standard_EXPORT static std::pair<Standard_Integer, Standard_Integer> CellsCount (
const Handle (Adaptor3d_Surface)& theSurface,
const Standard_Integer theVerticesNb,
const Standard_Real theDeflection,
const BRepMesh_DefaultRangeSplitter* theRangeSplitter);
private:
//! Classifies the point in case of coincidence of two vectors.
//! @param thePoint1 the start point of a segment (base point).
//! @param thePoint2 the end point of a segment.
//! @param thePointToCheck the point to classify.
//! @return zero value if point is out of segment and non zero value
//! if point is between the first and the second point of segment.
static Standard_Integer classifyPoint (const gp_XY& thePoint1,
const gp_XY& thePoint2,
const gp_XY& thePointToCheck);
private:
const TopoDS_Edge* myEdge;
GCPnts_TangentialDeflection myDiscretTool;
GeomAbs_IsoType myIsoType;
};
#endif
|
#pragma once
class CellGrid
{
public:
CellGrid(void);
~CellGrid(void);
};
|
#pragma once
#include "ZeroIScene.h"
#include "ZeroSceneManager.h"
#include "UIManager.h"
#include "GameManager.h"
#include "Item.h"
#include <list>
class Stage :
public ZeroIScene
{
public:
Stage();
Item* item;
UIManager* ui;
GameManager* game;
ZeroFont* damageText;
ZeroFont* healthText;
ZeroFont* speedText;
ZeroSprite* failSprite;
ZeroSprite* failBackground;
void Update(float eTime) override;
void Render() override;
void ShowResult(PlayerCharacter* player, float eTime);
virtual void CheckOut();
virtual void CheckOut(float eTime);
virtual void PopStage();
bool IsCollision(PlayerCharacter* player, Item* item);
};
|
#include "RealImplementation.h"
#include <string>
RealImplementation::RealImplementation(const std::string& text, float value)
{
m_Object = RandomObject(text, value);
}
void RealImplementation::AddText(const std::string& string)
{
m_Object.m_Text = m_Object.m_Text + string;
}
void RealImplementation::ClearText()
{
m_Object.m_Text.clear();
}
float RealImplementation::operator*(float op)
{
return m_Object.m_Value * op;
}
float RealImplementation::operator-(float op)
{
return m_Object.m_Value - op;
}
float RealImplementation::operator+(float op)
{
return m_Object.m_Value + op;
}
float RealImplementation::operator/(float op)
{
return m_Object.m_Value / op;
}
float RealImplementation::operator=(float value)
{
return m_Object.m_Value= value;
}
std::string RealImplementation::ToString() const
{
return m_Object.m_Text + std::to_string(static_cast<int>(m_Object.m_Value));
}
|
#include <stdio.h>
#include <stdlib.h>
void NAMD_bug(const char *errmsg)
{
fprintf(stderr, "%s\n", errmsg);
exit(1);
}
void NAMD_die(const char *errmsg)
{
fprintf(stderr, "%s\n", errmsg);
exit(1);
}
|
#include<iostream>
#include<stdio.h>
#include<vector>
#include<ctime>
#include<cstring>
#include<stdlib.h>
using namespace std;
class Roulette{
public:
vector<char*> reward;
vector<double> poss;
int roll_max;
Roulette(){
roll_max = 1000000;
reward.clear();
poss.clear();
}
int set_reward(int _n, vector<char*> _r, vector<double> _p){
if (_r.size()<_n || _p.size()<_n) return -1;
reward.clear();
poss.clear();
for(int i=0; i<_n; i++){
char* tmp = new char(strlen(_r[i])+1);
strcpy(tmp, _r[i]);
tmp[strlen(_r[i])] = '\0';
reward.push_back(tmp);
poss.push_back(_p[i]);
}
return 0;
}
int change_poss(int _i, double _p){
int size = reward.size();
if (_i>=size) return -1;
poss[_i] = _p;
return 0;
}
int change_reward(int _i, char* _r){
int size = reward.size();
if (_i>=size) return -1;
char* tmp = new char(strlen(_r)+1);
tmp[strlen(_r)] = '\0';
strcpy(tmp, _r);
reward[_i] = tmp;
return 0;
}
void default_init(){
vector<char*> r;
vector<double> p;
int n = 5;
r.push_back("N");
p.push_back(40);
r.push_back("R");
p.push_back(30);
r.push_back("SR");
p.push_back(20);
r.push_back("SSR");
p.push_back(9);
r.push_back("EX");
p.push_back(1);
set_reward(n, r, p);
}
void standardize(){
double sum = 0;
for(auto i=poss.begin(); i!=poss.end(); i++){
sum += (*i);
}
for(auto i=poss.begin(); i!=poss.end(); i++){
(*i)/=sum;
}
}
void new_seed(){
srand((unsigned)time(NULL));
}
double roll(){
return rand() / (double)(RAND_MAX);
}
int get_reward(double p){
int size = poss.size();
for(int i=0; i<size; i++){
p-=poss[i];
if (p<=0){
return i;
}
}
return size-1;
}
};
//int main(){
// Roulette r;
// r.default_init();
// r.standardize();
//// cout<<r.roll();
// for(int i=0; i<100; i++){
// double t = r.roll();
// cout<<r.reward[r.get_reward(t)]<<t<<endl;
// }
//}
|
/* class to laod shader attributes in main.cpp */
class ShaderLoader{
public:
ShaderLoader( const int bufferSize = 10000 );
~ShaderLoader();
void loadShader( const char *fileName );
const char* getShader();
private:
char *shaderInfo;
};
|
#include <sstream>
#include "../inc/SEObject.h"
uint32_t SEObjectName::nextAutoIndex = 0x00000000;
SEObjectName::tNameSet SEObjectName::nameSet(SEObjectName::newNameSet());
SEObject::tObjectMap SEObject::objectMap(SEObject::newObjectMap());
uint32_t SEObjectName::nameToCode(const std::string &n, uint32_t seed)
{
uint32_t h = seed;
for (int i=0;i<n.length();++i)
h=h*101 + n[i];
return h;
}
void SEObjectName::setName(const std::string &s)
{
if (nameInUse(s))
setAutoName();
else
{
n_ = s;
c_ = nameToCode(n_);
}
}
void SEObjectName::setAutoName()
{
n_ = getNextAutoName();
c_ = nameToCode(n_);
}
std::string SEObjectName::getNextAutoName()
{
std::ostringstream s, t;
t.setf(std::ios_base::hex, std::ios_base::basefield);
t.fill('0');
t.width(8);
t << nextAutoIndex;
s << "SEObj_" << t.str();
std::string r = s.str();
do {
++nextAutoIndex;
t << nextAutoIndex;
s << "SEObj_" << t.str();
} while (nameInUse(s.str()));
return(r);
}
|
#include <SoftwareSerial.h>
#include "UbidotsMicroESP8266.h"
#define TOKEN "wgcppnHhcK88Z7Vy34jQCyqQI7CULO" // Put here your Ubidots TOKEN
#define ID_1 "59d8e2c1c03f97267c9b3a59" // Put your variable ID here
#define WIFISSID "Instituto Terra - Visitantes" // Put here your Wi-Fi SSID
#define PASSWORD "" // Put here your Wi-Fi password
Ubidots client(TOKEN);
SoftwareSerial mySerial(13,15); // rx e tx2 NodeMCU - d8 e d7 (conferir a ordem) - ligar com resistor 5v para 3.3V
void setup(){
Serial.begin(115200);
client.wifiConnection(WIFISSID, PASSWORD);
//client.setDebug(true); // Uncomment this line to set DEBUG on
mySerial.begin(115200);
}
void loop(){
float value1 = analogRead(0);
client.add(ID_1, value1);
client.sendAll(false);
delay(5000);
if (mySerial.available()) { Serial.write(mySerial.read());
/*float t = mySerial.parseFloat();
Serial.println(t);
float h = mySerial.parseFloat();
Serial.println(h);
int l = mySerial.parseInt();
Serial.println(l);
int p = mySerial.parseInt();
Serial.print(p); */
}
}
|
#pragma once
#include <iostream>
#include <array>
#include <vector>
#include "json.hpp"
#include "particle.h"
nlohmann::json estimate_step_json(Particle* particles, double* weights, int N, double time, int* ftag_visible, size_t N_visible, int* da_table, int N_features, int id) ;
|
#pragma once
#include "plbase/PluginBase.h"
#include "AnimBlendFrameData.h"
#pragma pack(push, 4)
class PLUGIN_API CAnimBlendClumpData
{
public:
void *m_pLastAssociationLink;
int32_t field_4;
uint32_t m_dwNumBones;
int32_t field_C;
AnimBlendFrameData *m_pBones;
};
#pragma pack(pop)
|
#include <iostream>
#include <iomanip>
// Program: Given three double numbers from keyboard input, the program returns through a function
// the maximum of the three
using namespace std;
// Function that accepts 3 double numbers and returns the maximum of them
double maxim(double x1, double x2, double x3) {
double max = x1;
if (x2 > max)
max = x2;
if (x3 > max)
max = x3;
return(max);
}
int main(void) {
double x, y, z;
cout << "Insert the first number : ";
cin >> x;
cout << "Insert the second number : ";
cin >> y;
cout << "Insert the third number : ";
cin >> z;
cout << "The maximum is "
<< setw(4)
<< maxim(x, y, z)
<< endl;
return(0);
}
|
// Copyright (c) 2019 Thomas Heller
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#include <pika/assert.hpp>
#include <pika/testing.hpp>
#include <string>
[[noreturn]] void assertion_handler(
pika::detail::source_location const&, const char*, std::string const&)
{
PIKA_TEST(true);
std::exit(1);
}
int main()
{
// We set a custom assertion handler because the default one aborts, which
// ctest considers a fatal error, even if WILL_FAIL is set to true.
pika::detail::set_assertion_handler(&assertion_handler);
PIKA_ASSERT(false);
PIKA_TEST(true);
}
|
#include <bits/stdc++.h>
using namespace std;
#define MODULO 1000000007
struct Arista{
int x,y,b;
const bool operator < (const Arista otro) const{
return b == otro.b? x < otro.x : b > otro.b;
}
};
priority_queue<Arista> cola;
vector<int> padre(100005);
vector<int> altura(100005);
vector<int> ancho(100005);
int N;
Arista nueva, actual;
unsigned long long int respuesta = 0, auxu, auxv, aux;
int buscaPadre(int hijo){
if(padre[hijo] == hijo) return hijo;
return padre[hijo] = buscaPadre(padre[hijo]);
}
void une(int u, int v){
int padreU = buscaPadre(u);
int padreV = buscaPadre(v);
if(padreU == padreV) return;
if(altura[padreU] > altura[padreV]){
padre[padreV] = padreU;
aux = ((ancho[padreU]%MODULO) * (ancho[padreV]%MODULO)) % MODULO;
aux = (aux * actual.b) % MODULO;
respuesta += aux;
respuesta %= MODULO;
ancho[padreU] += ancho[padreV];
} else if(altura[padreV] > altura[padreV]){
padre[padreU] = padreV;
aux = ((ancho[padreU]%MODULO) * (ancho[padreV]%MODULO)) % MODULO;
aux = (aux * actual.b) % MODULO;
respuesta += aux;
respuesta %= MODULO;
ancho[padreV] += ancho[padreU];
} else {
padre[padreU] = padreV;
altura[padreV]++;
aux = ((ancho[padreU]%MODULO) * (ancho[padreV]%MODULO)) % MODULO;
aux = (aux * actual.b) % MODULO;
respuesta += aux;
respuesta %= MODULO;
ancho[padreV] += ancho[padreU];
}
}
void rellena(){
for(int i=0; i<=100002; i++){
padre[i] = i;
altura[i] = 1;
ancho[i] = 1;
}
}
int main()
{
ios_base::sync_with_stdio(0);
rellena();
cin >> N;
for(int i=1; i<N; i++){
cin >>nueva.x >> nueva.y >> nueva.b;
cola.push(nueva);
}
while(!cola.empty()){
actual = cola.top();
cola.pop();
une(actual.x,actual.y);
}
cout << respuesta << '\n';
return 0;
}
/*
5
1 2 1
1 3 1
2 4 2
2 5 2
*/
|
#ifndef __JSVEC_HH__
#define __JSVEC_HH__
#include <node.h>
#include <node_buffer.h>
#include <qk/vec.hh>
#include <qk/dcube.hh>
#include <colormap/colormap_interface.hh>
namespace sadira{
using namespace qk;
using namespace v8;
using namespace node;
void free_stream_buffer(char* b, void*x);
template <typename T> class jsvec
: public ObjectWrap, public vec<T> {
//class jsvec : public ObjectWrap {
public:
static Persistent<FunctionTemplate> s_ctm;
//static Persistent<Function> constructor;
static void init(Handle<Object> target, const char* class_name){
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
s_ctm = Persistent<FunctionTemplate>::New(tpl);
//s_ctm->Inherit(colormap_interface::s_ct);
s_ctm->InstanceTemplate()->SetInternalFieldCount(1);
s_ctm->SetClassName(String::NewSymbol(class_name));
NODE_SET_PROTOTYPE_METHOD(s_ctm, "length",length);
//NODE_SET_PROTOTYPE_METHOD(s_ctm, "resize",resize);
target->Set(String::NewSymbol(class_name), s_ctm->GetFunction());
//constructor = Persistent<Function>::New(tpl->GetFunction());
}
private:
jsvec (int _d=0)
:vec<T>(_d)
{
cout << "New vecrix "<< this <<" D="<<_d<<endl;
}
// jsvec (const vec<T> & m){
// operator = (m);
// }
virtual ~jsvec(){}
static Handle<Value> New(const Arguments& args) {
HandleScope scope;
//jsvec<T>* obj = new jsvec<T>();
jsvec* obj = new jsvec();
obj->Wrap(args.This());
args.This()->Set(String::NewSymbol("id"), Number::New(12345));
return args.This();
}
static v8::Handle<v8::Value> length(const v8::Arguments& args) {
v8::HandleScope scope;
// jsvec<T>* obj = NULL;
// obj = ObjectWrap::Unwrap<jsvec<T> >(args.This());
jsvec* obj = NULL;
obj = ObjectWrap::Unwrap<jsvec>(args.This());
cout << "Unwrapped VEC... ptr" << obj <<endl;
obj->redim(obj->dim+1);
// cout << "OBJ= "<< obj <<" D="<<obj->dim<<endl;
//obj->redim(5);
// cout << "NEWOBD ="<<obj->dim<<endl;
// jsvec<float> jsf(10,10);
// cout << "jsf w="<<jsf.dims[0]<<endl;
Handle<Value> w=Number::New(obj->dim);
return scope.Close(w);
}
public:
using vec<T>::dim;
using vec<T>::redim;
using vec<T>::operator=;
};
}
#endif
|
// check for valid parentheses
#include<bits/stdc++.h>
using namespace std;
bool balanced(string s)
{
int n=s.length(),i;
char x;
stack<int>a;
for(i=0;i<n;i++)
{
if(s[i]=='{'||s[i]=='('||s[i]=='[')
{
a.push(s[i]);
continue;
}
if(a.empty())
return false;
switch(s[i])
{
case '}':
x = a.top();
a.pop();
if(x=='('||x=='[')
return false;
break;
case ')':
x = a.top();
a.pop();
if(x=='{'||x=='[')
return false;
break;
case ']':
x = a.top();
a.pop();
if(x=='('||x=='{')
return false;
break;
}
}
return (a.empty());
}
int main()
{
string s;
cout<<"Enter parentheses ";
cin>>s;
if(balanced(s))
cout<<"\ntrue";
else
cout<<"\nfalse";
return 0;
}
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen (Arun MENON)
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESBasic_HArray1OfHArray1OfXYZ_HeaderFile
#define _IGESBasic_HArray1OfHArray1OfXYZ_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TColStd_Array1OfTransient.hxx>
#include <Standard_Transient.hxx>
#include <TColgp_HArray1OfXYZ.hxx>
#include <Standard_Integer.hxx>
class IGESBasic_HArray1OfHArray1OfXYZ;
DEFINE_STANDARD_HANDLE(IGESBasic_HArray1OfHArray1OfXYZ, Standard_Transient)
class IGESBasic_HArray1OfHArray1OfXYZ : public Standard_Transient
{
public:
Standard_EXPORT IGESBasic_HArray1OfHArray1OfXYZ(const Standard_Integer low, const Standard_Integer up);
Standard_EXPORT Standard_Integer Lower() const;
Standard_EXPORT Standard_Integer Upper() const;
Standard_EXPORT Standard_Integer Length() const;
Standard_EXPORT void SetValue (const Standard_Integer num, const Handle(TColgp_HArray1OfXYZ)& val);
Standard_EXPORT Handle(TColgp_HArray1OfXYZ) Value (const Standard_Integer num) const;
DEFINE_STANDARD_RTTI_INLINE(IGESBasic_HArray1OfHArray1OfXYZ,Standard_Transient)
protected:
private:
TColStd_Array1OfTransient thelist;
};
#endif // _IGESBasic_HArray1OfHArray1OfXYZ_HeaderFile
|
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2014 Live Networks, Inc. All rights reserved.
// A 'ServerMediaSubsession' object that creates new, unicast, "RTPSink"s
// on demand, from a H264 Elementary Stream video file.
// C++ header
#ifndef _H264_VIDEO_LIVE_SERVER_MEDIA_SUBSESSION_HH
#define _H264_VIDEO_LIVE_SERVER_MEDIA_SUBSESSION_HH
#ifndef _ON_DEMAND_SERVER_MEDIA_SUBSESSION_HH
#include "OnDemandServerMediaSubsession.hh"
#endif
#include "LiveStreamMediaSource.hh"
class H264VideoLiveServerMediaSubsession : public OnDemandServerMediaSubsession {
public:
static H264VideoLiveServerMediaSubsession*
createNew(UsageEnvironment& env, LiveStreamMediaSource& wisInput, Boolean reuseFirstSource);
// Used to implement "getAuxSDPLine()":
void checkForAuxSDPLine1();
void afterPlayingDummy1();
protected:
H264VideoLiveServerMediaSubsession(UsageEnvironment& env,
LiveStreamMediaSource& wisInput, Boolean reuseFirstSource);
// called only by createNew();
virtual ~H264VideoLiveServerMediaSubsession();
void setDoneFlag() { fDoneFlag = ~0; }
virtual void startStream(unsigned clientSessionId, void* streamToken,
TaskFunc* rtcpRRHandler,
void* rtcpRRHandlerClientData,
unsigned short& rtpSeqNum,
unsigned& rtpTimestamp,
ServerRequestAlternativeByteHandler* serverRequestAlternativeByteHandler,
void* serverRequestAlternativeByteHandlerClientData);
virtual void pauseStream(unsigned /*clientSessionId*/, void* streamToken);
virtual void seekStream(unsigned clientSessionId, void* streamToken, double& seekNPT, double streamDuration, u_int64_t& numBytes);
virtual void seekStream(unsigned clientSessionId, void* streamToken, char*& absStart, char*& absEnd);
protected: // redefined virtual functions
virtual char const* getAuxSDPLine(RTPSink* rtpSink,
FramedSource* inputSource);
virtual FramedSource* createNewStreamSource(unsigned clientSessionId,
unsigned& estBitrate);
virtual RTPSink* createNewRTPSink(Groupsock* rtpGroupsock,
unsigned char rtpPayloadTypeIfDynamic,
FramedSource* inputSource);
private:
Boolean fReuseFirstSource;
char* fAuxSDPLine;
char fDoneFlag; // used when setting up "fAuxSDPLine"
RTPSink* fDummyRTPSink; // ditto
LiveStreamMediaSource& fWISInput;
};
#endif
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avencoder.hpp"
#include "libyuv.h"
#include <time.h>
#include <Windows.h>
#define DEFAULT_BIT_RATE 10000000
#define DEFAULT_FRAME_RATE 33
#define DUMP_H264
#ifdef DUMP_H264
#define DUMP_FILE_NAME "output.h264"
static FILE* f = NULL;
#endif // DUMP_H264
static inline uint64_t get_time()
{
time_t clock;
timeval now;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm.tm_isdst = -1;
clock = mktime(&tm);
now.tv_sec = clock;
now.tv_usec = wtm.wMilliseconds * 1000;
return (uint64_t)now.tv_sec * 1000000 + (uint64_t)now.tv_usec;
}
AvEncoder::AvEncoder()
{
}
AvEncoder::~AvEncoder()
{
if (context) {
avcodec_free_context(&context);
}
if (frm420p) {
av_frame_free(&frm420p);
}
if (frmArgb) {
av_frame_free(&frmArgb);
}
if (pkt) {
av_packet_free(&pkt);
}
#ifdef DUMP_H264
if (f) {
fclose(f);
}
#endif // DUMP_H264
}
bool AvEncoder::init(char* codec_name, int width, int height)
{
codec = avcodec_find_encoder_by_name(codec_name);
if (!codec) {
printf("Codec '%s' not found\n", codec_name);
return false;
}
context = avcodec_alloc_context3(codec);
if (!context) {
printf("Could not allocate video codec context\n");
return false;
}
context->bit_rate = DEFAULT_BIT_RATE;
context->width = width;
context->height = height;
AVRational time_base = { 1, DEFAULT_FRAME_RATE };
context->time_base = time_base;
AVRational framerate = { DEFAULT_FRAME_RATE, 1 };
context->framerate = framerate;
context->gop_size = 100;
context->max_b_frames = 0;
context->pix_fmt = AV_PIX_FMT_YUV420P;
context->qmin = 15;
context->qmax = 35;
context->thread_count = 4;
if (codec->id == AV_CODEC_ID_H264) {
av_opt_set(context->priv_data, "preset", "ultrafast", 0);
av_opt_set(context->priv_data, "tune", "zerolatency", 0);
av_opt_set(context->priv_data, "profile", "baseline", 0);
}
int ret = avcodec_open2(context, codec, NULL);
if (ret < 0) {
printf("Could not open codec: %d\n", ret);
return false;
}
#ifdef DUMP_H264
/*f = fopen(DUMP_FILE_NAME, "wb");
if (!f) {
printf("Could not open %s\n", DUMP_FILE_NAME);
return false;
}*/
#endif // DUMP_H264
pkt = av_packet_alloc();
if (!pkt) {
return false;
}
frm420p = av_frame_alloc();
if (!frm420p) {
printf("Could not allocate video frame\n");
return false;
}
frmArgb = av_frame_alloc();
if (!frmArgb) {
printf("Could not allocate video frame\n");
return false;
}
frm420p->format = context->pix_fmt;
frm420p->width = context->width;
frm420p->height = context->height;
frmArgb->width = context->width;
frmArgb->height = context->height;
frmArgb->format = AV_PIX_FMT_RGBA;
ret = av_frame_get_buffer(frm420p, 32);
if (ret < 0) {
printf("Could not allocate the video frame data\n");
return false;
}
return true;
}
void AvEncoder::encode(unsigned char* buffer)
{
av_image_fill_arrays(frmArgb->data, frmArgb->linesize, buffer, AV_PIX_FMT_RGBA, context->width, context->height, 32);
int ret;
static int j = 0;
rgba_to_yuv420(frmArgb, frm420p);
frm420p->pts = ++j;
/* send the frame to the encoder */
if (frm420p) {
printf("Send frame %3lld\n", frm420p->pts);
}
ret = avcodec_send_frame(context, frm420p);
if (ret < 0) {
printf("Error sending a frame for encoding\n");
return;
}
while (ret >= 0) {
ret = avcodec_receive_packet(context, pkt);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
return;
else if (ret < 0) {
fprintf(stderr, "Error during encoding\n");
exit(1);
}
printf("Write packet %3lld(size=%5d)\n", pkt->pts, pkt->size);
#ifdef DUMP_H264
char file[200];
sprintf(file, "%d.h264", j);
f = fopen(file, "wb");
fwrite(pkt->data, 1, pkt->size, f);
fclose(f);
#endif // DUMP_H264
av_packet_unref(pkt);
}
}
bool AvEncoder::rgba_to_yuv420(AVFrame* frmArgb, AVFrame* frm420p)
{
uint64_t start = get_time();
libyuv::ARGBToI420(frmArgb->data[0], frmArgb->linesize[0], frm420p->data[0], frm420p->linesize[0], frm420p->data[1], frm420p->linesize[1], frm420p->data[2], frm420p->linesize[2], context->width, context->height);
uint64_t end = get_time();
printf("yuv time is %u", end - start);
//return true;
struct SwsContext* sws = sws_getContext(context->width, context->height, AV_PIX_FMT_RGBA,
context->width, context->height, AV_PIX_FMT_YUV420P, SWS_POINT, NULL, NULL, NULL);
int ret = sws_scale(sws, frmArgb->data, frmArgb->linesize, 0, context->height, frm420p->data, frm420p->linesize);
printf("scale time is %u", get_time() - end);
sws_freeContext(sws);
return (ret == context->height) ? true : false;
}
|
#pragma once
#include "declspec.h"
#include <string>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/VideoMode.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/NonCopyable.hpp>
#include "ResourceHolder.h"
namespace pure
{
class PUREENGINE_API Game : private sf::NonCopyable
{
public:
Game();
virtual ~Game();
const sf::RenderWindow& getWindow() const;
void createWindow(const sf::VideoMode vm, const std::string& title);
void start();
void setFPS(bool show);
void setFrameTime(float framesPerSecond);
void setUseFixedTimeStep(bool shouldUseTimeStep);
protected:
sf::RenderWindow m_window;
ResourceHolder m_resources;
virtual void onGameStart() = 0;
virtual void draw() = 0;
virtual void update(float deltaTime) = 0;
virtual void handleInput(const sf::Event& event) { }
private:
std::string m_name;
bool m_bShowFPS;
bool m_bUseFixedTimeStep;
sf::Time m_timePerFrame;
void processInput();
void render();
};
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.app18_FuseControlsTextControl_Value_Property.h>
#include <Fuse.Controls.TextControl.h>
#include <Uno.Bool.h>
#include <Uno.UX.IPropertyListener.h>
#include <Uno.UX.PropertyObject.h>
#include <Uno.UX.Selector.h>
static uType* TYPES[1];
namespace g{
// internal sealed class app18_FuseControlsTextControl_Value_Property :301
// {
static void app18_FuseControlsTextControl_Value_Property_build(uType* type)
{
::TYPES[0] = ::g::Fuse::Controls::TextControl_typeof();
type->SetBase(::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL));
type->SetFields(1,
::TYPES[0/*Fuse.Controls.TextControl*/], offsetof(app18_FuseControlsTextControl_Value_Property, _obj), uFieldFlagsWeak);
}
::g::Uno::UX::Property1_type* app18_FuseControlsTextControl_Value_Property_typeof()
{
static uSStrong< ::g::Uno::UX::Property1_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Uno::UX::Property1_typeof();
options.FieldCount = 2;
options.ObjectSize = sizeof(app18_FuseControlsTextControl_Value_Property);
options.TypeSize = sizeof(::g::Uno::UX::Property1_type);
type = (::g::Uno::UX::Property1_type*)uClassType::New("app18_FuseControlsTextControl_Value_Property", options);
type->fp_build_ = app18_FuseControlsTextControl_Value_Property_build;
type->fp_Get1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, uTRef))app18_FuseControlsTextControl_Value_Property__Get1_fn;
type->fp_get_Object = (void(*)(::g::Uno::UX::Property*, ::g::Uno::UX::PropertyObject**))app18_FuseControlsTextControl_Value_Property__get_Object_fn;
type->fp_Set1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, void*, uObject*))app18_FuseControlsTextControl_Value_Property__Set1_fn;
type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_FuseControlsTextControl_Value_Property__get_SupportsOriginSetter_fn;
return type;
}
// public app18_FuseControlsTextControl_Value_Property(Fuse.Controls.TextControl obj, Uno.UX.Selector name) :304
void app18_FuseControlsTextControl_Value_Property__ctor_3_fn(app18_FuseControlsTextControl_Value_Property* __this, ::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector* name)
{
__this->ctor_3(obj, *name);
}
// public override sealed string Get(Uno.UX.PropertyObject obj) :306
void app18_FuseControlsTextControl_Value_Property__Get1_fn(app18_FuseControlsTextControl_Value_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString** __retval)
{
return *__retval = uPtr(uCast< ::g::Fuse::Controls::TextControl*>(obj, ::TYPES[0/*Fuse.Controls.TextControl*/]))->Value(), void();
}
// public app18_FuseControlsTextControl_Value_Property New(Fuse.Controls.TextControl obj, Uno.UX.Selector name) :304
void app18_FuseControlsTextControl_Value_Property__New1_fn(::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector* name, app18_FuseControlsTextControl_Value_Property** __retval)
{
*__retval = app18_FuseControlsTextControl_Value_Property::New1(obj, *name);
}
// public override sealed Uno.UX.PropertyObject get_Object() :305
void app18_FuseControlsTextControl_Value_Property__get_Object_fn(app18_FuseControlsTextControl_Value_Property* __this, ::g::Uno::UX::PropertyObject** __retval)
{
return *__retval = __this->_obj, void();
}
// public override sealed void Set(Uno.UX.PropertyObject obj, string v, Uno.UX.IPropertyListener origin) :307
void app18_FuseControlsTextControl_Value_Property__Set1_fn(app18_FuseControlsTextControl_Value_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString* v, uObject* origin)
{
uPtr(uCast< ::g::Fuse::Controls::TextControl*>(obj, ::TYPES[0/*Fuse.Controls.TextControl*/]))->SetValue(v, origin);
}
// public override sealed bool get_SupportsOriginSetter() :308
void app18_FuseControlsTextControl_Value_Property__get_SupportsOriginSetter_fn(app18_FuseControlsTextControl_Value_Property* __this, bool* __retval)
{
return *__retval = true, void();
}
// public app18_FuseControlsTextControl_Value_Property(Fuse.Controls.TextControl obj, Uno.UX.Selector name) [instance] :304
void app18_FuseControlsTextControl_Value_Property::ctor_3(::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector name)
{
ctor_2(name);
_obj = obj;
}
// public app18_FuseControlsTextControl_Value_Property New(Fuse.Controls.TextControl obj, Uno.UX.Selector name) [static] :304
app18_FuseControlsTextControl_Value_Property* app18_FuseControlsTextControl_Value_Property::New1(::g::Fuse::Controls::TextControl* obj, ::g::Uno::UX::Selector name)
{
app18_FuseControlsTextControl_Value_Property* obj1 = (app18_FuseControlsTextControl_Value_Property*)uNew(app18_FuseControlsTextControl_Value_Property_typeof());
obj1->ctor_3(obj, name);
return obj1;
}
// }
} // ::g
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author spoon
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/FishEyeLayouter.h"
void FishEyeLayouter::CalculateFishSizes()
{
if (m_calculated_rows && m_calculated_columns)
return;
// check if fisheye is required
int i;
int grid_width = m_grid_rect.width;
for (i = 0; i < (int)m_col_count-1; ++i)
grid_width -= m_column_info[i].margin;
int total_width = 0;
for (i = 0; i < (int)m_col_count; ++i)
total_width += this->m_column_info[i].preferred_size;
// If all items fit with their requested size, just do a normal layout
if (total_width <= grid_width)
{
int curpos = 0;
for (i = 0; i < (int)m_col_count; ++i)
{
m_column_info[i].size = m_column_info[i].preferred_size;
m_column_info[i].position = curpos;
curpos += m_column_info[i].size+m_column_info[i].margin;
}
m_calculated_columns = m_calculated_rows = TRUE;
return;
}
// Count how many fisheye slots are in use
// The selected has prefered width, the ones next to it common width + 2/3 of prefered width - common width and the one next to that 1/3...
// The slots is defined as number of 1/3
int fish_slots = 0;
for (i = max(m_selected-2, 0); i <= m_selected+2 && i < (int)m_col_count; ++i)
{
fish_slots += 3-abs(i-m_selected);
}
// Try to keep the selected tab it's prefered size.
// The total width of all fisheye tabs are 3*prefered width
// Leave some space for other tabs by making sure one tab is less than 25% of the space
// gives a maximum coverage of 1/4*3 = 75%
int fish_base_width = m_column_info[m_selected].preferred_size;
if (fish_base_width > grid_width/4)
fish_base_width = grid_width/4;
// The base width which is used on non fisheye tabs is fish_slots/3 * (prefered_width-base_width) + base_width * num_items = total_width
// or, base_width = (total_width-(prefered_width*fish_slots)/3) / (num_items-fish_slots/3)
int base_width = 3*grid_width-(fish_base_width*fish_slots);
base_width = base_width / (3*m_col_count-fish_slots);
// The width of the second is base_width+(prefered-base)*2/3 to make sure they are not smaller than the non-fisheye tabs
fish_base_width -= base_width;
int fish_widths[3];
fish_widths[0] = base_width+fish_base_width;
fish_widths[1] = base_width+(fish_base_width*2)/3;
fish_widths[2] = base_width+fish_base_width/3;
// Spread out the unused amount on the slots
int unused_width = grid_width-m_col_count*base_width;
for (i = max(m_selected-2, 0); i <= m_selected+2 && i < (int)m_col_count; ++i)
{
unused_width -= fish_widths[op_abs(i-m_selected)]-base_width;
}
int fp_increase = (unused_width<<16)/m_col_count;
int fp_fracpoint = 0;
int curpos = 0;
for (i = 0; i < (int)m_col_count; ++i)
{
fp_fracpoint += fp_increase;
if (i >= m_selected-2 && i <= m_selected+2)
m_column_info[i].size = fish_widths[op_abs(i-m_selected)];
else
m_column_info[i].size = base_width;
m_column_info[i].size += fp_fracpoint>>16;
fp_fracpoint -= fp_fracpoint&0xffff0000;
m_column_info[i].position = curpos;
curpos += m_column_info[i].size+m_column_info[i].margin;
}
m_calculated_columns = m_calculated_rows = TRUE;
}
OpRect FishEyeLayouter::GetLayoutRectForCell(unsigned col, unsigned row, unsigned colspan, unsigned rowspan)
{
OP_ASSERT(row == 0 && colspan == 1 && rowspan == 1);
CalculateFishSizes();
return OpRect(m_column_info[col].position, 0, m_column_info[col].size, m_row_info[row].preferred_size);
}
|
// Generated by gencpp from file node_robot_msgs/agent_task_2.msg
// DO NOT EDIT!
#ifndef NODE_ROBOT_MSGS_MESSAGE_AGENT_TASK_2_H
#define NODE_ROBOT_MSGS_MESSAGE_AGENT_TASK_2_H
#include <ros/service_traits.h>
#include <node_robot_msgs/agent_task_2Request.h>
#include <node_robot_msgs/agent_task_2Response.h>
namespace node_robot_msgs
{
struct agent_task_2
{
typedef agent_task_2Request Request;
typedef agent_task_2Response Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct agent_task_2
} // namespace node_robot_msgs
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::node_robot_msgs::agent_task_2 > {
static const char* value()
{
return "507b103286c30709359161b3b51d9c4a";
}
static const char* value(const ::node_robot_msgs::agent_task_2&) { return value(); }
};
template<>
struct DataType< ::node_robot_msgs::agent_task_2 > {
static const char* value()
{
return "node_robot_msgs/agent_task_2";
}
static const char* value(const ::node_robot_msgs::agent_task_2&) { return value(); }
};
// service_traits::MD5Sum< ::node_robot_msgs::agent_task_2Request> should match
// service_traits::MD5Sum< ::node_robot_msgs::agent_task_2 >
template<>
struct MD5Sum< ::node_robot_msgs::agent_task_2Request>
{
static const char* value()
{
return MD5Sum< ::node_robot_msgs::agent_task_2 >::value();
}
static const char* value(const ::node_robot_msgs::agent_task_2Request&)
{
return value();
}
};
// service_traits::DataType< ::node_robot_msgs::agent_task_2Request> should match
// service_traits::DataType< ::node_robot_msgs::agent_task_2 >
template<>
struct DataType< ::node_robot_msgs::agent_task_2Request>
{
static const char* value()
{
return DataType< ::node_robot_msgs::agent_task_2 >::value();
}
static const char* value(const ::node_robot_msgs::agent_task_2Request&)
{
return value();
}
};
// service_traits::MD5Sum< ::node_robot_msgs::agent_task_2Response> should match
// service_traits::MD5Sum< ::node_robot_msgs::agent_task_2 >
template<>
struct MD5Sum< ::node_robot_msgs::agent_task_2Response>
{
static const char* value()
{
return MD5Sum< ::node_robot_msgs::agent_task_2 >::value();
}
static const char* value(const ::node_robot_msgs::agent_task_2Response&)
{
return value();
}
};
// service_traits::DataType< ::node_robot_msgs::agent_task_2Response> should match
// service_traits::DataType< ::node_robot_msgs::agent_task_2 >
template<>
struct DataType< ::node_robot_msgs::agent_task_2Response>
{
static const char* value()
{
return DataType< ::node_robot_msgs::agent_task_2 >::value();
}
static const char* value(const ::node_robot_msgs::agent_task_2Response&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // NODE_ROBOT_MSGS_MESSAGE_AGENT_TASK_2_H
|
#pragma once
#include <stdint.h>
class Game
{
public:
void Move(int m, int r, float seconds);
float playerX, playerY, playerA;
Game();
~Game();
};
|
#include "rtc.h"
#include "RTClib.h"
RTC_DS3231 RtcTime;
uint16_t _timeYear = 2020;
uint8_t _timeMonth = 1;
uint8_t _timeDay = 1;
uint8_t _timeHour = 0;
uint8_t _timeMinute = 0;
uint8_t _timeSecond = 0;
uint8_t _timeDayOfWeek = -1; //0 = sunday, 6 = saturday
bool CRtc::update() //Copy RTC values to time data
{
DateTime now = RtcTime.now();
//Check if RTC returned valid data
if ((now.month() > 12) || (now.day() > 31) || (now.hour() > 23) || (now.minute() > 59) || (now.second() > 59))
{
Serial.println("[E][Rtc] RTC returned invalid data:");
printf("%04u/%02u/%02u - %02u:%02u:%02u\n", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); //Set the time from web, this could be delayed by the update time, but at least its valid data. Time will sync later.
RtcTime.adjust(DateTime(_onlineTimeYear, _onlineTimeMonth, _onlineTimeDay, _onlineTimeHour, _onlineTimeMinute, _onlineTimeSecond));
return false;
}
else
{
_timeYear = now.year();
_timeMonth = now.month();
_timeDay = now.day();
_timeDayOfWeek = now.dayOfTheWeek();
_timeHour = now.hour();
_timeMinute = now.minute();
_timeSecond = now.second();
return true;
}
return false;
}
//Set the time for the RTC
void CRtc::setTime(uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second)
{
RtcTime.adjust(DateTime(year, month, day, hour, minute, second));
}
//Initialize RTC
bool CRtc::init()
{
if (RtcTime.begin())
{
if (RtcTime.lostPower())
{
Serial.println("[I][Rtc] RTC lost power. Setting time with online time on next check.");
}
return true;
}
else
Serial.println("[E][Rtc] Could not find RTC.");
return false;
}
//Check if rtc is on
bool CRtc::checkRtc()
{
return RtcTime.begin();
}
|
#ifndef CORE_NET_EVENTLOOPPOOL_H
#define CORE_NET_EVENTLOOPPOOL_H
#include "EventLoop.h"
#include "lock.hpp"
#include <map>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <pthread.h>
namespace core { namespace net {
class EventLoopPool : private boost::noncopyable
{
public:
static bool InitEventLoopPool(int tcp_in_each_innerloop = 0);
static void DestroyEventLoopPool();
static bool CreateEventLoop(const std::string& name);
static void TerminateLoop(const std::string& name);
static boost::shared_ptr< EventLoop > GetEventLoop(const std::string& name);
//boost::shared_ptr< EventLoop > GetInnerEventLoop(TcpSockSmartPtr sp_tcp);
static bool AddTcpSockToInnerLoop(TcpSockSmartPtr sp_tcp);
static bool AddTcpSockToLoop(const std::string& loopname, TcpSockSmartPtr sp_tcp);
private:
EventLoopPool();
~EventLoopPool();
};
} }
#endif
|
#include <iostream>
#include <cmath>
using namespace std;
int n;
int fact(){
if(n == 0){
return 0;
}
int count_2 = 0;
int count_5 = 0;
for (int i = 1; i <= n; i++){
int curNum = i;
while(true){
if(curNum % 2 != 0 && curNum % 5 != 0){
break;
}
if(curNum % 2 == 0){
count_2++;
curNum = curNum / 2;
}
if(curNum % 5 == 0){
count_5++;
curNum = curNum / 5;
}
}
}
return (count_2 > count_5) ? count_5 : count_2;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
cout << fact() << '\n';
return 0;
}
|
#include "pen.h"
#include "fountain.h"
#include "rbp.h"
using namespace std;
void WriteWithPen(Pen &pen) {
std::cout << pen.drawLine() << std::endl;
std::cout << pen.drawCircle() << std::endl;
}
int main() {
FountainPen fp;
WriteWithPen(fp);
RollerBallPen rbp("A Pen that Uses a Roller Ball");
WriteWithPen(rbp);
Pen pen;
WriteWithPen(pen);
return 0;
}
|
/*! @file LogVol_ShieldingPSDCone.hh
@brief Defines mandatory user class LogVol_ShieldingPSDCone.
@date August, 2012
@author Flechas (D. C. Flechas dcflechasg@unal.edu.co)
@version 1.9
In this header file, the 'physical' setup is defined: materials, geometries and positions.
This class defines the experimental hall used in the toolkit.
*/
/* no-geant4 classes*/
#include "LogVol_ShieldingPSDCone.hh"
/* units and constants */
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
/* geometric objects */
#include "G4Box.hh"
#include "G4Polycone.hh"
/* logic and physical volume */
#include "G4LogicalVolume.hh"
/* geant4 materials */
#include "G4NistManager.hh"
/* visualization */
#include "G4VisAttributes.hh"
LogVol_ShieldingPSDCone:: LogVol_ShieldingPSDCone(G4String fname,G4double fIrad,G4double fOrad,G4double fheight,G4double fang,G4Material* fmaterial):
G4LogicalVolume(new G4Box(fname+"_Sol",10*mm, 10*mm, 10*mm),fmaterial,fname,0,0,0)
{
/* set variables */
SetName(fname);
// Dimensions //
SetOuterRadius(fOrad);
SetInnerRadius(fIrad);
if(fheight>2.0*mm)
SetHeight(fheight);
else
{
SetHeight(2.0*mm);
G4cout<<"\n"<<"\n"<<"*********** WARNING MESSAGE ***********"<<"\n"<<G4endl;
G4cout<<"WARNING:: Height of the collimator is smaller than source"<<G4endl;
G4cout<<"Height of collimator ro sample will be 2 mm"<<"\n"<<G4endl;
}
SetAngOpening(fang);
// Construct solid volume //
ConstructSolidVol_ShieldingPSDCone();
//*** Visualization ***//
G4VisAttributes* black_vis
= new G4VisAttributes(true,G4Colour(0.1,0.1,0.1));
black_vis->SetForceWireframe(false);
black_vis->SetForceSolid(false);
this->SetVisAttributes(black_vis);
}
LogVol_ShieldingPSDCone::~LogVol_ShieldingPSDCone()
{}
void LogVol_ShieldingPSDCone::ConstructSolidVol_ShieldingPSDCone(void)
{
G4double hcog = 1.0*mm;
G4double rinner1=InnerRadius+hcog*std::tan(AngOp/rad);
G4double rinner2=rinner1+(Height-hcog)*std::tan(AngOp/rad);
G4double MaxRadius2=OuterRadius+(Height-hcog)*std::tan((AngOp-5.0*deg)/rad);
const G4int numZPlanesShieldingPSDCone=3;
const G4double zPlaneShieldingPSDCone[]={0.*mm,hcog,Height};
const G4double rInnerShieldingPSDCone[]={InnerRadius,rinner1,rinner2};
const G4double rOuterShieldingPSDCone[]={OuterRadius,OuterRadius,MaxRadius2};
ShieldingPSDCone_solid = new G4Polycone(Name+"_Sol",0.*rad,2*M_PI*rad,
numZPlanesShieldingPSDCone,
zPlaneShieldingPSDCone,
rInnerShieldingPSDCone,
rOuterShieldingPSDCone);
/*** Main trick here: Set the new solid volume ***/
SetSolidVol_ShieldingPSDCone();
}
void LogVol_ShieldingPSDCone::SetSolidVol_ShieldingPSDCone(void)
{
/*** Main trick here: Set the new solid volume ***/
if(ShieldingPSDCone_solid)
this->SetSolid(ShieldingPSDCone_solid);
}
|
// Moduł Scan.cpp
// =================
// Defnicje funkcji składowych klasy Scan, tabeli leksemów AT
// i tabeli słów kluczowych.
//
#include "Scan.h"
char *AT[MAXSYM+1] = // Tabela Atomów (dla komunikatów o błędach
{
"if", "nothing", "frac", "str", "bool",
"var", "else", "return", "true", "false", "input",
"while", "print", "func",
"ident", "fracconst","strconst",
"*", "+", "-", "||", "&&", "/", "}", "!", "{", "<", ">", "==", ")", "(",
",", ".", ":", "=", "others"
};
Scan::KeyRec Scan::KT[NKEYS]= // Kolejność wg funkcji hash(keyword)
{
// Keyword Atom hash(keyword)
//-------------------------------------------
{ "bool", boolsy }, // 0
{ "nothing", nothingsy}, // 1
{ "return", returnsy }, // 2
{ "true", truesy}, // 3
{ "var", varsy }, // 4
{ "func", funcsy }, // 5
{ "input", inputsy }, // 6
{ "false", falsesy }, // 7
{ "print", printsy }, // 8
{ "else", elsesy }, // 9
{ "str", strsy }, // 10
{ "while", whilesy }, //11
{ "if", ifsy }, //12
{ "frac", fracsy } //13
};
SymType Scan::NextSymbol()
{
do
{
while(isspace(c)) Nextc(); // Pomiń znaki białe
if(c==EOF) return others;
if(c=='/')
{
atompos = src.GetPos(); // Może być divop albo komentarz
Nextc();
if (c == '*')
{
Nextc();
while (true)
{
if (c == '*')
{
Nextc();
if (c == '/')
{
Nextc();
break;
}
else
continue;
}
else if (c == EOF)
{
ScanError(UNTERMCOMM, "Niezakończony komentarz");
return others;
}
Nextc();
}
}
else
return divop;
}
} while(isspace(c) || c=='/');
atompos=src.GetPos(); // Będzie jakiś atom leksykalny
//---Identyfikator lub słowo kluczowe
if(isalpha(c))
{ unsigned len, h;
spell.clear();
do
{ spell.push_back(c);
Nextc();
} while(isalnum(c));
len = spell.size();
h = hash(spell);
if(KT[h].kw == spell)
return KT[h].atom;
else return ident;
}
else
//---Stała ułamkowa
if(isdigit(c))
{
bool pointSeen = false;
bool underscoreSeen = false;
unsigned wholes = 0, nom = 0, denom = 1;
do
{
bool big = false; unsigned long long ul = 0;
do
{
ul = ul * 10 + (c - '0');
big = big || ul>INT_MAX;
Nextc();
} while (isdigit(c));
if (big)
ScanError(ICONST2BIG, "Przekroczony zakres stałej całkowitej");
if (c == '.' && !pointSeen)
{
if (underscoreSeen)
{
ScanError(FCONSTMALFORM, "Niepoprawny format stałej ułamkowej");
fracconstant = Fraction(0, 0, 0, false);
}
else
{
pointSeen = true;
wholes = ul;
Nextc();
if (!isdigit(c))
{
ScanError(FCONSTMALFORM, "Niepoprawny format stałej ułamkowej");
fracconstant = Fraction(0, 0, 0, false);
}
}
}
else if (c == '_' && !underscoreSeen)
{
underscoreSeen = true;
nom = ul;
Nextc();
if (!isdigit(c))
{
ScanError(FCONSTMALFORM, "Niepoprawny format stałej ułamkowej");
fracconstant = Fraction(0, 0, 0, false);
}
}
else
{
if (underscoreSeen)
{
if (!pointSeen)
wholes = 0;
denom = ul;
fracconstant = Fraction(wholes, nom, denom, false);
}
else if (!underscoreSeen && !pointSeen)
{
wholes = ul;
nom = 0;
denom = 1;
fracconstant = Fraction(wholes, nom, denom, false);
}
else
{
ScanError(FCONSTMALFORM, "Niepoprawny format stałej ułamkowej");
fracconstant = Fraction(0, 0, 0, false);
}
fracconstant.normalize();
return fracconst;
}
//intconstant = (int)ul;
} while (isdigit(c));
}
else
//---Pozostałe atomy
switch(c)
{
//----Stała znakowa
case '"': Nextc();
spell.clear();
while (c != '"')
{
if (c == EOF)
{
ScanError(UNTERMSTRCONST, "Niezakończony łańcuch znakowy");
return others;
}
spell.push_back(c);
Nextc();
}
Nextc();
return strconst;
//----Operatory 2 i 1 znakowe
case '=': Nextc();
if (c=='=') { Nextc(); return eqop; }
return becomes;
case '&': Nextc();
if (c == '&') { Nextc(); return andop; }
return others;
case '|': Nextc();
if (c == '|') { Nextc(); return orop; }
return others;
//----Operatory 1 znakowe
case '+': Nextc(); return addop;
case '-': Nextc(); return subop;
case '*': Nextc(); return mulop;
case '(': Nextc(); return lparent;
case ')': Nextc(); return rparent;
case ',': Nextc(); return comma;
case '>': Nextc(); return gtop;
case '<': Nextc(); return ltop;
case '.': Nextc(); return period;
case '!': Nextc(); return notop;
case '{': Nextc(); return beginsy;
case '}': Nextc(); return endsy;
case ':': Nextc(); return colon;
//----Nielegalne znaki
default : Nextc(); return others;
}
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <queue>
#include <unordered_set>
#define INT_MIN (1<<31)
#define INT_MAX (~INT_MIN)
#define UNREACHABLE (INT_MAX>>2)
using namespace std;
ifstream fin("11631_input.txt");
#define cin fin
typedef vector<int> ele;
struct
{
bool operator()(const ele & a, const ele & b)
{
return a[2] < b[2];
}
} my_comp_0;
int get_father(int p, vector<int> & union_find_set)
{
int p_backup = p;
while (union_find_set[p] != p)
p = union_find_set[p];
union_find_set[p_backup] = p;
return p;
}
int main()
{
int n, m;
cin >> m >> n;
while (m && n)
{
vector<ele> edges;
int sum = 0;
for (int i = 0; i < n; i++)
{
edges.push_back(ele(3, 0));
for (int j = 0; j <= 2; j++)
cin >> edges[i][j];
sum += edges[i][2];
}
sort(edges.begin(), edges.end(), my_comp_0);
vector<int> union_find_set(m, 0);
for (int i = 0; i < m; i++)
union_find_set[i] = i;
int mst = 0;
for (auto it : edges)
{
int fa1, fa2;
fa1 = get_father(it[0], union_find_set);
fa2 = get_father(it[1], union_find_set);
if (fa2 != fa1)
{
mst += it[2];
union_find_set[fa2] = fa1;
}
}
cout << sum - mst << endl;
cin >> m >> n;
}
}
|
#include "m_pd.h"
//IMPROVE - inlets
//FIXME - fixed sample rate
//TODO - help file
#include "warps/dsp/modulator.h"
static t_class *wrps_tilde_class;
typedef struct _wrps_tilde {
t_object x_obj;
t_float f_dummy;
t_float f_drive1;
t_float f_drive2;
t_float f_algo;
t_float f_density;
// CLASS_MAINSIGNALIN = in_left;
t_inlet* x_in_right;
t_inlet* x_in_amount;
t_outlet* x_out_left;
t_outlet* x_out_right;
// clouds:reverb
warps::Modulator processor;
warps::ShortFrame* ibuf;
warps::ShortFrame* obuf;
int iobufsz;
} t_wrps_tilde;
//define pure data methods
extern "C" {
t_int* wrps_tilde_render(t_int *w);
void wrps_tilde_dsp(t_wrps_tilde *x, t_signal **sp);
void wrps_tilde_free(t_wrps_tilde *x);
void* wrps_tilde_new(t_floatarg f);
void wrps_tilde_setup(void);
void wrps_tilde_drive1(t_wrps_tilde *x, t_floatarg f);
void wrps_tilde_drive2(t_wrps_tilde *x, t_floatarg f);
void wrps_tilde_algo(t_wrps_tilde *x, t_floatarg f);
void wrps_tilde_density(t_wrps_tilde *x, t_floatarg f);
}
// puredata methods implementation -start
t_int *wrps_tilde_render(t_int *w)
{
t_wrps_tilde *x = (t_wrps_tilde *)(w[1]);
t_sample *in_left = (t_sample *)(w[2]);
t_sample *in_right = (t_sample *)(w[3]);
t_sample *out_left = (t_sample *)(w[4]);
t_sample *out_right = (t_sample *)(w[5]);
int n = (int)(w[6]);
if (n > x->iobufsz) {
delete [] x->ibuf;
delete [] x->obuf;
x->iobufsz = n;
x->ibuf = new warps::ShortFrame[x->iobufsz];
x->obuf = new warps::ShortFrame[x->iobufsz];
}
x->processor.mutable_parameters()->channel_drive[0]=x->f_drive1;
x->processor.mutable_parameters()->channel_drive[1]=x->f_drive2;
x->processor.mutable_parameters()->modulation_parameter=x->f_density;
x->processor.mutable_parameters()->modulation_algorithm=x->f_algo;
for (int i = 0; i < n; i++) {
x->ibuf[i].l = in_left[i] * 1024;
x->ibuf[i].r = in_right[i] * 1024;
}
x->processor.Process(x->ibuf, x->obuf,n);
for (int i = 0; i < n; i++) {
out_left[i] = x->obuf[i].l / 1024.0f;
out_right[i] = x->obuf[i].r / 1024.0f;
}
return (w + 7); // # args + 1
}
void wrps_tilde_dsp(t_wrps_tilde *x, t_signal **sp)
{
// add the perform method, with all signal i/o
dsp_add(wrps_tilde_render, 6,
x,
sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[3]->s_vec, // signal i/o (clockwise)
sp[0]->s_n);
}
void wrps_tilde_free(t_wrps_tilde *x)
{
delete [] x->ibuf;
delete [] x->obuf;
inlet_free(x->x_in_right);
inlet_free(x->x_in_amount);
outlet_free(x->x_out_left);
outlet_free(x->x_out_right);
}
void *wrps_tilde_new(t_floatarg f)
{
t_wrps_tilde *x = (t_wrps_tilde *) pd_new(wrps_tilde_class);
x->iobufsz = 64;
x->ibuf = new warps::ShortFrame[x->iobufsz];
x->obuf = new warps::ShortFrame[x->iobufsz];
x->f_drive1 = 1.0f;
x->f_drive2 = 1.0f;
x->f_algo = 0.5f;
x->f_density = 0.5f;
x->x_in_right = inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
x->x_out_left = outlet_new(&x->x_obj, &s_signal);
x->x_out_right = outlet_new(&x->x_obj, &s_signal);
x->processor.Init(44100.0f);
return (void *)x;
}
void wrps_tilde_drive1(t_wrps_tilde *x, t_floatarg f)
{
x->f_drive1 = f;
}
void wrps_tilde_drive2(t_wrps_tilde *x, t_floatarg f)
{
x->f_drive2 = f;
}
void wrps_tilde_density(t_wrps_tilde *x, t_floatarg f)
{
x->f_density= f;
}
void wrps_tilde_algo(t_wrps_tilde *x, t_floatarg f)
{
x->f_algo = f;
}
void wrps_tilde_setup(void) {
wrps_tilde_class = class_new(gensym("wrps~"),
(t_newmethod)wrps_tilde_new,
0, sizeof(t_wrps_tilde),
CLASS_DEFAULT,
A_DEFFLOAT, A_NULL);
class_addmethod( wrps_tilde_class,
(t_method)wrps_tilde_dsp,
gensym("dsp"), A_NULL);
CLASS_MAINSIGNALIN(wrps_tilde_class, t_wrps_tilde, f_dummy);
class_addmethod(wrps_tilde_class,
(t_method) wrps_tilde_drive1, gensym("drive1"),
A_DEFFLOAT, A_NULL);
class_addmethod(wrps_tilde_class,
(t_method) wrps_tilde_drive2, gensym("drive2"),
A_DEFFLOAT, A_NULL);
class_addmethod(wrps_tilde_class,
(t_method) wrps_tilde_density, gensym("density"),
A_DEFFLOAT, A_NULL);
class_addmethod(wrps_tilde_class,
(t_method) wrps_tilde_algo, gensym("algo"),
A_DEFFLOAT, A_NULL);
}
// puredata methods implementation - end
|
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _gp_Hypr2d_HeaderFile
#define _gp_Hypr2d_HeaderFile
#include <gp.hxx>
#include <gp_Ax22d.hxx>
#include <gp_Ax2d.hxx>
#include <gp_Pnt2d.hxx>
#include <Standard_DomainError.hxx>
#include <Standard_ConstructionError.hxx>
//! Describes a branch of a hyperbola in the plane (2D space).
//! A hyperbola is defined by its major and minor radii, and
//! positioned in the plane with a coordinate system (a
//! gp_Ax22d object) of which:
//! - the origin is the center of the hyperbola,
//! - the "X Direction" defines the major axis of the hyperbola, and
//! - the "Y Direction" defines the minor axis of the hyperbola.
//! This coordinate system is the "local coordinate system"
//! of the hyperbola. The orientation of this coordinate
//! system (direct or indirect) gives an implicit orientation to
//! the hyperbola. In this coordinate system, the equation of
//! the hyperbola is:
//! X*X/(MajorRadius**2)-Y*Y/(MinorRadius**2) = 1.0
//! The branch of the hyperbola described is the one located
//! on the positive side of the major axis.
//! The following schema shows the plane of the hyperbola,
//! and in it, the respective positions of the three branches of
//! hyperbolas constructed with the functions OtherBranch,
//! ConjugateBranch1, and ConjugateBranch2:
//! @code
//! ^YAxis
//! |
//! FirstConjugateBranch
//! |
//! Other | Main
//! --------------------- C ------------------------------>XAxis
//! Branch | Branch
//! |
//! |
//! SecondConjugateBranch
//! |
//! @endcode
//! Warning
//! The major radius can be less than the minor radius.
//! See Also
//! gce_MakeHypr2d which provides functions for more
//! complex hyperbola constructions
//! Geom2d_Hyperbola which provides additional functions
//! for constructing hyperbolas and works, in particular, with
//! the parametric equations of hyperbolas
class gp_Hypr2d
{
public:
DEFINE_STANDARD_ALLOC
//! Creates of an indefinite hyperbola.
gp_Hypr2d()
: majorRadius (RealLast()),
minorRadius (RealLast())
{}
//! Creates a hyperbola with radii theMajorRadius and
//! theMinorRadius, centered on the origin of theMajorAxis
//! and where the unit vector of theMajorAxis is the "X
//! Direction" of the local coordinate system of the
//! hyperbola. This coordinate system is direct if theIsSense
//! is true (the default value), and indirect if theIsSense is false.
//! Warnings :
//! It is yet possible to create an Hyperbola with
//! theMajorRadius <= theMinorRadius.
//! Raises ConstructionError if theMajorRadius < 0.0 or theMinorRadius < 0.0
gp_Hypr2d (const gp_Ax2d& theMajorAxis, const Standard_Real theMajorRadius,
const Standard_Real theMinorRadius, const Standard_Boolean theIsSense = Standard_True)
: majorRadius (theMajorRadius),
minorRadius (theMinorRadius)
{
pos = gp_Ax22d (theMajorAxis, theIsSense);
Standard_ConstructionError_Raise_if (theMinorRadius < 0.0 || theMajorRadius < 0.0,
"gp_Hypr2d() - invalid construction parameters");
}
//! a hyperbola with radii theMajorRadius and
//! theMinorRadius, positioned in the plane by coordinate system theA where:
//! - the origin of theA is the center of the hyperbola,
//! - the "X Direction" of theA defines the major axis of
//! the hyperbola, that is, the major radius
//! theMajorRadius is measured along this axis, and
//! - the "Y Direction" of theA defines the minor axis of
//! the hyperbola, that is, the minor radius
//! theMinorRadius is measured along this axis, and
//! - the orientation (direct or indirect sense) of theA
//! gives the implicit orientation of the hyperbola.
//! Warnings :
//! It is yet possible to create an Hyperbola with
//! theMajorRadius <= theMinorRadius.
//! Raises ConstructionError if theMajorRadius < 0.0 or theMinorRadius < 0.0
gp_Hypr2d (const gp_Ax22d& theA, const Standard_Real theMajorRadius, const Standard_Real theMinorRadius)
: pos (theA),
majorRadius (theMajorRadius),
minorRadius (theMinorRadius)
{
Standard_ConstructionError_Raise_if (theMinorRadius < 0.0 || theMajorRadius < 0.0,
"gp_Hypr2d() - invalid construction parameters");
}
//! Modifies this hyperbola, by redefining its local
//! coordinate system so that its origin becomes theP.
void SetLocation (const gp_Pnt2d& theP) { pos.SetLocation (theP); }
//! Modifies the major or minor radius of this hyperbola.
//! Exceptions
//! Standard_ConstructionError if theMajorRadius or
//! MinorRadius is negative.
void SetMajorRadius (const Standard_Real theMajorRadius)
{
Standard_ConstructionError_Raise_if (theMajorRadius < 0.0,
"gp_Hypr2d::SetMajorRadius() - major radius should be greater or equal zero");
majorRadius = theMajorRadius;
}
//! Modifies the major or minor radius of this hyperbola.
//! Exceptions
//! Standard_ConstructionError if MajorRadius or
//! theMinorRadius is negative.
void SetMinorRadius (const Standard_Real theMinorRadius)
{
Standard_ConstructionError_Raise_if (theMinorRadius < 0.0,
"gp_Hypr2d::SetMinorRadius() - minor radius should be greater or equal zero");
minorRadius = theMinorRadius;
}
//! Modifies this hyperbola, by redefining its local
//! coordinate system so that it becomes theA.
void SetAxis (const gp_Ax22d& theA) { pos.SetAxis (theA); }
//! Changes the major axis of the hyperbola. The minor axis is
//! recomputed and the location of the hyperbola too.
void SetXAxis (const gp_Ax2d& theA) { pos.SetXAxis (theA); }
//! Changes the minor axis of the hyperbola.The minor axis is
//! recomputed and the location of the hyperbola too.
void SetYAxis (const gp_Ax2d& theA) { pos.SetYAxis (theA); }
//! In the local coordinate system of the hyperbola the equation of
//! the hyperbola is (X*X)/(A*A) - (Y*Y)/(B*B) = 1.0 and the
//! equation of the first asymptote is Y = (B/A)*X
//! where A is the major radius of the hyperbola and B the minor
//! radius of the hyperbola.
//! Raises ConstructionError if MajorRadius = 0.0
gp_Ax2d Asymptote1() const;
//! In the local coordinate system of the hyperbola the equation of
//! the hyperbola is (X*X)/(A*A) - (Y*Y)/(B*B) = 1.0 and the
//! equation of the first asymptote is Y = -(B/A)*X
//! where A is the major radius of the hyperbola and B the minor
//! radius of the hyperbola.
//! Raises ConstructionError if MajorRadius = 0.0
gp_Ax2d Asymptote2() const;
//! Computes the coefficients of the implicit equation of
//! the hyperbola :
//! theA * (X**2) + theB * (Y**2) + 2*theC*(X*Y) + 2*theD*X + 2*theE*Y + theF = 0.
Standard_EXPORT void Coefficients (Standard_Real& theA, Standard_Real& theB, Standard_Real& theC,
Standard_Real& theD, Standard_Real& theE, Standard_Real& theF) const;
//! Computes the branch of hyperbola which is on the positive side of the
//! "YAxis" of <me>.
gp_Hypr2d ConjugateBranch1() const
{
gp_Dir2d aV (pos.YDirection());
Standard_Boolean isSign = (pos.XDirection().Crossed (pos.YDirection())) >= 0.0;
return gp_Hypr2d (gp_Ax2d (pos.Location(), aV), minorRadius, majorRadius, isSign);
}
//! Computes the branch of hyperbola which is on the negative side of the
//! "YAxis" of <me>.
gp_Hypr2d ConjugateBranch2() const
{
gp_Dir2d aV (pos.YDirection().Reversed());
Standard_Boolean isSign = (pos.XDirection().Crossed (pos.YDirection())) >= 0.0;
return gp_Hypr2d (gp_Ax2d (pos.Location(), aV), minorRadius, majorRadius, isSign);
}
//! Computes the directrix which is the line normal to the XAxis of the hyperbola
//! in the local plane (Z = 0) at a distance d = MajorRadius / e
//! from the center of the hyperbola, where e is the eccentricity of
//! the hyperbola.
//! This line is parallel to the "YAxis". The intersection point
//! between the "Directrix1" and the "XAxis" is the "Location" point
//! of the "Directrix1".
//! This point is on the positive side of the "XAxis".
gp_Ax2d Directrix1() const;
//! This line is obtained by the symmetrical transformation
//! of "Directrix1" with respect to the "YAxis" of the hyperbola.
gp_Ax2d Directrix2() const;
//! Returns the eccentricity of the hyperbola (e > 1).
//! If f is the distance between the location of the hyperbola
//! and the Focus1 then the eccentricity e = f / MajorRadius. Raises DomainError if MajorRadius = 0.0.
Standard_Real Eccentricity() const
{
Standard_DomainError_Raise_if (majorRadius <= gp::Resolution(),
"gp_Hypr2d::Eccentricity() - major radius is zero");
return sqrt (majorRadius * majorRadius + minorRadius * minorRadius) / majorRadius;
}
//! Computes the focal distance. It is the distance between the
//! "Location" of the hyperbola and "Focus1" or "Focus2".
Standard_Real Focal() const
{
return 2.0 * sqrt (majorRadius * majorRadius + minorRadius * minorRadius);
}
//! Returns the first focus of the hyperbola. This focus is on the
//! positive side of the "XAxis" of the hyperbola.
gp_Pnt2d Focus1() const
{
Standard_Real aC = sqrt (majorRadius * majorRadius + minorRadius * minorRadius);
return gp_Pnt2d (pos.Location().X() + aC * pos.XDirection().X(), pos.Location().Y() + aC * pos.XDirection().Y());
}
//! Returns the second focus of the hyperbola. This focus is on the
//! negative side of the "XAxis" of the hyperbola.
gp_Pnt2d Focus2() const
{
Standard_Real aC = sqrt(majorRadius * majorRadius + minorRadius * minorRadius);
return gp_Pnt2d(pos.Location().X() - aC * pos.XDirection().X(), pos.Location().Y() - aC * pos.XDirection().Y());
}
//! Returns the location point of the hyperbola.
//! It is the intersection point between the "XAxis" and
//! the "YAxis".
const gp_Pnt2d& Location() const { return pos.Location(); }
//! Returns the major radius of the hyperbola (it is the radius
//! corresponding to the "XAxis" of the hyperbola).
Standard_Real MajorRadius() const { return majorRadius; }
//! Returns the minor radius of the hyperbola (it is the radius
//! corresponding to the "YAxis" of the hyperbola).
Standard_Real MinorRadius() const { return minorRadius; }
//! Returns the branch of hyperbola obtained by doing the
//! symmetrical transformation of <me> with respect to the
//! "YAxis" of <me>.
gp_Hypr2d OtherBranch() const
{
Standard_Boolean isSign = (pos.XDirection().Crossed (pos.YDirection())) >= 0.0;
return gp_Hypr2d (gp_Ax2d (pos.Location(), pos.XDirection().Reversed()), majorRadius, minorRadius, isSign);
}
//! Returns p = (e * e - 1) * MajorRadius where e is the
//! eccentricity of the hyperbola.
//! Raises DomainError if MajorRadius = 0.0
Standard_Real Parameter() const
{
Standard_DomainError_Raise_if (majorRadius <= gp::Resolution(),
"gp_Hypr2d::Parameter() - major radius is zero");
return (minorRadius * minorRadius) / majorRadius;
}
//! Returns the axisplacement of the hyperbola.
const gp_Ax22d& Axis() const { return pos; }
//! Computes an axis whose
//! - the origin is the center of this hyperbola, and
//! - the unit vector is the "X Direction" or "Y Direction"
//! respectively of the local coordinate system of this hyperbola
//! Returns the major axis of the hyperbola.
gp_Ax2d XAxis() const { return pos.XAxis(); }
//! Computes an axis whose
//! - the origin is the center of this hyperbola, and
//! - the unit vector is the "X Direction" or "Y Direction"
//! respectively of the local coordinate system of this hyperbola
//! Returns the minor axis of the hyperbola.
gp_Ax2d YAxis() const { return pos.YAxis(); }
void Reverse()
{
gp_Dir2d aTemp = pos.YDirection();
aTemp.Reverse();
pos.SetAxis (gp_Ax22d(pos.Location(), pos.XDirection(), aTemp));
}
//! Reverses the orientation of the local coordinate system
//! of this hyperbola (the "Y Axis" is reversed). Therefore,
//! the implicit orientation of this hyperbola is reversed.
//! Note:
//! - Reverse assigns the result to this hyperbola, while
//! - Reversed creates a new one.
Standard_NODISCARD gp_Hypr2d Reversed() const;
//! Returns true if the local coordinate system is direct
//! and false in the other case.
Standard_Boolean IsDirect() const
{
return (pos.XDirection().Crossed (pos.YDirection())) >= 0.0;
}
Standard_EXPORT void Mirror (const gp_Pnt2d& theP);
//! Performs the symmetrical transformation of an hyperbola with
//! respect to the point theP which is the center of the symmetry.
Standard_NODISCARD Standard_EXPORT gp_Hypr2d Mirrored (const gp_Pnt2d& theP) const;
Standard_EXPORT void Mirror (const gp_Ax2d& theA);
//! Performs the symmetrical transformation of an hyperbola with
//! respect to an axis placement which is the axis of the symmetry.
Standard_NODISCARD Standard_EXPORT gp_Hypr2d Mirrored (const gp_Ax2d& theA) const;
void Rotate (const gp_Pnt2d& theP, const Standard_Real theAng) { pos.Rotate (theP, theAng); }
//! Rotates an hyperbola. theP is the center of the rotation.
//! theAng is the angular value of the rotation in radians.
Standard_NODISCARD gp_Hypr2d Rotated (const gp_Pnt2d& theP, const Standard_Real theAng) const
{
gp_Hypr2d aH = *this;
aH.pos.Rotate (theP, theAng);
return aH;
}
void Scale (const gp_Pnt2d& theP, const Standard_Real theS);
//! Scales an hyperbola. <theS> is the scaling value.
//! If <theS> is positive only the location point is
//! modified. But if <theS> is negative the "XAxis" is
//! reversed and the "YAxis" too.
Standard_NODISCARD gp_Hypr2d Scaled (const gp_Pnt2d& theP, const Standard_Real theS) const;
void Transform (const gp_Trsf2d& theT);
//! Transforms an hyperbola with the transformation theT from
//! class Trsf2d.
Standard_NODISCARD gp_Hypr2d Transformed (const gp_Trsf2d& theT) const;
void Translate (const gp_Vec2d& theV) { pos.Translate (theV); }
//! Translates an hyperbola in the direction of the vector theV.
//! The magnitude of the translation is the vector's magnitude.
Standard_NODISCARD gp_Hypr2d Translated (const gp_Vec2d& theV) const
{
gp_Hypr2d aH = *this;
aH.pos.Translate (theV);
return aH;
}
void Translate(const gp_Pnt2d& theP1, const gp_Pnt2d& theP2) { pos.Translate (theP1, theP2); }
//! Translates an hyperbola from the point theP1 to the point theP2.
Standard_NODISCARD gp_Hypr2d Translated (const gp_Pnt2d& theP1, const gp_Pnt2d& theP2) const
{
gp_Hypr2d aH = *this;
aH.pos.Translate (theP1, theP2);
return aH;
}
private:
gp_Ax22d pos;
Standard_Real majorRadius;
Standard_Real minorRadius;
};
//=======================================================================
//function : Asymptote1
// purpose :
//=======================================================================
inline gp_Ax2d gp_Hypr2d::Asymptote1() const
{
Standard_ConstructionError_Raise_if (majorRadius <= gp::Resolution(),
"gp_Hypr2d::Asymptote1() - major radius is zero");
gp_Dir2d aVdir = pos.XDirection();
gp_XY aCoord1 (pos.YDirection().XY());
gp_XY aCoord2 = aCoord1.Multiplied (minorRadius / majorRadius);
aCoord1.Add (aCoord2);
aVdir.SetXY (aCoord1);
return gp_Ax2d (pos.Location(), aVdir);
}
//=======================================================================
//function : Asymptote2
// purpose :
//=======================================================================
inline gp_Ax2d gp_Hypr2d::Asymptote2() const
{
Standard_ConstructionError_Raise_if (majorRadius <= gp::Resolution(),
"gp_Hypr2d::Asymptote2() - major radius is zero");
gp_Vec2d aVdir = pos.XDirection();
gp_XY aCoord1 (pos.YDirection().XY());
gp_XY aCoord2 = aCoord1.Multiplied (-minorRadius / majorRadius);
aCoord1.Add (aCoord2);
aVdir.SetXY (aCoord1);
return gp_Ax2d (pos.Location(), aVdir);
}
//=======================================================================
//function : Directrix1
// purpose :
//=======================================================================
inline gp_Ax2d gp_Hypr2d::Directrix1() const
{
Standard_Real anE = Eccentricity();
gp_XY anOrig = pos.XDirection().XY();
anOrig.Multiply (majorRadius / anE);
anOrig.Add (pos.Location().XY());
return gp_Ax2d (gp_Pnt2d (anOrig), gp_Dir2d (pos.YDirection()));
}
//=======================================================================
//function : Directrix2
// purpose :
//=======================================================================
inline gp_Ax2d gp_Hypr2d::Directrix2() const
{
Standard_Real anE = Eccentricity();
gp_XY anOrig = pos.XDirection().XY();
anOrig.Multiply (Parameter() / anE);
anOrig.Add (Focus1().XY());
return gp_Ax2d (gp_Pnt2d (anOrig), gp_Dir2d (pos.YDirection()));
}
//=======================================================================
//function : Reversed
// purpose :
//=======================================================================
inline gp_Hypr2d gp_Hypr2d::Reversed() const
{
gp_Hypr2d aH = *this;
gp_Dir2d aTemp = pos.YDirection();
aTemp.Reverse ();
aH.pos.SetAxis (gp_Ax22d (pos.Location(),pos.XDirection(), aTemp));
return aH;
}
//=======================================================================
//function : Scale
// purpose :
//=======================================================================
inline void gp_Hypr2d::Scale (const gp_Pnt2d& theP, const Standard_Real theS)
{
majorRadius *= theS;
if (majorRadius < 0)
{
majorRadius = -majorRadius;
}
minorRadius *= theS;
if (minorRadius < 0)
{
minorRadius = -minorRadius;
}
pos.Scale (theP, theS);
}
//=======================================================================
//function : Scaled
// purpose :
//=======================================================================
inline gp_Hypr2d gp_Hypr2d::Scaled (const gp_Pnt2d& theP, const Standard_Real theS) const
{
gp_Hypr2d aH = *this;
aH.majorRadius *= theS;
if (aH.majorRadius < 0)
{
aH.majorRadius = -aH.majorRadius;
}
aH.minorRadius *= theS;
if (aH.minorRadius < 0)
{
aH.minorRadius = -aH.minorRadius;
}
aH.pos.Scale (theP, theS);
return aH;
}
//=======================================================================
//function : Transform
// purpose :
//=======================================================================
inline void gp_Hypr2d::Transform (const gp_Trsf2d& theT)
{
majorRadius *= theT.ScaleFactor();
if (majorRadius < 0)
{
majorRadius = -majorRadius;
}
minorRadius *= theT.ScaleFactor();
if (minorRadius < 0)
{
minorRadius = -minorRadius;
}
pos.Transform (theT);
}
//=======================================================================
//function : Transformed
// purpose :
//=======================================================================
inline gp_Hypr2d gp_Hypr2d::Transformed (const gp_Trsf2d& theT) const
{
gp_Hypr2d aH = *this;
aH.majorRadius *= theT.ScaleFactor();
if (aH.majorRadius < 0)
{
aH.majorRadius = -aH.majorRadius;
}
aH.minorRadius *= theT.ScaleFactor();
if (aH.minorRadius < 0)
{
aH.minorRadius = -aH.minorRadius;
}
aH.pos.Transform (theT);
return aH;
}
#endif // _gp_Hypr2d_HeaderFile
|
#include "DBClass.h"
#include <string>
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;
int DBClass::load(const char* filename, const char* key)
{
std::ifstream f(filename);
std::string s;
if (!f.good()) { return -1; }
while (f.good()) {
DBRecord newRecord;
int i;
for (i = 0; i < 3 && f.good(); i++) {
getline(f, s);
auto l = s.rfind("\"");
if (l == string::npos) {
i--;
continue;
}
auto pl = s.rfind("\"", l-1);
string ss = s.substr(pl+1, l-pl-1);
newRecord[i] = std::move(ss);
}
if (i == 3) {
data.push_back(std::move(newRecord));
}
}
f.close();
return 0;
}
void DBClass::printAll() const
{
for (const auto& e : data) {
e.print();
}
}
int DBClass::find(const char* secondname) const
{
for (unsigned int i = 0; i < data.size(); i++) {
if (data[i][1] == secondname) { return i; }
}
return -1;
}
int DBClass::add(const char* name, const char* second_name, const char* passport)
{
for (const auto& e : string(name)) {
if (!((e | 32) >= 'a' && (e | 32) <= 'z')) { return -1; }
}
for (const auto& e : string(second_name)) {
if (!((e | 32) >= 'a' && (e | 32) <= 'z')) { return -1; }
}
if (strlen(passport) != 11) { return -1; }
for (int i = 0; i < 4; i++) {
if (!(passport[i] >= '0' && passport[i] <= '9')) { return -1; }
}
if (passport[4] != ' ') { return -1; }
for (int i = 5; i < 11; i++) {
if (!(passport[i] >= '0' && passport[i] <= '9')) { return -1; }
}
data.push_back({name, second_name, passport});
return data.size() - 1;
}
int DBClass::remove(const int n)
{
if (n < 0 || (unsigned int) n >= data.size() - 1) { return -1; }
data.erase(data.begin() + n);
return 0;
}
void DBClass::save(const char* filename, const char* key)
{
ofstream f (filename);
for (const auto& e : data) {
f << "{" << endl;
f << "\t\"Name\"=\"" << e[0] << "\"" << endl;
f << "\t\"Second name\"=\"" << e[1] << "\"" << endl;
f << "\t\"Passport\"=\"" << e[2] << "\"" << endl;
f << "}" << endl;
}
}
void DBRecord::print() const
{
for (const auto& e : data) {
cout << e << '\t';
}
cout << endl;
}
|
#ifndef EXECUTIVE_H
#define EXECUTIVE_H
#include "MinMax.h"
#include <fstream>
#include <iostream>
using namespace std;
class executive {
private:
MinMax myheap;
MinMax myTest;
public:
executive(string _filename);
~executive();
void Print();
};
#endif
|
#include "network.h"
Network::Network(QObject *parent) : QObject(parent)
{
mngr = new QNetworkAccessManager(this);
}
QByteArray Network::get(QUrl u)
{
QNetworkReply *reply = mngr->get(QNetworkRequest(u));
// Wait for reply
QEventLoop wait;
connect(mngr, SIGNAL(finished(QNetworkReply*)), &wait, SLOT(quit()));
QTimer::singleShot(10000, &wait, SLOT(quit()));
wait.exec();
QByteArray answer = reply->readAll();
reply->deleteLater();
return answer;
}
Network::~Network()
{
delete mngr;
}
Network* Network::getInstance()
{
static Network *instance = new Network();
return instance;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <stack>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
// 昇順sort
#define sorti(x) sort(x.begin(), x.end())
// 降順sort
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
string s;
cin >> s;
stack<char> stc;
for (auto itr : s) {
if (itr != 'B') {
stc.push(itr);
} else {
if (stc.size() > 0) {
stc.pop();
} else {
;
}
}
}
vector<char> c;
while (stc.size() > 0) {
char tmp = stc.top();
stc.pop();
c.pb(tmp);
}
for (int i = c.size() - 1; i >= 0; --i) {
cout << c[i];
}
END;
}
|
//
// Created by 송지원 on 2020/07/21.
//
//바킹독님 코드. 어떤 수를 추가하거나 안하거나를 어떻게 구현하는가 했는데 나
// 재귀적으로 호출을 하면서 어떤 값을 더한 값으로 함수를 호출해주거나
// 현재 값 그대로 함수를 호출해주면
// 어떤 값을 더해주거나 안하거나 하는 경우의 수를 만족할 수 있다!!
#include <iostream>
using namespace std;
int n, s;
int arr[30];
int cnt = 0;
void func(int cur, int tot) {
if (cur == n) {
if(tot == s) cnt ++;
return;
}
func(cur+1, tot);
func(cur+1, tot+arr[cur]);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> s;
for (int i=0; i<n; i++) {
cin >> arr[i];
}
func(0 , 0);
if (s == 0) cnt--;
cout << cnt;
}
|
#include "gameover.h"
#include "game.h"
#include <QObject>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsItem>
#include <QPushButton>
#include <QFontDatabase>
#include <QIcon>
extern Game *game;
GameOver::GameOver(): QObject(), QGraphicsPixmapItem() {
this->setLabel();
this->setButton();
}
void GameOver::setButton() {
button = new QPushButton();
button->setGeometry(500, 250, 200, 75);
button->setFlat(true);
button->setIcon(QIcon(":/Image/reloadButton.png"));
button->setIconSize(QSize(200, 75));
button->setStyleSheet("background-color: rgba(0, 0, 0, 0%);");
connect(button, SIGNAL(clicked()), this, SLOT(createNewGame()));
}
void GameOver::setLabel() {
label = new QLabel();
label->setStyleSheet("background-color: rgba(0, 0, 0, 0%)");
label->setGeometry(410, 175, 400, 75);
label->setFont(QFont("Times", 28));
label->setPixmap(QPixmap(":/Image/gameover.png"));
}
QPushButton* GameOver::getButton() {
return button;
}
QLabel* GameOver::getLabel() {
return label;
}
void GameOver::createNewGame() {
game->createUI();
}
|
/*
*change the infix to suffix(reverse Polish Expression)
*
*/
#include <string>
#include <stack>
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
static int priority(char op)
{
if (op == '+' || op == '-'){
return 1;
}else if(op == '*' || op == '/'){
return 2;
}else{
return 0;
}
}
static bool isOperator(char op) //判断输入串中的字符是不是操作符,如果是返回true
{
return (op=='+' || op=='-' || op=='*' || op=='/');
}
string reversePolishNotation(string &s)
{
queue<char> mainStack;
stack<char> operatorStack;
int i;
for(i = 0; i < s.size(); ++i){
if(s[i] == '('){
operatorStack.push(s[i]);
}else if(s[i] == ' '|| s[i] == '\t'){
continue;
}else if(isdigit(s[i])){
mainStack.push(s[i]);
while(i + 1 < s.size() && isdigit(s[i+1])){
mainStack.push(s[i+1]);
++i;
}
mainStack.push(' ');
}else if(isOperator(s[i])){
if(operatorStack.empty() || operatorStack.top() == '(' || priority(s[i]) > operatorStack.top()){
operatorStack.push(s[i]);
}else{ //此处需要特别注意,可读性太差
//这种情况一定是发生在符号栈非空
/*while
(priority(operatorStack.top()) > priority(s[i])){
char c = operatorStack.top(); operatorStack.pop();
mainStack.push(c);
mainStack.push(' ');
}*/
while(!operatorStack.empty()){
if(priority(operatorStack.top()) >= priority(s[i])){
char c = operatorStack.top(); operatorStack.pop();
mainStack.push(c);
mainStack.push(' ');
}else
break;
}
operatorStack.push(s[i]);
}
}else if(s[i] == ')'){
while(operatorStack.top() != '('){
char c = operatorStack.top(); operatorStack.pop();
mainStack.push(c);
mainStack.push(' ');
}
operatorStack.pop();
}else{
printf("unknown operator, %c \n", s[i]);
}
}
while(! operatorStack.empty()){
char c = operatorStack.top(); operatorStack.pop();
mainStack.push(c);
mainStack.push(' ');
}
string ret;
while(!mainStack.empty()){
ret += mainStack.front();
mainStack.pop();
}
return ret;
}
int main()
{
string str = " 1 +2 * (3- 4)-5*6";
string polish = reversePolishNotation(str);
cout<<"The infix is:"<<endl;
cout<<str<<endl<<endl;
cout<<"The suffix is:"<<endl;
cout<<polish<<endl;
return 0;
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
void quit()
{
putchar('\n');
#ifdef _WIN32
system("PAUSE");
#else
puts("Press ENTER to continue...\n");
getc(stdin);
#endif
exit(1);
}
template <typename T>
void writeFile(const std::string &fileName, const std::vector<T> &vector)
{
std::ofstream ofs;
ofs.open(fileName, std::ios::binary);
ofs.write((const char *)vector.data(), vector.size() * sizeof(T));
ofs.close();
}
void openFile(const std::string &fileName, std::vector<unsigned char> &v)
{
std::ifstream is(fileName, std::ios::binary);
if (!is)
std::cerr << "Specified file could not be found.", quit();
is.seekg(0, std::ios::end);
unsigned int length = (unsigned int)is.tellg();
is.seekg(0, std::ios::beg);
v.clear();
v.reserve(length);
while (length > 0)
{
char temp;
is.read(&temp, 1);
v.push_back(temp);
length--;
}
is.close();
}
std::vector<unsigned char> left, right, file;
void combine()
{
if (left.size() != right.size())
std::cerr << "The file sizes of the left and right files were not the same.", quit();
file.reserve(left.size() + right.size());
unsigned int pos = 0;
int stage = 0;
while (pos < left.size())
{
for (unsigned int i = 0; i < 64; i++)
file.push_back(left[pos + i]);
for (unsigned int i = 0; i < 64; i++)
file.push_back(right[pos + i]);
pos += 64;
if (pos % 256 == 0)
{
if (stage == 0)
{
pos += 0x100;
stage = 1;
}
else if (stage == 1)
{
pos -= 0x200;
stage = 2;
}
else if (stage == 2)
{
pos += 0x100;
stage = 3;
}
else
{
stage = 0;
}
}
}
writeFile("GFX.bin", file);
}
void split()
{
if (file.size() % 128 != 0)
std::cerr << "Size of file was not divisible by 64.", quit();
left.reserve(file.size() / 2);
right.reserve(file.size() / 2);
unsigned int pos = 0;
int state = 0;
while (pos < file.size())
{
for (unsigned int i = 0; i < 64; i++)
{
left.push_back(file[pos + i]);
right.push_back(file[pos + i + 64]);
}
pos += 128;
if (pos % 0x200 == 0)
{
if (state == 0)
{
pos += 0x200;
state++;
}
else if (state == 1)
{
pos -= 0x400;
state++;
}
else if (state == 2)
{
pos += 0x200;
state++;
}
else
{
state = 0;
}
}
}
writeFile("LeftGFX.bin", left);
writeFile("RightGFX.bin", right);
}
int main(int argc, char* argv[])
{
if (argc == 1 || argc > 3)
std::cerr << "32XSplit usage:\n\n32XSplit [GFXFile.bin]\nOR\n32XSplit [Left.bin] [Right.bin]\n\nIf one file is specified, then the program splits it into LeftGFX.bin and\nRightGFX.bin.\n\nIf two are specified, then the program combines them.\n\n", quit();
if (argc == 2)
{
openFile(argv[1], file);
split();
}
else if (argc == 3)
{
openFile(argv[1], left);
openFile(argv[2], right);
combine();
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
//accepted. AC in One Go.
ll n,min_area;
vector<pair<ll,ll>> slabs(200);
vector<vector<ll>> dp(601,vector<ll>(601));
ll dp_rec(ll w, ll h){
if(w*h < min_area) return w*h;
if(dp[w][h]!=-1) return dp[w][h];
dp[w][h] = INT_MAX;
for(ll i=0;i<n;i++){
if(slabs[i].first == w && slabs[i].second == h){
dp[w][h] = 0;
return dp[w][h];
}
if(slabs[i].first < w) dp[w][h] = min(dp[w][h], dp_rec(w-slabs[i].first,h) + dp_rec(slabs[i].first,h));
if(slabs[i].second< h) dp[w][h] = min(dp[w][h], dp_rec(w,h-slabs[i].second) + dp_rec(w,slabs[i].second));
}
return dp[w][h];
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--){
ll W,H;
cin>>W>>H>>n;
min_area = INT_MAX;
for(ll i=0;i<n;i++){
cin>>slabs[i].first>>slabs[i].second;
if(slabs[i].first*slabs[i].second < min_area){
min_area = slabs[i].first*slabs[i].second;
}
}
for(ll i=0;i<601;i++)
for(ll j=0;j<601;j++)
dp[i][j] = -1;
cout<<dp_rec(W,H)<<"\n";
}
}
|
#ifndef PGTOOLS_COPMEMMATCHER_H
#define PGTOOLS_COPMEMMATCHER_H
#include "../TextMatchers.h"
using namespace PgTools;
enum verbosity { v0, v1, v2 };
enum reverseMode { no, yes, both };
static const int HASH_COLLISIONS_PER_POSITION_LIMIT = 12;
static const int AVERAGE_HASH_COLLISIONS_PER_POSITION_LIMIT = 1;
static const int UNLIMITED_NUMBER_OF_HASH_COLLISIONS_PER_POSITION = 4;
static const int HASH_SIZE_MIN_ORDER = 24;
static const int HASH_SIZE_MAX_ORDER = 31;
typedef std::pair<std::string, size_t> SequenceItem;
typedef std::vector<SequenceItem> SequenceVector;
template<class MyUINT1, class MyUINT2>
using HashBuffer = std::pair<MyUINT1*, MyUINT2* >;
class CopMEMMatcher: public TextMatcher {
private:
const char* start1;
size_t N;
int bigRef;
const int L;
int K, k1, k2;
std::uint32_t(*hashFunc32)(const char*);
std::uint32_t(*hashFuncMatrix[64][6])(const char*);
const int H = 3;
std::uint32_t hash_size;
std::uint32_t hash_size_minus_one;
int LK2 = (L - K) / 2;
int LK2_MINUS_4 = LK2 - 4;
int K_PLUS_LK24 = K + LK2_MINUS_4;
void initHashFuncMatrix();
void initParams(uint32_t minMatchLength);
void calcCoprimes();
void displayParams();
inline std::uint32_t hashFunc(const char* str) { return hashFunc32(str) & hash_size_minus_one; };
template<typename MyUINT1, typename MyUINT2>
void genCumm(size_t N, const char* gen, MyUINT2* cumm, vector<MyUINT1> &skippedList);
template<typename MyUINT2>
void genCummMultithreaded(size_t N, const char* gen, uint8_t* counts, MyUINT2* cumm);
void dumpMEM(SequenceItem& item1, SequenceItem& item2, size_t* match);
void dumpMEMTight(SequenceItem& item1, size_t* match, size_t counter);
std::pair<std::uint64_t*, std::uint64_t*> buffer2;
std::pair<std::uint64_t*, std::uint32_t*> buffer1;
std::pair<std::uint32_t*, std::uint32_t*> buffer0;
template<typename MyUINT1, typename MyUINT2>
HashBuffer<MyUINT1, MyUINT2> processRef();
template<typename MyUINT1, typename MyUINT2>
HashBuffer<MyUINT1, MyUINT2> processRefMultithreaded();
template <class MyUINT1, class MyUINT2>
void deleteHashBuffer(HashBuffer<MyUINT1, MyUINT2> & buf);
template<typename MyUINT1, typename MyUINT2>
void processExactMatchQueryTight(HashBuffer<MyUINT1, MyUINT2> buffer, vector<TextMatch> &resMatches,
const string &destText,
bool destIsSrc, bool revComplMatching, uint32_t minMatchLength);
template<typename MyUINT1, typename MyUINT2>
uint64_t processApproxMatchQueryTight(HashBuffer<MyUINT1, MyUINT2> buffer, const char *pattern, const uint_read_len_max length,
uint8_t maxMismatches, uint8_t minMismatches, uint8_t &mismatchesCount,
uint64_t& betterMatchCount, uint64_t& falseMatchCount);
public:
CopMEMMatcher(const char *srcText, const size_t srcLength, const uint32_t targetMatchLength, uint32_t minMatchLength = UINT32_MAX);
virtual ~CopMEMMatcher();
void matchTexts(vector<TextMatch> &resMatches, const string &destText, bool destIsSrc, bool revComplMatching,
uint32_t minMatchLength) override;
uint64_t approxMatchPattern(const char *pattern, const uint_read_len_max length, uint8_t maxMismatches, uint8_t minMismatches,
uint8_t &mismatchesCount, uint64_t& multiMatchCount, uint64_t& falseMatchCount);
};
#endif //PGTOOLS_COPMEMMATCHER_H
|
#include <iostream>
#include <string>
#include <vector>
#include "custom_date.h"
#include "custom_person.h"
using namespace std;
void add_dmy (Date&, int, int, int);
void test_class_person()
{
Person p = Person("Aditya", 15, 9, 1992, 1);
cout << "P object's name is " << p.get_name() << endl;
Date p_bd;
p.get_birthdate(p_bd);
cout << "P's bday day is "<< p_bd.get_day() << endl;
Person *p_array = new Person[4];
delete[] p_array;
}
void test_class_date()
{
Date my_bday;
cout << "My birth date is ";
my_bday.print_date();
/* default is changed here from 15.9.1992 to 27.8.1992 */
Date::set_default(27,8,1992);
cout << "Default changed"<< endl;
Date sha_bday;
cout << "Sharda's bday is ";
sha_bday.print_date();
/* Demonstration of copying class object */
Date copy_of_sha_bday = sha_bday;
cout << "Copy of Sharda's bday is ";
copy_of_sha_bday.print_date();
/* Demonstration of constant member functions */
cout << "Get day using const member function on my_day : " << my_bday.get_day()<< endl;
/*
* Demonstration of self reference
* Remember, this is a pointer to the object for which fn was invoked
*/
Date copy_of_my_bday = my_bday;
//Date& ref_date = copy_of_my_bday;
add_dmy(copy_of_my_bday, 1,1,1);
cout << "copy_of_my_bday after add_dmy is ";
copy_of_my_bday.print_date();
cout << "Month in string is " << my_bday.get_string() << endl;
copy_of_my_bday = sha_bday;
}
int main ()
{
//test_class_date();
test_class_person();
return (0);
}
void add_dmy (Date& date, int d, int m, int y)
{
date.add_day(d).add_month(m).add_year(y);
}
|
#include "DIR.h"
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef USERJSMAGIC_H
#define USERJSMAGIC_H
#ifdef USER_JAVASCRIPT
#include "modules/dom/src/domobj.h"
class DOM_EnvironmentImpl;
class DOM_UserJSMagicFunction
: public DOM_Object
{
protected:
uni_char *name;
ES_Object *impl, *real;
DOM_Object *data;
BOOL busy;
DOM_UserJSMagicFunction *next;
DOM_UserJSMagicFunction(ES_Object *impl, DOM_Object *data);
public:
~DOM_UserJSMagicFunction();
static OP_STATUS Make(DOM_UserJSMagicFunction *&function, DOM_EnvironmentImpl *environment, const uni_char *name, ES_Object *impl);
virtual int Call(ES_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, ES_Runtime *origining_runtime);
virtual BOOL IsA(int type) { return type == DOM_TYPE_USERJSMAGICFUNCTION || DOM_Object::IsA(type); }
virtual void GCTrace();
void SetNonBusy() { busy = FALSE; }
const uni_char *GetFunctionName() { return name; }
DOM_UserJSMagicFunction *GetNext() { return next; }
void SetNext(DOM_UserJSMagicFunction *new_next) { next = new_next; }
void SetReal(ES_Object *new_real) { real = new_real; }
ES_Object *GetReal() { return real; }
};
class DOM_UserJSMagicVariable
: public DOM_Object
{
protected:
uni_char *name;
ES_Object *getter, *setter;
ES_Value last;
unsigned busy;
DOM_UserJSMagicVariable *next;
DOM_UserJSMagicVariable(ES_Object *getter, ES_Object *setter);
public:
~DOM_UserJSMagicVariable();
static OP_STATUS Make(DOM_UserJSMagicVariable *&variable, DOM_EnvironmentImpl *environment, const uni_char *name, ES_Object *getter, ES_Object *setter);
virtual BOOL IsA(int type) { return type == DOM_TYPE_USERJSMAGICVARIABLE || DOM_Object::IsA(type); }
virtual void GCTrace();
enum BusyType
{
BUSY_READING = 1,
BUSY_WRITING = 2
};
void SetNonBusy(BOOL reading) { busy &= ~(reading ? BUSY_READING : BUSY_WRITING); }
const uni_char *GetVariableName() { return name; }
DOM_UserJSMagicVariable *GetNext() { return next; }
void SetNext(DOM_UserJSMagicVariable *new_next) { next = new_next; }
ES_GetState GetValue(ES_Value *value, ES_Runtime *origining_runtime, ES_Object *restart_object = NULL);
ES_PutState SetValue(ES_Value *value, ES_Runtime *origining_runtime, ES_Object *restart_object = NULL);
};
#endif // USER_JAVASCRIPT
#endif // USERJSMAGIC_H
|
#include<stdio.h>
#include<iostream>
int main()
{
int sex,age;
printf("如果男性請輸入1,女性請輸入2。\n");
printf("請輸入性別和年齡:");
scanf("%d%d",&sex,&age);
if( sex==1 && age>=18 )
{
printf("你可以結婚\n");
}
if( sex==1 && age<18 )
{
printf("你不可以結婚\n");
}
if( sex==2 && age>=16 )
{
printf("妳可以結婚\n");
}
if( sex==2 && age<16 )
{
printf("妳不可以結婚\n");
}
return 0;
}
|
#include "gtest/gtest.h"
#include <type_traits>
#include <utility>
class emptyClass
{
};
TEST(SpecMemFuncGenUnitTest, empty_class_has_everything)
{
emptyClass a;
emptyClass b(a);
a = b;
emptyClass c(std::move(a));
b = std::move(c);
}
class classWithCopyCtor
{
public:
classWithCopyCtor() {}
classWithCopyCtor(const classWithCopyCtor&) { x = 1;}
int x {0};
};
TEST(SpecMemFuncGenUnitTest, copy_ctor_do_not_disable_assignment_but_disable_moves)
{
classWithCopyCtor a;
classWithCopyCtor b(a);
a = b;
classWithCopyCtor c(std::move(a)); // here copy is performed !!!
ASSERT_EQ(1, c.x);
b = std::move(c); // here copy is performed !!!
}
class classWithAssignmentOperator
{
public:
classWithAssignmentOperator() {}
classWithAssignmentOperator& operator=(const classWithAssignmentOperator&) { x = 1; return *this; }
int x {0};
};
TEST(SpecMemFuncGenUnitTest, assignment_operator_do_not_disable_copy_ctor_but_disable_moves)
{
classWithAssignmentOperator a;
classWithAssignmentOperator b(a);
a = b;
classWithAssignmentOperator c(std::move(a)); // here copy is performed !!!
b = std::move(c); // here copy is performed !!!
ASSERT_EQ(1, b.x);
}
class classWithMoveCtor
{
public:
classWithMoveCtor() {}
classWithMoveCtor(classWithMoveCtor&& rhs) { }
};
TEST(SpecMemFuncGenUnitTest, move_ctor_disable_move_operator_and_copy_operations)
{
classWithMoveCtor a;
//classWithMoveCtor b(a); do not compiles
classWithMoveCtor b;
//a = b; do not compiles
classWithMoveCtor c(std::move(a));
//b = std::move(c); do not compiles
}
class classWithMoveOperator
{
public:
classWithMoveOperator() {}
classWithMoveOperator& operator=(classWithMoveOperator&& rhs) { return *this; }
};
TEST(SpecMemFuncGenUnitTest, move_operator_disable_move_ctor_and_copy_operations)
{
classWithMoveOperator a;
//classWithMoveCtor b(a); do not compiles
classWithMoveOperator b;
//a = b; do not compiles
// classWithMoveOperator c(std::move(a));do not compiles
b = std::move(a);
}
// Be carefull here!!!
// Declaring user destructor prevent compiler from generating
// move operations. For example if class would have std::string
// it will be copied - not moved.
class classWithDestructor
{
public:
classWithDestructor() {}
classWithDestructor(const classWithDestructor&) { x = 1;}
classWithDestructor& operator=(const classWithDestructor&) { x = 1; return *this; }
~classWithDestructor() {}
int x {0};
};
TEST(SpecMemFuncGenUnitTest, declared_destructor_do_not_disable_copy_but_disable_moves)
{
classWithDestructor a;
classWithDestructor b(a);
a = b;
classWithDestructor c(std::move(a)); // here copy is performed !!!
b = std::move(c); // here copy is performed !!!
}
class classWithDestructorAndMove
{
public:
classWithDestructorAndMove() {}
classWithDestructorAndMove(const classWithDestructorAndMove&) { x = 1;}
classWithDestructorAndMove& operator=(const classWithDestructorAndMove&) { x = 2; return *this; }
classWithDestructorAndMove(classWithDestructorAndMove&&) { x = 3;}
classWithDestructorAndMove& operator=(classWithDestructorAndMove&&) { x = 4; return *this; }
~classWithDestructorAndMove() {}
int x {0};
};
TEST(SpecMemFuncGenUnitTest, proper_way_to_impl_class)
{
classWithDestructorAndMove a;
ASSERT_EQ(0, a.x);
classWithDestructorAndMove b(a);
ASSERT_EQ(1, b.x);
a = b;
ASSERT_EQ(2, a.x);
classWithDestructorAndMove c(std::move(a));
ASSERT_EQ(3, c.x);
b = std::move(c);
ASSERT_EQ(4, b.x);
}
// General rule:
// move operations are generated for classes (when needed) only if these three things are true:
// • No copy operations are declared in the class.
// • No move operations are declared in the class.
// • No destructor is declared in the class.
/*
The C++11 rules governing the special member functions are thus:
• Default constructor: Same rules as C++98. Generated only if the class contains
no user-declared constructors.
• Destructor: Essentially same rules as C++98; sole difference is that destructors
are noexcept by default (see Item 14). As in C++98, virtual only if a base class
destructor is virtual.
• Copy constructor: Same runtime behavior as C++98: memberwise copy con‐
struction of non-static data members. Generated only if the class lacks a user-
declared copy constructor. Deleted if the class declares a move operation.
Generation of this function in a class with a user-declared copy assignment oper‐
ator or destructor is deprecated.
• Copy assignment operator: Same runtime behavior as C++98: memberwise
copy assignment of non-static data members. Generated only if the class lacks a
user-declared copy assignment operator. Deleted if the class declares a move
operation. Generation of this function in a class with a user-declared copy con‐
structor or destructor is deprecated.
• Move constructor and move assignment operator: Each performs memberwise
moving of non-static data members. Generated only if the class contains no user-
declared copy operations, move operations, or destructor.
*/
|
//
// Created by ischelle on 05/05/2021.
//
#include "Medic.hpp"
namespace pandemic
{
Medic::Medic(Board board, City city) : Player(board, city)
{
//nothing
}
// void Medic::treat() {
// }
}
|
#pragma once
#include "QsoTokenType.h"
// Class for parsing frequency tokens
class FreqToken : public QsoTokenType
{
public:
FreqToken();
virtual ~FreqToken();
virtual bool Parse(const string& token);
virtual QsoTokenType* Clone() { return new FreqToken(); }
};
|
#ifndef UGV_FOLLOW_MANEUVER_H
#define UGV_FOLLOW_MANEUVER_H
#include <ros/ros.h>
#include <Eigen/Dense>
#include "maneuvers/trajectory_class.h"
#include "maneuvers/eth_trajectory.h"
#include "geometry_msgs/PoseWithCovarianceStamped.h"
#include "geometry_msgs/AccelWithCovarianceStamped.h"
#include "geometry_msgs/PoseWithCovariance.h"
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include "nav_msgs/Odometry.h"
class ugv_follow: public trajectory_class{
private:
//ROS NodeHandle
ros::NodeHandle nh_;
//Trajectory Targets for the controller
Eigen::Vector3d target_position;
Eigen::Vector3d target_velocity;
Eigen::Vector3d target_acceleration;
Eigen::Vector3d target_jerk;
Eigen::Vector3d target_angvel;
double target_yaw;
int type;
//UGV Current State Parameters
Eigen::Vector3d ugv_position;
Eigen::Vector3d ugv_velocity;
Eigen::Vector3d ugv_acceleration;
Eigen::Vector4d ugv_attitude;
double ugv_yaw;
//UAV current state parameters
Eigen::Vector3d mavPos_, mavVel_;
//UGV future state parameters
Eigen::Vector3d ugvpos_future, ugvvel_future;
//Acceleration due to gravity
Eigen::Vector3d g_;
//Time to intersection of trajectories of the UGV and quadrotor
double time_to_intersection;
//Current distance between the UGV and the quadrotor
double dist_to_ugv;
//Mean velocity at which the quadrotor is assumed to follow the UGV
double ugv_follow_velocity;
//Subscriber definitions
ros::Subscriber vehicle_posSub_, accelSub_, mavPoseSub_, mavtwistSub_;
//Variable representing the phase of operation of the ugv tracking maneuver. Tracking and
//following of the UGV is carried out in two phases. The manuever starts with the quadrotor trying
//to catch up with the UGV. This becomes phase 1. In the next phase the quadrotor tries to closely
//follow the UGV at a given height by making use of onboard camera to detect the UGV
int phase;
//Dummy variable for storing time
double elasped_time;
//Height at which the quadrotor follows the UGV
double hover_height;
//To see if user has commanded landing
int ugv_land_init;
//Start time of the landing operation
ros::Time start_time;
public:
//Constructor
ugv_follow(const ros::NodeHandle& nh);
//Destructor
~ugv_follow();
//Function to generate and store the trajectory targets for the controller
void trajectory_generator(double);
//Function to intialise the trajectory for completing the manuever
double maneuver_init(double);
//Function to calculate the desired angular velocity making using of the differential
//flatness property of the quadrotor
Eigen::Vector3d calculate_trajectory_angvel();
//Functions to return the desired trajectory targets
Eigen::Vector3d get_target_pos();
Eigen::Vector3d get_target_vel();
Eigen::Vector3d get_target_acc();
Eigen::Vector3d get_target_jerk();
Eigen::Vector3d get_target_angvel();
double get_target_yaw();
int get_type();
//Function to predict the state of the UGV after a given time based on the current acceleration
//of the UGV
bool future_state_predict();
//Function subscribing to the current acceleration of the UGV
void ugv_accel_sub(const geometry_msgs::AccelWithCovarianceStamped&);
//Function subscribing to the current position and attitude of the quadrotor
void mav_pose_sub(const geometry_msgs::PoseStamped&);
//Function subscribing to the current velocity of the quadrotor
void mavtwistCallback(const geometry_msgs::TwistStamped&);
//Function subscribing to the current state of the UGV
void ugv_state_sub(const nav_msgs::Odometry&);
//Function to calculate the distance along the XY plane for two given vectors
double planar_distance_calculator(Eigen::Vector3d&, Eigen::Vector3d&);
};
#endif
|
#include <stdio.h>
#include <string.h>
int syn; //存放单词的类型
int p; //用于遍历程序源代码
int line; //用来标识行数
char ch; //用于读取程序源代码
int sum; //用来保存数字的值
char program[1000], token[10]; // program用来存储源代码,token用来存放词素
char *rwtab[9] = {"begin", "if", "then", "else", "while",
"do", "Const", "Var", "end"}; //关键字
char *lexicalType[27]; //词法类型
struct symbol {
char name[10];
int value;
}; //符号表项
symbol symbolTable[100]; //符号表
int q; //用于依次往符号表中添加项目
char id[10]; //用于存储id
char temp[100][10] = {"t1", "t2", "t3", "t4", "t5",
"t6", "t7", "t8", "t9"}; //中间变量
int w; //用于依次生成中间变量
bool lookup(char *id) {
int i;
for (i = 0; symbolTable[i].name[0] != '\0'; i++) {
if (strcmp(id, symbolTable[i].name) == 0) return true;
}
return false;
}
void initLexicalType() {
int i;
for (i = 1; i <= 9; i++) lexicalType[i] = "ReservedWord";
lexicalType[10] = "Identifier";
lexicalType[11] = "Number";
for (i = 12; i <= 22; i++) lexicalType[i] = "Operator";
for (i = 23; i <= 26; i++) lexicalType[i] = "Delimiter";
}
bool isDigital(char ch) {
if (ch <= '9' && ch >= '0')
return true;
else
return false;
}
bool isAlpha(char ch) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
return true;
else
return false;
}
void Scanner() {
int m;
for (m = 0; m < 10; m++) {
token[m] = '\0';
}
m = 0;
//初始化词素数组为空
ch = program[p++];
while (ch == ' ' || ch == '\n' || ch == '\t') //剔除空白
{
// if(ch=='\n'){
// printf("%d:",line);//输出行数及该行代码
// for(int i=p;program[i]!='\0'&&program[i]!='\n';i++)
// printf("%c",program[i]);
// printf("\n");
// line++;
// }
ch = program[p++];
}
if (isAlpha(ch)) {
do {
token[m++] = ch;
ch = program[p++];
} while (isAlpha(ch) || isDigital(ch));
p--;
syn = 10; //标识符类别号
token[m++] = '\0';
for (int n = 0; n <= 8; n++) {
if (strcmp(token, rwtab[n]) == 0) {
syn = n + 1; //关键字类别号
break;
} //识别关键字
}
return;
} else if (isDigital(ch)) {
sum = 0;
while (isDigital(ch)) {
token[m++] = ch;
sum = sum * 10 + ch - '0';
ch = program[p++];
}
p--;
token[m++] = '\0';
syn = 11; //无符号整数类别号
if (isAlpha(ch)) syn = -1; //词法错误
return;
} else {
token[0] = ch;
switch (ch) {
case '<':
ch = program[p++];
if (ch == '>') {
syn = 22; //识别<>
token[1] = ch;
} else if (ch == '=') {
syn = 21; //识别<=
token[1] = ch;
} else {
syn = 20; //识别<
p--;
}
break;
case '>':
ch = program[p++];
if (ch == '=') {
syn = 19; //识别>=
token[1] = ch;
} else {
syn = 18; //识别>
p--;
}
break;
case '=':
ch = program[p++];
if (ch == '=') {
syn = 17; //识别==
token[1] = ch;
} else {
syn = 16; //识别=
p--;
}
break;
case '+':
syn = 12;
break; //识别+
case '-':
syn = 13;
break; //识别-
case '*':
syn = 14;
break; //识别*
case '/':
syn = 15;
break; //识别/
case ';':
syn = 23;
break; //识别;
case '(':
syn = 24;
break; //识别(
case ')':
syn = 25;
break; //识别)
case ',':
syn = 26;
break; //识别,
case '#':
syn = 0;
break; //识别#
default:
syn = -1;
break; //词法错误
}
return;
}
}
//输出单词符号二元式<词类表示,单词的属性值>
// 1~9对应关键字,10对应标识符,11对应无符号整数,
// 12~22对应运算符 ,23~26对应分界符
void lexicalPrint() {
if (syn == 11) //无符号整数类型属性值为其value
printf(" %s:<%d,%d>\n", lexicalType[syn], syn, sum);
else //其余类型属性值为其单词序列
printf(" %s:<%d,%s>\n", lexicalType[syn], syn, token);
}
bool Constan_Defined() {
if (syn == 10) //匹配标识符
{
if (!lookup(token)) {
strcpy(symbolTable[q].name, token);
Scanner();
if (syn == 16) //匹配等号
{
Scanner();
if (syn == 11) //匹配无符号整数
{
symbolTable[q].value = sum;
q++;
return true;
} else {
printf("错误:常量定义未指定无符号整数\n");
return false;
}
} else {
printf("错误:常量定义无等号赋值\n");
return false;
}
} else {
printf("错误:重复定义%s\n", token);
return false;
}
} else
return false;
}
bool Constan_Description() //指针不会读到下一个
{
if (syn == 7) //匹配Const关键字
{
Scanner();
if (Constan_Defined()) //匹配<常量定义>
{
Scanner();
while (syn == 26) //匹配逗号
{
Scanner();
if (Constan_Defined()) //匹配<常量定义>
{
Scanner();
continue;
} else {
printf("错误:缺少常量定义\n");
return false;
}
}
if (syn == 23) //匹配分号
{
return true;
} else {
printf("错误:缺少分号\n");
return false;
}
} else {
printf("错误:缺少常量定义\n");
return false;
}
} else {
return false;
}
}
bool Variable_Description() //指针不会读到下一个
{
if (syn == 8) //匹配Var关键字
{
Scanner();
if (syn == 10) //匹配标识符
{
if (!lookup(token)) {
strcpy(symbolTable[q].name, token);
q++;
Scanner();
while (syn == 26) //匹配逗号
{
Scanner();
if (syn == 10) //匹配标识符
{
strcpy(symbolTable[q].name, token);
q++;
Scanner();
continue;
} else {
printf("错误:缺少标识符\n");
return false;
}
}
if (syn == 23) //匹配分号
{
return true;
} else {
printf("错误:缺少分号\n");
return false;
}
} else {
printf("重复定义%s\n", token);
return false;
}
} else {
printf("错误:重复定义%s\n", token);
return false;
}
} else {
return false;
}
}
char *Item_expression();
char *Expression();
char *Factor();
bool Statement();
char *Item_expression() //指针会读到下一个 select={syn=10,11,24}
{
char lastid[10], op[10];
if (syn == 10 || syn == 11 || syn == 24) //匹配select
{
Factor();
strcpy(lastid, id); //保存id标识符
Scanner();
while (syn == 14 || syn == 15) //匹配项<乘法运算符>
{
strcpy(op, token);
Scanner();
if (Factor()) //匹配<因子>
{
printf(" %s=%s%s%s\n", temp[w], lastid, op, id);
strcpy(lastid, temp[w]);
w++;
Scanner();
continue;
} else {
printf("错误:缺少因子\n");
return NULL;
}
}
// printf("产生式:<D>→ε\n");
strcpy(id, lastid);
return id;
} else
return NULL;
}
char *Expression() //指针会读到下一个
{
char lastid[10], op[10];
int i;
char str[50] = "产生式:<表达式>→";
if (syn == 12) //匹配+
{
for (i = 0; str[i] != '\0'; i++)
;
str[i] = '+';
Scanner();
} else if (syn == 13) //匹配-
{
for (i = 0; str[i] != '\0'; i++)
;
str[i] = '-';
Scanner();
}
if (syn == 10 || syn == 11 || syn == 24) //匹配select集
{
Item_expression(); //匹配<项>
strcpy(lastid, id);
while (syn == 12 || syn == 13) //匹配<加法运算符>
{
strcpy(op, token);
Scanner();
if (Item_expression()) //匹配<项>
{
printf(" %s=%s%s%s\n", temp[w], lastid, op, id);
strcpy(lastid, temp[w]);
w++;
continue;
} else {
printf("错误:缺少项\n");
return NULL;
}
}
strcpy(id, lastid);
return id;
} else
return NULL;
}
char *Factor() {
strcpy(id, token);
if (syn == 10) //匹配标识符
{
return id;
} else if (syn == 11) //匹配无符号整数
{
return id;
} else if (syn == 24) //匹配左括号
{
Scanner();
if (Expression()) //匹配<表达式>
{
if (syn == 25) //匹配右括号
{
return id;
} else {
printf("错误:没有右扩号\n");
return NULL;
}
} else {
printf("错误:没有表达式\n");
return NULL;
}
} else
return NULL;
}
bool Assignment_statement() //指针会读到下一个
{
char lastid[10];
if (syn == 10) //匹配标识符
{
if (lookup(token)) {
strcpy(lastid, token);
Scanner();
if (syn == 16) //匹配等号
{
Scanner();
if (Expression()) //匹配表达式
{
printf(" %s:=%s\n", lastid, id);
return true;
} else {
printf("错误:缺少表达式\n");
return false;
}
} else {
printf("错误:缺少等号\n");
return false;
}
} else {
printf("错误:未定义变量%s\n", token);
return false;
}
} else
return false;
}
bool Condition() //指针会读到下一个
{
printf("产生式:<条件>→<表达式><关系运算符><表达式>\n");
if (Expression()) //匹配<表达式>
{
if (syn == 17 || syn == 18 || syn == 19 || syn == 20 || syn == 21 ||
syn == 22) //匹配<关系运算符>
{
Scanner();
if (Expression()) //匹配<表达式>
{
return true;
} else {
printf("错误:缺少表达式\n");
return false;
}
} else {
printf("错误:缺少关系运算符\n");
return false;
}
} else
return false;
}
bool Conditional_statements() {
if (syn == 2) //匹配if
{
printf("产生式:<条件语句>→if <条件> then <语句><E>\n");
Scanner();
if (Condition()) //匹配<条件>
{
if (syn == 3) //匹配then
{
Scanner();
if (Statement()) //匹配<语句>
{
if (syn == 4) //匹配else
{
printf("产生式:<E>→else<语句>\n");
Scanner();
if (Statement()) //匹配<语句>
{
return true;
} else {
printf("错误:else后缺少语句\n");
return false;
}
}
printf("产生式:<E>→ε\n");
return true;
} else {
printf("错误:then后缺少语句\n");
return false;
}
} else {
printf("错误:确实then\n");
return false;
}
} else {
printf("错误:if后缺少条件\n");
return false;
}
} else
return false;
}
bool While_Statement() //指针会读到下一个
{
if (syn == 5) //匹配while
{
printf("产生式:<当循环语句>→while <条件> do <语句>\n");
Scanner();
if (Condition()) //匹配<条件>
{
if (syn == 6) //匹配do
{
Scanner();
if (Statement()) //匹配<语句>
{
return true;
} else {
printf("错误:do后缺少语句\n");
return false;
}
} else {
printf("错误:缺少do\n");
return false;
}
} else {
printf("错误:缺少条件\n");
return false;
}
} else
return false;
}
bool Compound_statements() //指针会读到下一个
{
if (syn == 1) //匹配begin
{
Scanner();
if (Statement()) //匹配<语句>
{
while (syn == 23) //匹配分号
{
Scanner();
if (Statement()) //匹配<语句>
{
continue;
} else {
printf("错误:分号后缺少语句\n");
return false;
}
}
if (syn == 9) //匹配end
{
Scanner();
return true;
} else {
printf("错误:缺少end\n");
return false;
}
} else {
printf("错误:begin后缺少语句\n");
return false;
}
} else
return false;
}
bool Statement() //指针会读到下一个
{
if (syn == 10) //匹配<赋值语句>
{
Assignment_statement();
return true;
} else if (syn == 5) //匹配<当循环语句>
{
While_Statement();
return true;
} else if (syn == 1) //匹配<复合语句>
{
Compound_statements();
return true;
} else if (syn == 2) //匹配<条件语句>
{
Conditional_statements();
return true;
} else {
return false; //假设语句不能为空
}
}
int main() {
p = 0;
line = 1;
initLexicalType();
printf("输入词法分析串以#作为结束\n");
do {
ch = getchar();
program[p++] = ch;
} while (ch != '#');
p = 0;
q = 0;
w = 0;
// printf("%d:",line);
// for(int i=0;program[i]!='\0'&&program[i]!='\n';i++)
// printf("%c",program[i]);//输出第一行代码
// printf("\n");
line++;
Scanner();
Constan_Description();
Scanner();
Variable_Description();
Scanner();
Statement();
}
// Const x=8,y=7;
// Var a,b; begin
// a=x+y;
// b=a*x end
|
// Created by: DAUTRY Philippe
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDocStd_XLinkRoot_HeaderFile
#define _TDocStd_XLinkRoot_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TDocStd_XLinkPtr.hxx>
#include <TDF_Attribute.hxx>
#include <Standard_OStream.hxx>
class Standard_GUID;
class TDF_Data;
class TDF_RelocationTable;
class TDocStd_XLinkRoot;
DEFINE_STANDARD_HANDLE(TDocStd_XLinkRoot, TDF_Attribute)
//! This attribute is the root of all external
//! references contained in a Data from TDF. Only one
//! instance of this class is added to the TDF_Data
//! root label. Starting from this attribute all the
//! Reference are linked together, to be found easily.
class TDocStd_XLinkRoot : public TDF_Attribute
{
public:
//! Returns the ID: 2a96b61d-ec8b-11d0-bee7-080009dc3333
Standard_EXPORT static const Standard_GUID& GetID();
//! Sets an empty XLinkRoot to Root or gets the
//! existing one. Only one attribute per TDF_Data.
Standard_EXPORT static Handle(TDocStd_XLinkRoot) Set (const Handle(TDF_Data)& aDF);
//! Inserts <anXLinkPtr> at the beginning of the XLink chain.
Standard_EXPORT static void Insert (const TDocStd_XLinkPtr& anXLinkPtr);
//! Removes <anXLinkPtr> from the XLink chain, if it exists.
Standard_EXPORT static void Remove (const TDocStd_XLinkPtr& anXLinkPtr);
//! Returns the ID of the attribute.
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
//! Returns a null handle.
Standard_EXPORT Handle(TDF_Attribute) BackupCopy() const Standard_OVERRIDE;
//! Does nothing.
Standard_EXPORT void Restore (const Handle(TDF_Attribute)& anAttribute) Standard_OVERRIDE;
//! Returns a null handle.
Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE;
//! Does nothing.
Standard_EXPORT void Paste (const Handle(TDF_Attribute)& intoAttribute, const Handle(TDF_RelocationTable)& aRelocationTable) const Standard_OVERRIDE;
//! Dumps the attribute on <aStream>.
Standard_EXPORT Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE;
friend class TDocStd_XLinkIterator;
DEFINE_STANDARD_RTTIEXT(TDocStd_XLinkRoot,TDF_Attribute)
protected:
private:
//! Initializes fields.
Standard_EXPORT TDocStd_XLinkRoot();
//! Sets the field <myFirst> with <anXLinkPtr>.
void First (const TDocStd_XLinkPtr& anXLinkPtr);
//! Returns the contents of the field <myFirst>.
TDocStd_XLinkPtr First() const;
TDocStd_XLinkPtr myFirst;
};
#include <TDocStd_XLinkRoot.lxx>
#endif // _TDocStd_XLinkRoot_HeaderFile
|
#ifndef GLADIATOR_LISTENER_H
#define GLADIATOR_LISTENER_H
#include <string>
class Gladiator;
class Gladiator_Listener
{
public:
Gladiator_Listener();
virtual ~Gladiator_Listener();
virtual void died(const Gladiator* gladiator) = 0;
virtual void inflictedDamage(const Gladiator* gladiator, const Gladiator* victim, int amount) = 0;
protected:
private:
};
#endif // GLADIATOR_LISTENER_H
|
//Write a C++ program to count number of digits in a number.
#include<iostream>
using namespace std;
int main()
{
int a,c=0;
cout<<"Enter a multiple digit number:";
cin>>a;
while(a!=0)
{
c++;
a=a/10;
}
cout<<"There are "<<c<<" digits.";
}
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
using namespace std;
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
#define int long long
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define FOR(a,b) for(int i=a;i<b;i++)
#define REP(a,b) for(int i=a;i<=b;i++)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define endl '\n'
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
const int N = 1e5 + 5;
const int mod = 1e9 + 7;
vi graph[N];
vi vis;
vi comp;
int n, m;
void dfs(int src) {
vis[src] = 1;
comp.pb(src);
for (int to : graph[src]) {
if (!vis[to])
dfs(to);
}
}
void connected_comp() {
vis.assign(N, 0);
comp.clear();
vector <vi> ans;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
dfs(i);
ans.pb(comp);
}
comp.clear();
}
cout << ans.size() << " ";
int res = 1;
for (auto x : ans) {
res = res * x.size() % mod;
}
cout << res % mod << endl;
}
void solve() {
cin >> n >> m;
for (int i = 0; i <= n; i++)
graph[i].clear();
while (m--) {
int u, v; cin >> u >> v;
graph[u].pb(v);
graph[v].pb(u);
}
connected_comp();
//cout << ncr(3) << endl;
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
int t; cin >> t; while (t--)
solve();
return 0;
}
|
#pragma once
#include "BaseHeader.h"
#include "utilityBase.h"
class vfiMaxUtil :
public utilityBase
{
protected:
double get_wage(const State& current, const StochProc& stoch) const;
double get_zshock(const State& current, const StochProc& stoch, COUNTRYID whichCountry) const;
double prod_fn(const double k1, const double k2, /*const double c1mgmt,*/ const State& current,
const StochProc& stoch) const;
double getMaxBorrow(const double k1, const double k2/*, const double c1mgmt*/) const;
public:
vfiMaxUtil(const State& current, const StochProc& stoch, const EquilFns& fns);
~vfiMaxUtil();
virtual double operator() (VecDoub state_prime) const;
double getBoundUtil() const final;
double getBoundBorrow() const final;
bool constraintBinds() const final;
double calculateCurrentAssets(const double k1, const double k2, const double bonds, double r) const;
double calculateTestAssets(const double k1, const double k2, const double bonds, const double r) const;
double getNextPeriodAggAssets(int whichCountry, const double currentAggAsst) const;
};
|
#ifndef YL_BAAR_CONSUMER
#define YL_BAAR_CONSUMER
#include <ndn-cxx/face.hpp>
#include "tinyxml/tinyxml.h"
#include <string>
#include <map>
#include <mutex>
using namespace ndn;
using namespace std;
class Consumer
{
public:
Consumer();
~Consumer();
public:
void setProNum(int pronum);
// add by Jerry: 2018 0305
void GetRegData(const string& strMarket, const char* param);
void GetRegDataSize(const string& strMarket, const char* param);
void GetRegDataPrice(const string& strMarket, const char* param);
void GetMarketInfoFromMarket(const string& strMarket, const char* param);
void GetMarketInfoFromUser(const string& strMarket, const char* param);
void GetMarketInfoFromTecCompany(const string& strMarket, const char* param);
void GetMarketInfoFromBn(const string& strMarket, const char* param);
void GetAuthRandom(const string& strMarket, const char* param);
void GetMarketInfoFromTecCompanyAsUser(const string& strMarket, const char* param);
void GetRegDataFromOtherUser(const string& strMarket, const char* param);
void UserPubkeySync(const string& strMarket, const char* param);
void GetAuthToken(const string& strMarket, const char* param);
void GetConsumeBill(const string& strMarket, const char* param);
void GetConsumeBillSum(const string& strMarket, const char* param);
void DisableMarketFromBnNode(const string& strMarket, const char* param);
void AddMarketToBnNode(const string& strMarket, const char* param);
void UpdateMarketBalanceFromBnNode(const string& strMarket, const char* param);
//New interface add by gd 2018.04.05, Used to notify BSDR to store the specified data on chain
void NotifyOnChain(const string& strMarket, const char* param);
void RegisterDataPriceUpdate(const string& strMarket, const char* param);
void RegisterDataDisable(const string& strMarket, const char* param);
void RegisterDataUpdate(const string& strMarket, const char* param);
void RegisterDataSet(const string& strMarket, const char* param);
//del by Jerry: 201803015
//void GetBlockData(const string& consumerMarket, const string& dataMarket, const string& blocklabel);
//void GetTranInfo(const string& consumerMarket, const string& dataMarket, const string& blocklabel);
//egz
//void GetTxID(const string& dataMarket, const string& blocklabel);
private:
void expressInterestName(const string& strName);
void onData(const Interest& interest, const Data& data);
void onTranData(const Interest& interest, const Data& data);
void onNack(const Interest& interest, const lp::Nack& nack);
void onTimeout(const Interest& interest);
//egz
void onTxIDData(const Interest& interest, const Data& data);
public:
std::unique_ptr<Face> m_pface;
int m_pronum;
char * m_pData;
bool m_success;
string m_errormsg;
};
#endif /* #ifndef YL_BAAR_CONSUMER */
|
#include "pch.h"
Vertex* GraphAdjacencyList::insVertex(int des, Vertex* head)
{
Vertex* newVertex = new Vertex;
newVertex->id = des;
newVertex->next = head;
return newVertex;
}
void GraphAdjacencyList::initGraph(int numVertices)
{
for (int i = 0; i < numVertices; i++) {
head[i].next = nullptr;
}
}
|
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define FOR(i,n) for(ll i=0;i<n;i++)
#define FOR1(i,n) for(ll i=1;i<n;i++)
#define FORn1(i,n) for(ll i=1;i<=n;i++)
#define FORmap(i,mp) for(auto i=mp.begin();i!=mp.end();i++)
#define vll vector<ll>
#define vs vector<string>
#define pb(x) push_back(x)
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define mod 1000000007
using namespace std;
int main() {
// your code goes here
fast;
ll t;
cin>>t;
while(t--)
{
ll n,res=0;
cin>>n;
ll a[n],d[n];
unordered_map<ll,vector<ll>> mp;
FOR(i,n)
{
cin>>a[i];
if(i==0)
{
d[i]=a[i];
mp[d[i]].push_back(i);
}
else
{
d[i]=a[i]^d[i-1];
mp[d[i]].push_back(i);
}
if(d[i]==0)
res+=i;
}
//cout<<res<<" ";
FORmap(i,mp)
{
ll tmp=(i->second).size();
if(tmp>1)
{
//sort((i->second).begin(),(i->second).end());
ll sum = 0;
for (ll j=tmp-1; j>=0; j--)
sum += j*(i->second)[j] - (tmp-1-j)*(i->second)[j];
sum-=(tmp*(tmp-1))/2;
res+=sum;
}
}
cout<<res<<endl;
}
return 0;
}
|
// Copyright (c) 2013 Nick Porcino, All rights reserved.
// License is MIT: http://opensource.org/licenses/MIT
#ifndef LANDRU_RUNTIME_INSTRUCTIONS_H
#define LANDRU_RUNTIME_INSTRUCTIONS_H
#include <string>
#include <vector>
namespace Landru
{
namespace Instructions
{
#define INSTR_DECL(a, b, c) i##a,
enum Op
{
#include "InstructionsDef.h"
};
#undef INSTR_DECL
struct Info
{
int instruction;
const char* name;
int argCount;
const char* stackDoc;
};
const Info& getInfo(Op instruction);
char const*const disassemble(unsigned int const*const program, int pc,
const std::vector<std::string>& stringTable, int& skip);
char const*const disassemble(unsigned int const*const program, int pc,
const char* stringData, int* stringArray, int& skip);
char const*const opName(int op);
} // Instructions
}
#endif
|
#include "cocos2d.h"
#include "monster.h"
#include <cmath>
#define FIREBALL_TAG 11
#define MOVE_ACTION_TAG 1
#define SMALL_MOVE_ACTION_TAG 2
int getdirection(cocos2d::Vec2 diff) {
//0->上方 1->下 2->左 3->右
if (diff.y <= 0 && -diff.y >= fabs(diff.x)) {
//往下移动
return 1;
}
else if (diff.y >= 0 && diff.y >= fabs(diff.x)) {
//往上移动
return 0;
}
else if (diff.x >= 0 && diff.x >= fabs(diff.y)) {
//往右移动
return 3;
}
else {
//往左移动
return 2;
}
return 0;
}
BigMonster* BigMonster::create(const std::string& filename) {
BigMonster* bigSprite = new(std::nothrow) BigMonster();
if (bigSprite && bigSprite->initWithFile(filename))
{
bigSprite->autorelease();
return bigSprite;
}
CC_SAFE_DELETE(bigSprite);
return nullptr;
}
void BigMonster::move(int dir) {
//0->上 1->下 2->左 3->右
//随机波动
std::random_device rd;
auto eng = std::default_random_engine{ rd() };
auto dis = std::uniform_int_distribution<>{ -40,80 };
int rand = dis(eng);
int distance = 80 + rand;
float time = 3;
auto move_down = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, -distance));
auto move_up = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, distance));
auto move_right = cocos2d::MoveBy::create(time, cocos2d::Vec2(distance, 0));
auto move_left = cocos2d::MoveBy::create(time, cocos2d::Vec2(-distance, 0));
auto moveby = move_up;
//移动
switch (dir) {
case 0:moveby = move_up; break;
case 1:moveby = move_down; break;
case 2:moveby = move_left; break;
case 3:moveby = move_right; break;
default:
moveby = move_up;
break;
}
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "Boss_UP_0%d.png";
switch (dir) {
case 0:break;
case 1:openfile[5] = 'D'; openfile[6] = 'O'; break;
case 2:openfile[5] = 'L'; openfile[6] = 'F'; break;
case 3:openfile[5] = 'R'; openfile[6] = 'I'; break;
default:
break;
}
for (int i = 1; i <= 2; i++) {
char str[50];
sprintf(str, openfile, i);
animation->cocos2d::Animation::addSpriteFrameWithFile(str);
}
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(3); //-1无限循环
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto seq = cocos2d::Spawn::create(moveby, animate, nullptr);
seq->setTag(MOVE_ACTION_TAG);
this->runAction(seq);
}
void BigMonster::attack(cocos2d::Vec2 diff) {
//僵尸朝向攻击的方向
int dir = getdirection(diff);
stopActionByTag(MOVE_ACTION_TAG); //停掉移动的动作
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "Boss_UP_0%d.png";
switch (dir) {
case 0:break;
case 1:openfile[5] = 'D'; openfile[6] = 'O'; break;
case 2:openfile[5] = 'L'; openfile[6] = 'F'; break;
case 3:openfile[5] = 'R'; openfile[6] = 'I'; break;
default:break;
}
for (int i = 1; i <= 1; i++) {
char str[50];
sprintf(str, openfile, i);
animation->cocos2d::Animation::addSpriteFrameWithFile(str);
}
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(0); //静止的图片
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto seq = cocos2d::Spawn::create(animate, nullptr);
this->runAction(seq);
if (!is_under_attack) { //如果被攻击,有僵直,无法攻击
//创建火球
auto fireball = Sprite::create("fireball.png");
fireball->setPosition(cocos2d::Vec2(75, 75));
auto physicsBody = cocos2d::PhysicsBody::createCircle(20.0f, cocos2d::PhysicsMaterial(0.0f, 0.0f, 0.0f));
physicsBody->setDynamic(false);
physicsBody->setContactTestBitmask(0xFFFFFFFF);
fireball->setPhysicsBody(physicsBody);
fireball->setTag(FIREBALL_TAG);
//添加到场景中
this->addChild(fireball);
// 将偏移量转化为单位向量,即长度为1的向量。
diff.normalize();
// 将其乘以2000,你就获得了一个指向用户触屏方向的长度为2000的向量。为什么是2000呢?因为长度应当足以超过当前分辨率下屏幕的边界。
auto shootAmount = diff * 2000;
// 5.创建一个动作,在12秒内移动到目标位置,然后将它从场景中移除。
auto actionMove = cocos2d::MoveBy::create(12.0f, shootAmount);
auto actionRemove = cocos2d::RemoveSelf::create();
fireball->runAction(cocos2d::Sequence::create(actionMove, actionRemove, nullptr));
}
}
void BigMonster::under_attack(cocos2d::Vec2 diff,int de_hp){
is_under_attack = true;
this->hp -= de_hp;
stopActionByTag(MOVE_ACTION_TAG); //停掉移动的动作
//后退,向被攻击的反方向
int dir = getdirection(diff);
int distance = 20;
float time = 0.3;
auto move_down = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, -distance));
auto move_up = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, distance));
auto move_right = cocos2d::MoveBy::create(time, cocos2d::Vec2(distance, 0));
auto move_left = cocos2d::MoveBy::create(time, cocos2d::Vec2(-distance, 0));
auto moveby = move_up;
//移动
switch (dir) {
case 0:moveby = move_up; break;
case 1:moveby = move_down; break;
case 2:moveby = move_left; break;
case 3:moveby = move_right; break;
default:
moveby = move_up;
break;
}
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "Boss_UP_0%d.png";
switch (dir) {
case 1:break;
case 0:openfile[5] = 'D'; openfile[6] = 'O'; break;
case 3:openfile[5] = 'L'; openfile[6] = 'F'; break;
case 2:openfile[5] = 'R'; openfile[6] = 'I'; break;
default:break;
}
for (int i = 1; i <= 1; i++) {
char str[50];
sprintf(str, openfile, i);
animation->cocos2d::Animation::addSpriteFrameWithFile(str);
}
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(0); //静止的图片
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto seq = cocos2d::Spawn::create(moveby,animate, nullptr);
//auto delay = cocos2d::DelayTime::create(2);
this->runAction(cocos2d::Sequence::create(seq, nullptr));
is_under_attack = false;
}
void BigMonster::death() {
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "BOSS_d.png";
animation->cocos2d::Animation::addSpriteFrameWithFile(openfile);
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(0); //静止的图片
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto fade = cocos2d::FadeTo::create(2, 0);
auto seq = cocos2d::Spawn::create(fade, animate, nullptr);
this->runAction(cocos2d::Sequence::create(seq, nullptr));
}
SmallMonster* SmallMonster::create(const std::string& filename){
SmallMonster* smallSprite = new(std::nothrow) SmallMonster();
if (smallSprite && smallSprite->initWithFile(filename))
{
smallSprite->autorelease();
return smallSprite;
}
CC_SAFE_DELETE(smallSprite);
return nullptr;
}
void SmallMonster::move(int dir){
//0->上 1->下 2->左 3->右
//随机波动
std::random_device rd;
auto eng = std::default_random_engine{ rd() };
auto dis = std::uniform_int_distribution<>{ -50,100 };
int rand = dis(eng);
int distance = 80 + rand;
float time = 3;
auto move_down = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, -distance));
auto move_up = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, distance));
auto move_right = cocos2d::MoveBy::create(time, cocos2d::Vec2(distance, 0));
auto move_left = cocos2d::MoveBy::create(time, cocos2d::Vec2(-distance, 0));
auto moveby = move_up;
//移动
switch (dir) {
case 0:moveby = move_up; break;
case 1:moveby = move_down; break;
case 2:moveby = move_left; break;
case 3:moveby = move_right; break;
default:
moveby = move_up;
break;
}
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "0_0%d.png";
switch (dir) {
case 0:break;
case 1:openfile[0] = '1'; break;
case 2:openfile[0] = '2'; break;
case 3:openfile[0] = '3'; break;
default:
break;
}
for (int i = 1; i <= 2; i++) {
char str[50];
sprintf(str, openfile, i);
animation->cocos2d::Animation::addSpriteFrameWithFile(str);
}
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(3); //-1无限循环
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto seq = cocos2d::Spawn::create(moveby, animate, nullptr);
seq->setTag(SMALL_MOVE_ACTION_TAG);
this->runAction(seq);
}
void SmallMonster::attack(cocos2d::Vec2 diff){
//僵尸朝向攻击的方向
int dir = getdirection(diff);
stopActionByTag(SMALL_MOVE_ACTION_TAG); //停掉移动的动作
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "a0_0%d.png";
switch (dir) {
case 0:break;
case 1:openfile[1] = '1'; break;
case 2:openfile[1] = '2'; break;
case 3:openfile[1] = '3'; break;
default:
break;
}
for (int i = 1; i <= 2; i++) {
char str[50];
sprintf(str, openfile, i);
animation->cocos2d::Animation::addSpriteFrameWithFile(str);
}
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(1); //
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto seq = cocos2d::Spawn::create(animate, nullptr);
this->runAction(seq);
if (!is_under_attack) { //如果被攻击,有僵直,无法攻击
//创建空白球
auto fireball = Sprite::create("blank.png");
fireball->setPosition(cocos2d::Vec2(75, 75));
auto physicsBody = cocos2d::PhysicsBody::createCircle(20.0f, cocos2d::PhysicsMaterial(0.0f, 0.0f, 0.0f));
physicsBody->setDynamic(false);
physicsBody->setContactTestBitmask(0xFFFFFFFF);
fireball->setPhysicsBody(physicsBody);
fireball->setTag(FIREBALL_TAG);
//添加到场景中
this->addChild(fireball);
// 将偏移量转化为单位向量,即长度为1的向量。
diff.normalize();
// 将其乘以2000,你就获得了一个指向用户触屏方向的长度为2000的向量。为什么是2000呢?因为长度应当足以超过当前分辨率下屏幕的边界。
auto shootAmount = diff * 75;
// 5.创建一个动作,在2秒内移动到目标位置,然后将它从场景中移除。
auto actionMove = cocos2d::MoveBy::create(1.0f, shootAmount);
auto actionRemove = cocos2d::RemoveSelf::create();
fireball->runAction(cocos2d::Sequence::create(actionMove, actionRemove, nullptr));
}
}
void SmallMonster::under_attack(cocos2d::Vec2 diff,int de_hp){
is_under_attack = true;
this->hp -= de_hp;
stopActionByTag(SMALL_MOVE_ACTION_TAG); //停掉移动的动作
//后退,向被攻击的反方向
int dir = getdirection(diff);
int distance = 20;
float time = 0.3;
auto move_down = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, -distance));
auto move_up = cocos2d::MoveBy::create(time, cocos2d::Vec2(0, distance));
auto move_right = cocos2d::MoveBy::create(time, cocos2d::Vec2(distance, 0));
auto move_left = cocos2d::MoveBy::create(time, cocos2d::Vec2(-distance, 0));
auto moveby = move_up;
//移动
switch (dir) {
case 0:moveby = move_up; break;
case 1:moveby = move_down; break;
case 2:moveby = move_left; break;
case 3:moveby = move_right; break;
default:
moveby = move_up;
break;
}
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "0_0%d.png";
switch (dir) {
case 1:break;
case 0:openfile[0] = '1'; break;
case 3:openfile[0] = '2'; break;
case 2:openfile[0] = '3'; break;
default:break;
}
for (int i = 1; i <= 1; i++) {
char str[50];
sprintf(str, openfile, i);
animation->cocos2d::Animation::addSpriteFrameWithFile(str);
}
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(0.5); //单位帧间隔
animation->setLoops(0); //静止的图片
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto seq = cocos2d::Spawn::create(moveby, animate, nullptr);
//auto delay = cocos2d::DelayTime::create(2);
this->runAction(cocos2d::Sequence::create(seq, nullptr));
is_under_attack = false;
}
void SmallMonster::death(){
//相应的移动动画
auto animation = cocos2d::Animation::create();
//添加图片资源
char openfile[16] = "Small_d.png";
animation->cocos2d::Animation::addSpriteFrameWithFile(openfile);
//设置属性
animation->setRestoreOriginalFrame(false); //还原第一帧
animation->setDelayPerUnit(1); //单位帧间隔
animation->setLoops(0); //静止的图片
//创建动画
auto animate = cocos2d::Animate::create(animation);
auto fade = cocos2d::FadeTo::create(2, 0);
auto seq = cocos2d::Spawn::create(fade, animate, nullptr);
this->runAction(cocos2d::Sequence::create(seq, nullptr));
}
|
#ifndef CVML_OP_H
#define CVML_OP_H
class CVMLOp {
private:
enum { MAX_ARGUMENTS = 2 };
CVML& vml_;
CVMLOpCode* op_code_;
uint pc_;
uint line_num_;
uint num_arguments_;
CVMLArgument** arguments_;
public:
CVMLOp(CVML &vml, CVMLOpCode *op_code,
uint pc, uint line_num) :
vml_(vml), op_code_(op_code), pc_(pc), line_num_(line_num) {
num_arguments_ = op_code->num_args;
arguments_ = new CVMLArgument * [num_arguments_];
for (uint i = 0; i < num_arguments_; ++i)
arguments_[i] = new CVMLArgument(&vml_);
}
~CVMLOp() {
for (uint i = 0; i < num_arguments_; ++i)
delete arguments_[i];
delete [] arguments_;
}
bool equal(const CVMLOp &op);
uint getPC() const { return pc_; }
int lineNum() const { return line_num_; }
void setArgument(uint i, CVMLArgument &argument) {
if (i < num_arguments_)
*(arguments_[i]) = argument;
}
bool isArgument(uint i) {
return (i < num_arguments_);
}
CVMLArgument *getArgument(uint i) {
if (i < num_arguments_)
return arguments_[i];
else
return NULL;
}
uint getAddressLen();
friend std::ostream &operator<<(std::ostream &os, CVMLOp &op) {
op.print(os);
return os;
}
void print(std::ostream &os);
void printData(std::ostream &os, bool show_code, int indent);
void printCode(std::ostream &os);
void encode(CFile *file);
uint getEncodeSize();
private:
ushort getValue(ushort *extraValue1, bool *extraValueFlag1,
ushort *extraValue2, bool *extraValueFlag2);
};
#endif
|
#include "system.h"
#include "Integrators/integrator.h"
#include "Potentials/potential.h"
#include "InitialConditions/initialcondition.h"
#include "particle.h"
#include "time.h"
#include <iostream>
#include <cmath>
using std::cout;
using std::endl;
void System::computeForces() {
//resetting forces and potential energy before calculating new forces
resetAllForces();
m_potential->resetPotentialEnergy();
for (int i=0; i<m_numberOfParticles; i++) {
for (int j=i+1; j<m_numberOfParticles; j++) {
Particle *a = m_particles.at(i);
Particle *b = m_particles.at(j);
m_potential->computeForces(*a, *b);
}
}
}
void System::resetAllForces() {
for (int i=0; i<m_numberOfParticles; i++) {
m_particles.at(i)->resetForces();
m_particles.at(i)->resetPotentialEnergy();
}
}
void System::setPotential(Potential* potential) {
m_potential = potential;
}
void System::setIntegrator(Integrator* integrator) {
m_integrator = integrator;
}
void System::setInitialCondition(InitialCondition* initialCondition) {
m_initialCondition = initialCondition;
m_initialCondition->setupParticles(*this);
}
void System::setDt(double dt) {
m_integrator->setDt(dt);
}
void System::integrate(int numberOfSteps) {
clock_t start, finish;
start = clock();
m_integrateSteps = numberOfSteps;
printIntegrateInfo(0);
removeLinearMomentum();
computeMassCenter();
for (int i=1; i<numberOfSteps+1; i++) {
m_integrator->integrateOneStep(m_particles);
printIntegrateInfo(i);
writePositionsToFile();
}
finish =clock();
double t = ((finish-start));
double seconds = t/CLOCKS_PER_SEC;
cout << "Time computations took: " << seconds <<"s"<< endl;
closeOutFile();
}
void System::addParticle(Particle* p) {
m_particles.push_back(p);
m_numberOfParticles += 1;
}
void System::computeKineticEnergy() {
m_kineticEnergy = 0;
for(int i = 0; i<m_numberOfParticles; i++) {
Particle *p = m_particles.at(i);
double v_squared = p->velocitySquared();
m_kineticEnergy += (v_squared *p->getMass());
}
}
void System::integratePerihelionAngle(int numberOfSteps) {
m_integrateSteps = numberOfSteps;
printIntegrateInfo(0);
removeLinearMomentum();
clock_t start, finish;
start = clock();
double r_PreviousPrevious = 0.0;
double r_Previous = 0.0;
vec3 r_PreviousPosition = vec3(0,0,0);
double angle;
for (int i=0; i<numberOfSteps; i++) {
angle = 0.0;
m_integrator->integrateOneStep(m_particles);
vec3 temp = m_particles[1]->getPosition();
temp.operator -=(m_particles[0]->getPosition());
double r_Current = temp.length();
if (m_outFileOpen == false) {
m_outFile.open("positions.dat", std::ios::out);
m_outFileOpen = true;
}
if (r_Current > r_Previous && r_Previous < r_PreviousPrevious ) {
// At perihelion
double x = r_PreviousPosition[0];
double y = r_PreviousPosition[1];
angle = atan2(y,x);
}
m_outFile << angle << endl;
r_PreviousPrevious = r_Previous;
r_Previous = r_Current;
r_PreviousPosition = m_particles[1]->getPosition().operator -= (m_particles[0]->getPosition());
}
m_outFile.close();
finish = clock();
double t = ((finish-start));
double seconds = t/CLOCKS_PER_SEC;
cout << "Computations took: " << seconds <<"s"<< endl;
}
void System::computePotentialEnergy() {
m_potentialEnergy = 0;
for (int i=0; i<m_numberOfParticles; i++) {
Particle *p = m_particles.at(i);
m_potentialEnergy += p->getPotentialEnergy();
}
}
void System::computeMassCenter() {
vec3 mass_center = vec3(0,0,0);
double m_sum = 0;
vec3 r = vec3(0,0,0);
for (int i = 0; i<m_numberOfParticles; i++) {
r = vec3(0,0,0);
r = m_particles.at(i)->getPosition();
mass_center.operator +=(r.operator *=(m_particles.at(i)->getMass()));
m_sum += m_particles.at(i)->getMass();
}
mass_center.operator /=(m_sum);
for ( int i = 0; i<m_numberOfParticles; i++) {
m_particles.at(i)->getVelocity().operator-=(mass_center);
}
}
void System::printIntegrateInfo(int stepNumber) {
if (stepNumber == 0) {
cout << endl
<< " STARTING INTEGRATION " << endl
<< "-------------------------" << endl
<< " o Number of steps: " << m_integrateSteps << endl
<< " o Time step, dt: " << m_integrator->getDt() << endl
<< " o Initial condition: " << m_initialCondition->getName() << endl
<< " o Number of particles: " << m_particles.size() << endl
<< " o Potential in use: " << m_potential->getName() << endl
<< " o Integrator in use: " << m_integrator->getName() << endl
<< endl;
} else if (stepNumber % 10000 == 0) {
computeKineticEnergy();
computePotentialEnergy();
computeTotalMomentum();
m_totalEnergy = m_kineticEnergy + m_potentialEnergy;
printf("Step: %5d E =%8.5f Ek =%8.5f Ep =%8.5f M=%8.5f\n" ,
stepNumber, m_totalEnergy, m_kineticEnergy, m_potentialEnergy, m_totalMomentum);
fflush(stdout);
}
}
void System::removeLinearMomentum() {
computeTotalMomentum();
m_particles.at(0)->getVelocity().operator -=(m_vecMomentum);
computeTotalMomentum();
cout << "Sun v" << m_particles.at(0)->getVelocity() << "TotalM" << m_vecMomentum<< endl;
}
void System::computeTotalMomentum() {
m_vecMomentum = vec3(0,0,0);
m_totalMomentum = 0;
vec3 v_temp = vec3(0,0,0);
for (int i = 0; i<m_numberOfParticles; i++) {
//Particle *p = m_particles.at(i);
double m = m_particles.at(i)->getMass();
v_temp = m_particles.at(i)->getVelocity();
m_vecMomentum.operator += (v_temp.operator *=(m));
}
m_totalMomentum = m_vecMomentum.length();
}
void System::setFileWriting(bool writeToFile) {
m_writeToFile = writeToFile;
}
void System::writePositionsToFile() {
if (m_outFileOpen == false) {
m_outFile.open("positions.dat", std::ios::out);
m_outFileOpen = true;
}
double x[m_numberOfParticles];
double y[m_numberOfParticles];
for (int i = 0; i<m_numberOfParticles; i++) {
Particle *p = m_particles.at(i);
vec3 r = p->getPosition();
x[i] = r[0];
y[i] = r[1];
if (i<(m_numberOfParticles-1)) {
m_outFile << x[i] << "," << y[i]<< ",";
} else {
m_outFile << x[i] << "," << y[i];
}
} m_outFile << endl;
}
void System::closeOutFile() {
if (m_writeToFile == true) {
m_outFile.close();
m_outFileOpen = false;
}
}
|
#include "dfBasic.h"
dfBasicType dfGetTypeFromString(std::vector<char> str)
{
if(dfStrCmp(str, "int"))
{
return DF_int;
}
else if(dfStrCmp(str, "float"))
{
return DF_float;
}
else if(dfStrCmp(str, "vec2"))
{
return DF_vec2;
}
else if(dfStrCmp(str, "vec3"))
{
return DF_vec3;
}
else if(dfStrCmp(str, "vec4"))
{
return DF_vec4;
}
else if(dfStrCmp(str, "rect"))
{
return DF_rect;
}
else if(dfStrCmp(str, "mat4"))
{
return DF_mat4x4;
}
else if(dfStrCmp(str, "mat4"))
{
return DF_mat4x4;
}
else if(dfStrCmp(str, "point2D"))
{
return DF_point2D;
}
else if(dfStrCmp(str, "sampler2D"))
{
return DF_sampler2D;
}
return DF_null;
}
void InitAsciiTable()
{
asciiTable[' '] = 32;
asciiTable['!'] = 33;
asciiTable['\"'] = 34;
asciiTable['#'] = 35;
asciiTable['$'] = 36;
asciiTable['%'] = 37;
asciiTable['&'] = 38;
asciiTable['\''] = 39;
asciiTable['('] = 40;
asciiTable[')'] = 41;
asciiTable['*'] = 42;
asciiTable['+'] = 43;
//asciiTable[''] = 44;
asciiTable['-'] = 45;
asciiTable['.'] = 46;
asciiTable['/'] = 47;
asciiTable['0'] = 48;
asciiTable['1'] = 49;
asciiTable['2'] = 50;
asciiTable['3'] = 51;
asciiTable['4'] = 52;
asciiTable['5'] = 53;
asciiTable['6'] = 54;
asciiTable['7'] = 55;
asciiTable['8'] = 56;
asciiTable['9'] = 57;
asciiTable[':'] = 58;
asciiTable[';'] = 59;
asciiTable['<'] = 60;
asciiTable['='] = 61;
asciiTable['>'] = 62;
asciiTable['?'] = 63;
asciiTable['@'] = 64;
asciiTable['A'] = 65;
asciiTable['B'] = 66;
asciiTable['C'] = 67;
asciiTable['D'] = 68;
asciiTable['E'] = 69;
asciiTable['F'] = 70;
asciiTable['G'] = 71;
asciiTable['H'] = 72;
asciiTable['I'] = 73;
asciiTable['J'] = 74;
asciiTable['K'] = 75;
asciiTable['L'] = 76;
asciiTable['M'] = 77;
asciiTable['N'] = 78;
asciiTable['O'] = 79;
asciiTable['P'] = 80;
asciiTable['Q'] = 81;
asciiTable['R'] = 82;
asciiTable['S'] = 83;
asciiTable['T'] = 84;
asciiTable['U'] = 85;
asciiTable['V'] = 86;
asciiTable['W'] = 87;
asciiTable['X'] = 88;
asciiTable['Y'] = 89;
asciiTable['Z'] = 90;
asciiTable['['] = 91;
asciiTable['\\'] = 92;
asciiTable[']'] = 93;
asciiTable['^'] = 94;
asciiTable['_'] = 95;
asciiTable['`'] = 96;
asciiTable['a'] = 97;
asciiTable['b'] = 98;
asciiTable['c'] = 99;
asciiTable['d'] = 100;
asciiTable['e'] = 101;
asciiTable['f'] = 102;
asciiTable['g'] = 103;
asciiTable['h'] = 104;
asciiTable['i'] = 105;
asciiTable['j'] = 106;
asciiTable['k'] = 107;
asciiTable['l'] = 108;
asciiTable['m'] = 109;
asciiTable['n'] = 110;
asciiTable['o'] = 111;
asciiTable['p'] = 112;
asciiTable['q'] = 113;
asciiTable['r'] = 114;
asciiTable['s'] = 115;
asciiTable['t'] = 116;
asciiTable['u'] = 117;
asciiTable['v'] = 118;
asciiTable['q'] = 119;
asciiTable['x'] = 120;
asciiTable['y'] = 121;
asciiTable['z'] = 122;
asciiTable['{'] = 123;
asciiTable['|'] = 124;
asciiTable['}'] = 125;
asciiTable['~'] = 126;
}
void InitEngine()
{
InitAsciiTable();
}
|
#ifndef MASTERS_PROJECT_BINOMIALDIVIDENDMETHOD_H
#define MASTERS_PROJECT_BINOMIALDIVIDENDMETHOD_H
#include <map>
#include "../BinomialMethod.hpp"
#include "Dividend.hpp"
template<typename X>
class BinomialDividendMethod : public BinomialMethod<X> {
public:
int dividend_number;
Dividend<X> **dividends;
X **asset_prices;
public:
BinomialDividendMethod(Case<X> *_case, Dividend<X> **dividends, int dividend_number);
virtual ~BinomialDividendMethod();
protected:
X presentValueOfDividend(X div_amount, X tau, int i);
void build_asset_price_tree() override;
void calculate_payoff_for_initial_cond() override;
};
#include "BinomialDividendMethod.tpp"
#endif //MASTERS_PROJECT_BINOMIALDIVIDENDMETHOD_H
|
#include "parser_table.h"
std::vector < std::string > table_parser::extract_rows(std::string table){
return split_string(table, "|-");
}
std::vector < std::string > table_parser::extract_fields(std::string row){
return split_string(row, "||");
}
std::list < std::vector < std::string > > table_parser::table_to_df(std::string table){
table = remove(table, regex_def("\n"));
std::vector < std::string > rows = extract_rows(table);
std::vector < std::string > names = extract_fields(rows[0]);
std::list < std::vector < std::string > > output;
output.push_back(names);
return output;
}
|
#pragma once
#include <API/Code/Graphics/Material/CookTorranceMaterial.h>
#include <API/Code/Graphics/Mesh/3D/CubeMesh.h>
#include <API/Code/Graphics/Mesh/3D/SphereMesh.h>
#include <API/Code/Graphics/Mesh/3D/Mesh3D.h>
#include <API/Code/Graphics/Texture/TextureImage.h>
#include <API/Code/Graphics/Light/DirectionalLight/DirectionalLight.h>
#include <API/Code/Graphics/Light/PointLight/PointLight.h>
#include <API/Code/Graphics/Renderer/Renderer.h>
#include <API/Code/Maths/Curve/CurveHermite.h>
class SnowPlane;
/// <summary>
/// Holds : <para/>
/// - The objects interacting with the snow<para/>
/// - The lights<para/>
/// - The animation of the boots.
/// </summary>
class Scene
{
public:
/// <summary>Initialize the scene objects.</summary>
Scene();
/// <summary>Render of the target only the objects interacting with the snow.</summary>
/// <param name="_Renderer">The rendering target.</param>
/// <param name="_DepthMaterial">The material to use (will be the one in the DepthPass class).</param>
/// <param name="_Camera">The camera to use (will be the one bellow the ground).</param>
void RenderDepthPass( ae::Renderer& _Renderer, const ae::Material& _DepthMaterial, ae::Camera& _Camera );
/// <summary>Render all the objects on the target.</summary>
/// <param name="_Renderer">The rendering target.</param>
void RenderColorPass( ae::Renderer& _Renderer );
/// <summary>Update the boots objects animations.</summary>
void UpdateBootsAnim();
private:
/// <summary>Common material for objects.</summary>
ae::CookTorranceMaterial m_ObjectsMat;
// Objets.
ae::SphereMesh m_Ball;
ae::Mesh3D m_Lantern;
ae::Mesh3D m_MooMoo;
ae::TextureImage m_MooMooTexture;
ae::Mesh3D m_FenceBack;
ae::Mesh3D m_FenceLeft;
ae::Mesh3D m_LeftBoot;
ae::Mesh3D m_RightBoot;
// Lights
ae::DirectionalLight m_AmbientLight;
ae::PointLight m_LanternLight;
// Boots animation.
ae::CurveHermite m_BootsTrajectoryLeft;
ae::CurveHermite m_BootsTrajectoryRight;
float m_BootsAnimTime;
const float m_BootsAnimTotalTime;
};
|
#include <cassert>
namespace rlrpg
{
template<class T>
Optional<T>::Optional():
m_exists(false)
{
}
template<class T>
Optional<T>::Optional(empty_t):
m_exists(false)
{
}
template<class T>
Optional<T>::Optional(default_t):
m_exists(false)
{
in_place();
}
template<class T>
template<class ...Args>
Optional<T>::Optional(Args &&... args):
m_exists(true)
{
new (m_instance) T(std::forward<Args>(args)...);
}
template<class T>
Optional<T>::operator bool() const
{
return m_exists;
}
template<class T>
template<class ...Args>
void Optional<T>::in_place(Args && ... args)
{
if(m_exists)
{
reinterpret_cast<T&>(m_instance[0]) = T(std::forward<Args>(args)...);
} else
{
new (m_instance) T(std::forward<Args>(args)...);
m_exists = true;
}
}
template<class T>
T const& Optional<T>::operator()() const
{
assert(m_exists && "Tried to access empty object.");
return reinterpret_cast<T const&>(m_instance[0]);
}
template<class T>
T & Optional<T>::operator()()
{
assert(m_exists && "Tried to access empty object.");
return reinterpret_cast<T &>(m_instance[0]);
}
template<class T>
Optional<T>::~Optional()
{
if(m_exists)
reinterpret_cast<T*>(m_instance)->~T();
}
template<class T>
Optional<T> &Optional<T>::operator=(empty_t)
{
if(m_exists)
{
reinterpret_cast<T*>(m_instance)->~T();
m_exists = false;
}
}
}
|
/* IBM_PROLOG_BEGIN_TAG */
/*
* Copyright 2003,2016 IBM International Business Machines Corp.
*
* 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.
*/
/* IBM_PROLOG_END_TAG */
#ifndef _Cargdata_h
#define _Cargdata_h
class CArgData {
// member data
private:
ARGS_T *dataptr;
// member functions
public:
// constructor and destructor.
CArgData();
~CArgData();
// Note this function is public but it should only be used for the
// initialization of the htx_data struct. Do not use this for sending
// htx messages use the Cmsg class...!!!!
ARGS_T *GetArgDataPtr();
};
#endif
|
#include "Device.h"
#include "Resource/Effect/EffectFabric.h"
#include "Resource/Effect/Effect.h"
#include "Keng/Base/Serialization/SerializeMandatory.h"
#include "yasli/STL.h"
#include "EverydayTools/Exception/CallAndRethrow.h"
#include "EverydayTools/Exception/ThrowIfFailed.h"
namespace keng::graphics
{
const char* EffectFabric::GetNodeName() const {
return "effect";
}
const char* EffectFabric::GetResourceType() const {
return "Effect";
}
resource::IResourcePtr EffectFabric::LoadResource(resource::IResourceSystem& resourceSystem,
Archive& ar, const resource::IDevicePtr& abstractDevice) const {
return CallAndRethrowM + [&] {
edt::ThrowIfFailed(abstractDevice != nullptr, "Can't create effect without device");
auto device = std::dynamic_pointer_cast<Device>(abstractDevice);
auto result = EffectPtr::MakeInstance();
// TODO: check legal shader types combinations?
struct EffectInfo {
void serialize(Archive& ar) {
ar(vs, "vertex_shader");
ar(fs, "fragment_shader");
}
std::string vs;
std::string fs;
};
EffectInfo effectInfo;
SerializeMandatory(ar, effectInfo, GetNodeName());
bool anyShader = false;
{
if (!effectInfo.vs.empty()) {
auto base = resourceSystem.GetResource(effectInfo.vs.data(), device);
result->vs = std::dynamic_pointer_cast<Shader<ShaderType::Vertex>>(base);
anyShader = true;
}
}
{
if (!effectInfo.fs.empty()) {
auto base = resourceSystem.GetResource(effectInfo.fs.data(), device);
result->fs = std::dynamic_pointer_cast<Shader<ShaderType::Fragment>>(base);
anyShader = true;
}
}
edt::ThrowIfFailed(anyShader, "Invalid effect file (0 shaders)");
return result;
};
}
}
|
#pragma once
#include<iostream>
#include<vector>
#include<assert.h>
using namespace std;
template<class T,class Compare>
class Heap //仿函数管理大小堆更方便
{
public:
Heap()
{}
Heap(T* a, size_t n)
{
_a.reserve(n);
for (size_t i = 0; i < n; ++i)
{
_a.push_back(a[i]);
}
//建堆
for (int i = (_a.size() - 2) / 2; i >= 0; --i)//需要等于0所以用int
{
AdjustDown(i);
}
}
size_t Size()
{
return _a.size();
}
void AdjustDown(int root)//向下调整
{
Compare com;
int parent = root;
int child = parent * 2 + 1;
while (child < _a.size())
{
if (child + 1 < _a.size()
&& com(_a[child + 1],_a[child]))//比较出大的孩子
{
++child;
}
if (com(_a[child], _a[parent]))
{
swap(_a[child], _a[parent]);
parent = child;
child = parent * 2 + 1;
}
else //表示父亲大于孩子
{
break;
}
}
}
void Push(const T& x)
{
_a.push_back(x);
AdjustUp(_a.size() - 1);
}
void AdjustUp(int child)//向上调整
{
Compare com;
int parent = (child - 1) / 2;
while (child > 0)//这里的parent不可能为负数
{
//if (_a[child]>_a[parent])
if (com(_a[child],_a[parent]))
{
swap(_a[child], _a[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void Pop()//pop最大的数据
{
assert(!_a.empty());
swap(_a[0], _a[_a.size() - 1]);
_a.pop_back();
AdjustDown(0);
}
T& Top()
{
assert(!_a.empty());
return _a[0];
}
private:
vector<T>_a;
};
template<class T>
struct Less
{
bool operator()(const T& l, const T& r)
{
return l < r;
}
};
template<class T>
struct Greater
{
bool operator()(const T& l, const T& r)
{
return l > r;
}
};
void AdjustDwon(int* a, size_t n, int root)
{
int parent = root;
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n
&& a[child + 1] > a[child])
{
++child;
}
if (a[parent] < a[child])
{
swap(a[parent], a[child]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int* a,size_t n)//堆排序
{
for (int i = (n - 2) / 2; i >= 0; --i)//建堆
{
AdjustDwon(a, n, i);
}
//排序
size_t end = n - 1;
while (end > 0)//当end不等于0时候就需要交换
{
swap(a[0], a[end]);
AdjustDwon(a, end, 0);//end 是最后数的下标以及个数
--end;
}
}
void TestHeap()
{
//int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
//Heap<int>hp1(a, sizeof(a)/sizeof(a[0]));
//hp1.Push(30);
//hp1.Pop();
/*int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
Heap<int,Less<int>>hp1(a, sizeof(a)/sizeof(a[0]));
Heap<int,Greater<int>>hp2(a, sizeof(a) / sizeof(a[0]));*/
//Less<int>less;
//cout << less(1, 2)<<endl;
}
|
/*
########################################################################
# Exemplo de Allegro orientado a objetos elaborado por: #
# Jorge Leandro Francisco #
# Monitor da Disciplina Fundamentos de Programação 2 #
# do curso de Engenharia Eletrônica da UTFPR #
# Prof. Jean M. Simão #
########################################################################
*/
#include "Principal.h"
int main()
{
Principal ObjPrincipal;
return 0;
}
END_OF_MAIN()
/*
Para trocar o ícone do executável:
1 - Escolher um ícone (.ico) personalizado e colocá-lo em uma
pasta à escolha. De preferência na pasta onde estão os arquivos do
jogo, como as imagens.
2 - Abrir o projeto do jogo e ir no menu
"Projeto -> Opções do Projeto -> Geral -> Navegar"
3 - Procurar o ícone e abrir.
*/
/*
Para que o código fique mais coerente com os princípios de orientação
a objetos, as funções de inicialização da biblioteca gráfica foram
retiradas do 'main' onde estavam implementadas de forma procedural e
incorporadas em uma classe GerenciadorGráfico.
O objeto gerenciador é agregado à classe Principal.
*/
|
/********************************************************************************
** Form generated from reading UI file 'CSoftUpgredeWidget.ui'
**
** Created by: Qt User Interface Compiler version 5.3.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CSOFTUPGREDEWIDGET_H
#define UI_CSOFTUPGREDEWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_CSoftUpgredeWidget
{
public:
QGridLayout *gridLayout_2;
QHBoxLayout *horizontalLayout;
QLabel *label;
QComboBox *comboBox_brand;
QSpacerItem *horizontalSpacer;
QLabel *label_2;
QLineEdit *lineEdit_brand;
QToolButton *tbtn_addbrand;
QToolButton *tbtn_Passwd;
QTableWidget *tableWidget;
QHBoxLayout *horizontalLayout_2;
QToolButton *tbtn_add;
QToolButton *tbtn_delete;
QSpacerItem *horizontalSpacer_3;
QPushButton *btn_Init;
QPushButton *btn_SaveData;
QPushButton *btn_Save;
void setupUi(QWidget *CSoftUpgredeWidget)
{
if (CSoftUpgredeWidget->objectName().isEmpty())
CSoftUpgredeWidget->setObjectName(QStringLiteral("CSoftUpgredeWidget"));
CSoftUpgredeWidget->resize(613, 392);
gridLayout_2 = new QGridLayout(CSoftUpgredeWidget);
gridLayout_2->setSpacing(6);
gridLayout_2->setContentsMargins(11, 11, 11, 11);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(0);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
label = new QLabel(CSoftUpgredeWidget);
label->setObjectName(QStringLiteral("label"));
horizontalLayout->addWidget(label);
comboBox_brand = new QComboBox(CSoftUpgredeWidget);
comboBox_brand->setObjectName(QStringLiteral("comboBox_brand"));
comboBox_brand->setMinimumSize(QSize(110, 0));
horizontalLayout->addWidget(comboBox_brand);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
label_2 = new QLabel(CSoftUpgredeWidget);
label_2->setObjectName(QStringLiteral("label_2"));
horizontalLayout->addWidget(label_2);
lineEdit_brand = new QLineEdit(CSoftUpgredeWidget);
lineEdit_brand->setObjectName(QStringLiteral("lineEdit_brand"));
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(lineEdit_brand->sizePolicy().hasHeightForWidth());
lineEdit_brand->setSizePolicy(sizePolicy);
lineEdit_brand->setMaximumSize(QSize(100, 16777215));
horizontalLayout->addWidget(lineEdit_brand);
tbtn_addbrand = new QToolButton(CSoftUpgredeWidget);
tbtn_addbrand->setObjectName(QStringLiteral("tbtn_addbrand"));
QIcon icon;
icon.addFile(QStringLiteral(":/Resources/plus.png"), QSize(), QIcon::Normal, QIcon::Off);
tbtn_addbrand->setIcon(icon);
tbtn_addbrand->setToolButtonStyle(Qt::ToolButtonIconOnly);
horizontalLayout->addWidget(tbtn_addbrand);
tbtn_Passwd = new QToolButton(CSoftUpgredeWidget);
tbtn_Passwd->setObjectName(QStringLiteral("tbtn_Passwd"));
QIcon icon1;
icon1.addFile(QStringLiteral(":/Resources/key.png"), QSize(), QIcon::Normal, QIcon::Off);
tbtn_Passwd->setIcon(icon1);
horizontalLayout->addWidget(tbtn_Passwd);
gridLayout_2->addLayout(horizontalLayout, 0, 0, 1, 1);
tableWidget = new QTableWidget(CSoftUpgredeWidget);
if (tableWidget->columnCount() < 7)
tableWidget->setColumnCount(7);
QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(0, __qtablewidgetitem);
QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(1, __qtablewidgetitem1);
QTableWidgetItem *__qtablewidgetitem2 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(2, __qtablewidgetitem2);
QTableWidgetItem *__qtablewidgetitem3 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(3, __qtablewidgetitem3);
QTableWidgetItem *__qtablewidgetitem4 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(4, __qtablewidgetitem4);
QTableWidgetItem *__qtablewidgetitem5 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(5, __qtablewidgetitem5);
QTableWidgetItem *__qtablewidgetitem6 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(6, __qtablewidgetitem6);
tableWidget->setObjectName(QStringLiteral("tableWidget"));
tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed);
tableWidget->setAlternatingRowColors(true);
tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
tableWidget->horizontalHeader()->setStretchLastSection(true);
tableWidget->verticalHeader()->setVisible(false);
gridLayout_2->addWidget(tableWidget, 1, 0, 1, 1);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
tbtn_add = new QToolButton(CSoftUpgredeWidget);
tbtn_add->setObjectName(QStringLiteral("tbtn_add"));
tbtn_add->setIcon(icon);
horizontalLayout_2->addWidget(tbtn_add);
tbtn_delete = new QToolButton(CSoftUpgredeWidget);
tbtn_delete->setObjectName(QStringLiteral("tbtn_delete"));
QIcon icon2;
icon2.addFile(QStringLiteral(":/Resources/minus.png"), QSize(), QIcon::Normal, QIcon::Off);
tbtn_delete->setIcon(icon2);
horizontalLayout_2->addWidget(tbtn_delete);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer_3);
btn_Init = new QPushButton(CSoftUpgredeWidget);
btn_Init->setObjectName(QStringLiteral("btn_Init"));
horizontalLayout_2->addWidget(btn_Init);
btn_SaveData = new QPushButton(CSoftUpgredeWidget);
btn_SaveData->setObjectName(QStringLiteral("btn_SaveData"));
horizontalLayout_2->addWidget(btn_SaveData);
btn_Save = new QPushButton(CSoftUpgredeWidget);
btn_Save->setObjectName(QStringLiteral("btn_Save"));
horizontalLayout_2->addWidget(btn_Save);
gridLayout_2->addLayout(horizontalLayout_2, 2, 0, 1, 1);
retranslateUi(CSoftUpgredeWidget);
QMetaObject::connectSlotsByName(CSoftUpgredeWidget);
} // setupUi
void retranslateUi(QWidget *CSoftUpgredeWidget)
{
CSoftUpgredeWidget->setWindowTitle(QApplication::translate("CSoftUpgredeWidget", "CSoftUpgredeWidget", 0));
label->setText(QApplication::translate("CSoftUpgredeWidget", "\345\223\201\347\211\214:", 0));
comboBox_brand->clear();
comboBox_brand->insertItems(0, QStringList()
<< QApplication::translate("CSoftUpgredeWidget", "\351\200\211\346\213\251\345\223\201\347\211\214", 0)
);
label_2->setText(QApplication::translate("CSoftUpgredeWidget", "\346\267\273\345\212\240\345\255\220\345\223\201\347\211\214\357\274\232", 0));
lineEdit_brand->setPlaceholderText(QApplication::translate("CSoftUpgredeWidget", "\350\276\223\345\205\245\345\223\201\347\211\214\345\220\215\347\247\260", 0));
#ifndef QT_NO_TOOLTIP
tbtn_addbrand->setToolTip(QApplication::translate("CSoftUpgredeWidget", "\346\267\273\345\212\240\345\223\201\347\211\214", 0));
#endif // QT_NO_TOOLTIP
tbtn_addbrand->setText(QString());
#ifndef QT_NO_TOOLTIP
tbtn_Passwd->setToolTip(QApplication::translate("CSoftUpgredeWidget", "\345\223\201\347\211\214\345\257\206\351\222\245\351\205\215\347\275\256", 0));
#endif // QT_NO_TOOLTIP
tbtn_Passwd->setText(QString());
QTableWidgetItem *___qtablewidgetitem = tableWidget->horizontalHeaderItem(0);
___qtablewidgetitem->setText(QApplication::translate("CSoftUpgredeWidget", "\350\275\257\344\273\266\345\220\215\347\247\260", 0));
QTableWidgetItem *___qtablewidgetitem1 = tableWidget->horizontalHeaderItem(1);
___qtablewidgetitem1->setText(QApplication::translate("CSoftUpgredeWidget", "\347\211\210\346\234\254\345\217\267", 0));
QTableWidgetItem *___qtablewidgetitem2 = tableWidget->horizontalHeaderItem(2);
___qtablewidgetitem2->setText(QApplication::translate("CSoftUpgredeWidget", "Url", 0));
QTableWidgetItem *___qtablewidgetitem3 = tableWidget->horizontalHeaderItem(3);
___qtablewidgetitem3->setText(QApplication::translate("CSoftUpgredeWidget", "\350\275\257\344\273\266\345\223\201\347\211\214", 0));
QTableWidgetItem *___qtablewidgetitem4 = tableWidget->horizontalHeaderItem(4);
___qtablewidgetitem4->setText(QApplication::translate("CSoftUpgredeWidget", "\350\275\257\344\273\266\347\261\273\345\210\253", 0));
QTableWidgetItem *___qtablewidgetitem5 = tableWidget->horizontalHeaderItem(5);
___qtablewidgetitem5->setText(QApplication::translate("CSoftUpgredeWidget", "\345\255\230\345\202\250\344\275\215\347\275\256", 0));
QTableWidgetItem *___qtablewidgetitem6 = tableWidget->horizontalHeaderItem(6);
___qtablewidgetitem6->setText(QApplication::translate("CSoftUpgredeWidget", "\344\270\273\347\250\213\345\272\217", 0));
#ifndef QT_NO_TOOLTIP
tbtn_add->setToolTip(QApplication::translate("CSoftUpgredeWidget", "\346\267\273\345\212\240\350\275\257\344\273\266", 0));
#endif // QT_NO_TOOLTIP
tbtn_add->setText(QString());
#ifndef QT_NO_TOOLTIP
tbtn_delete->setToolTip(QApplication::translate("CSoftUpgredeWidget", "\345\210\240\351\231\244", 0));
#endif // QT_NO_TOOLTIP
tbtn_delete->setText(QString());
btn_Init->setText(QApplication::translate("CSoftUpgredeWidget", "\350\277\230\345\216\237", 0));
btn_SaveData->setText(QApplication::translate("CSoftUpgredeWidget", "\344\277\235\345\255\230\351\205\215\347\275\256", 0));
btn_Save->setText(QApplication::translate("CSoftUpgredeWidget", "\347\224\237\346\210\220 XML", 0));
} // retranslateUi
};
namespace Ui {
class CSoftUpgredeWidget: public Ui_CSoftUpgredeWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CSOFTUPGREDEWIDGET_H
|
#include "StdAfx.h"
#include "voxelObject.h"
#include "Utility_wrap.h"
// voxelBox methods
voxelBox::voxelBox()
{
boneIndex = -1;
state = -1;
}
voxelBox::voxelBox(Vec3f ld, Vec3f ru)
: voxelBox()
{
leftDown = ld;
rightUp = ru;
center = (leftDown+rightUp)/2;
boneIndex = -1;
}
voxelBox::~voxelBox()
{
}
void voxelBox::draw(int mode)
{
if (mode == 0) // draw edge
{
Util_w::drawBoxWireFrame(leftDown, rightUp);
}
if (mode == 1) // draw solid box
{
Util_w::drawBoxSurface(leftDown, rightUp);
}
}
// hashVoxel methods
hashVoxel::hashVoxel()
{
}
hashVoxel::~hashVoxel()
{
}
int hashVoxel::getBoxIndexFromCoord(Vec3f coordf)
{
Vec3i xyzIdx = getVoxelCoord(coordf);
return getBoxIndexFromVoxelCoord(xyzIdx);
}
int hashVoxel::getBoxIndexFromCoord(Vec3f leftDown, Vec3f rightUp)
{
return getBoxIndexFromCoord((leftDown+rightUp)/2);
}
Vec3i hashVoxel::getVoxelCoord(Vec3f coordf)
{
return Util_w::XYZ2IJK(coordf-leftDown, voxelSize);
}
int hashVoxel::getBoxIndexFromVoxelCoord(Vec3i coordi)
{
for (int i = 0; i < 3; i++)
{
if (coordi[i] < 0 || coordi[i] >= NumXYZ[i])
{
return -1;
}
}
int hashF = coordi[2]*NumXYZ[0]*NumXYZ[1] + coordi[1]*NumXYZ[0] + coordi[0];
if (hashF < 0 || hashF >= voxelHash.size())
{
return -1;
}
return voxelHash[hashF];
}
int hashVoxel::getSymmetricBox(int idx)
{
voxelBox vOrigin = boxes->at(idx);
Vec3f centerOri = vOrigin.center;
Vec3f centerSym = centerOri;
// Symmetric through X axis
Vec3f centerPoint = (leftDown + rightUp)/2;
centerSym[0] = 2*centerPoint[0] - centerSym[0];
return getBoxIndexFromCoord(centerSym);
}
std::vector<int> hashVoxel::getNeighbor(int idx)
{
static bool inited = false;
if (!inited)
{
inited = true;
neighborOfBox.resize(boxes->size());
for(int i = 0; i < NumXYZ[0]; i++)
{
for (int j = 0; j < NumXYZ[1]; j++)
{
for(int k = 0; k < NumXYZ[2]; k++)
{
int idx = getBoxIndexFromVoxelCoord(Vec3i(i,j,k));
if (idx != -1)
{
for (int xx = 0; xx < 2; xx++)
{
for (int yy = 0; yy < 2; yy++)
{
for (int zz = 0; zz < 2; zz++)
{
int idxN = getBoxIndexFromVoxelCoord(Vec3i(i+xx, j+yy, k+zz));
if (idxN != -1 && idx != idxN)
{
neighborOfBox[idx].push_back(idxN);
neighborOfBox[idxN].push_back(idx);
}
}
}
}
}
}
}
}
}
return neighborOfBox[idx];
}
Vec3f hashVoxel::IJK2XYZ(Vec3i voxelCi)
{
return leftDown + Util_w::IJK2XYZ(voxelCi, voxelSize);
}
Vec3f hashVoxel::IJK2XYZLower(Vec3i coordi)
{
Vec3f pt = IJK2XYZ(coordi);
return pt - Vec3f(voxelSize, voxelSize, voxelSize) / 2;
}
Vec3f hashVoxel::IJK2XYZUpper(Vec3i coordi)
{
Vec3f pt = IJK2XYZ(coordi);
return pt + Vec3f(voxelSize, voxelSize, voxelSize) / 2;
}
// voxelObject methods
voxelObject::voxelObject()
{
}
voxelObject::~voxelObject()
{
}
bool voxelObject::init(SurfaceObj *obj, int res)
{
s_surObj = obj;
// Octree
m_octree.init(s_surObj, res);
m_centerf = m_octree.centerMesh;
m_voxelSizef = m_octree.boxSize;
// Voxel hash
constructVolxeHash();
// Boxes
constructNeighbor();
return true;
}
bool voxelObject::init(SurfaceObj *obj, int res, float scale)
{
s_surObj = obj;
// Octree
m_octree.init(s_surObj, res);
m_centerf = m_octree.centerMesh;
m_voxelSizef = m_octree.boxSize;
// Voxel hash
constructVolxeHash(scale);
// Boxes
constructNeighbor();
return true;
}
bool voxelObject::init(voxelObject *highRes, int voxelRes)
{
s_surObj = highRes->s_surObj;
// Octree
m_octree.init(s_surObj, voxelRes);
m_centerf = m_octree.centerMesh;
m_voxelSizef = m_octree.boxSize;
// Remove high empty box
m_octree.removeLowOccupationBox(&highRes->m_octree);
// Voxel hash
constructVolxeHash();
// Boxes
constructNeighbor();
return false;
}
bool voxelObject::init(voxelObject *highRes, float voxelSize)
{
s_surObj = highRes->s_surObj;
// Octree
m_octree.init(s_surObj, voxelSize);
m_centerf = m_octree.centerMesh;
m_voxelSizef = m_octree.boxSize;
// Remove high empty box
m_octree.removeLowOccupationBox(&highRes->m_octree);
// Voxel hash
constructVolxeHash();
// Boxes
constructNeighbor();
return true;
}
bool voxelObject::initWithSize(SurfaceObj *obj, float voxelSize)
{
s_surObj = obj;
// Octree
m_octree.init(s_surObj, voxelSize);
m_centerf = m_octree.centerMesh;
m_voxelSizef = m_octree.boxSize;
// Voxel hash
constructVolxeHash();
// Boxes
constructNeighbor();
return true;
}
void voxelObject::constructVolxeHash()
{
float voxelSize = m_octree.boxSize;
Vec3f gap(voxelSize, voxelSize, voxelSize);
Vec3f leftDownVoxel = m_octree.m_root->leftDownTight - gap;
Vec3f rightUpVoxel = m_octree.m_root->rightUpTight + gap;
Vec3f sizef = rightUpVoxel - leftDownVoxel;
Vec3i NumXYZ;
for (int i = 0; i < 3; i++)
{
NumXYZ[i] = (sizef[i] / m_voxelSizef);
}
m_hashTable.leftDown = leftDownVoxel;
m_hashTable.rightUp = rightUpVoxel;
m_hashTable.voxelSize = m_voxelSizef;
m_hashTable.NumXYZ = NumXYZ;
m_hashTable.boxes = &m_boxes;
// voxel index and hash
std::vector<int> voxelHash;
voxelHash.resize(NumXYZ[0] * NumXYZ[1] * NumXYZ[2]);
std::fill(voxelHash.begin(), voxelHash.end(), -1);
std::vector<octreeSNode*> *leaves = &m_octree.leaves;
m_boxes.resize(leaves->size());
for (int i = 0; i < leaves->size(); i++){
octreeSNode* node = leaves->at(i);
// List
voxelBox newBox(node->leftDownf, node->rightUpTight);
Vec3f xyzIdx = m_hashTable.getVoxelCoord(newBox.center);
newBox.xyzIndex = xyzIdx;
m_boxes[i] = newBox;
// Hash
int hashF = xyzIdx[2] * NumXYZ[0] * NumXYZ[1] + xyzIdx[1] * NumXYZ[0] + xyzIdx[0];
voxelHash[hashF] = i;
node->idxInLeaf = i;
}
m_hashTable.voxelHash = voxelHash;
}
Vec3f voxelObject::floorV(Vec3f v, float d)
{
Vec3f ld = m_hashTable.leftDown;
Vec3f dv = v - ld;
for (int i = 0; i < 3; i++)
{
dv[i] = d*floor(dv[i] / d);
}
return dv+ld;
}
void voxelObject::constructVolxeHash(float scale)
{
// Scale the bounding box
float voxelSize = m_octree.boxSize;
Vec3f unitV(voxelSize, voxelSize, voxelSize);
Vec3f leftDownVoxel = m_octree.m_root->leftDownTight;
Vec3f rightUpVoxel = m_octree.m_root->rightUpTight;
Vec3f boundSize = rightUpVoxel - leftDownVoxel;
leftDownVoxel = leftDownVoxel - boundSize*(scale / 2);
rightUpVoxel = rightUpVoxel + boundSize*(scale / 2);
// Snap the bounding box to voxel conner
leftDownVoxel = floorV(leftDownVoxel, m_voxelSizef);
rightUpVoxel = floorV(rightUpVoxel, m_voxelSizef);
// Construct
Vec3f sizef = rightUpVoxel - leftDownVoxel;
Vec3i NumXYZ;
for (int i = 0; i < 3; i++)
{
NumXYZ[i] = (sizef[i] / m_voxelSizef);
}
m_hashTable.leftDown = leftDownVoxel;
m_hashTable.rightUp = rightUpVoxel;
m_hashTable.voxelSize = m_voxelSizef;
m_hashTable.NumXYZ = NumXYZ;
m_hashTable.boxes = &m_boxes;
// voxel index and hash
std::vector<int> voxelHash;
voxelHash.resize(NumXYZ[0] * NumXYZ[1] * NumXYZ[2]);
std::fill(voxelHash.begin(), voxelHash.end(), -1);
std::vector<octreeSNode*> *leaves = &m_octree.leaves;
m_boxes.resize(leaves->size());
for (int i = 0; i < leaves->size(); i++)
{
octreeSNode* node = leaves->at(i);
// List
voxelBox newBox(node->leftDownf, node->rightUpTight);
Vec3i xyzIdx = m_hashTable.getVoxelCoord(newBox.center);
newBox.xyzIndex = xyzIdx;
m_boxes[i] = newBox;
// Hash
int hashF = xyzIdx[2] * NumXYZ[0] * NumXYZ[1] + xyzIdx[1] * NumXYZ[0] + xyzIdx[0];
voxelHash[hashF] = i;
node->idxInLeaf = i;
}
m_hashTable.voxelHash = voxelHash;
}
void voxelObject::constructNeighbor()
{
// Temp var
std::vector<Vec3i> allRelativeNeighbor;
Vec3i indexGap(-1, 0, 1);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
if (i == 0 && j == 0 && k == 0) // itself
{
continue;
}
allRelativeNeighbor.push_back(Vec3i(indexGap[i], indexGap[j], indexGap[k]));
}
}
}
// Construct all neighbor information
m_allBoxAroundBox.clear();
for (int i = 0; i < m_boxes.size(); i++)
{
Vec3i curBoxCoordi = m_boxes[i].xyzIndex;
arrayInt neighborIdxs;
for (int j = 0; j < allRelativeNeighbor.size(); j++)
{
Vec3i neighbori = curBoxCoordi + allRelativeNeighbor[j];
int nbIdx = m_hashTable.getBoxIndexFromVoxelCoord(neighbori);
if (nbIdx != -1)
{
neighborIdxs.push_back(nbIdx);
}
}
m_allBoxAroundBox.push_back(neighborIdxs);
}
// Construct neighbor that share face
m_boxShareFaceWithBox.clear();
for (int i = 0; i < m_boxes.size(); i++)
{
Vec3i curBoxCoordi = m_boxes[i].xyzIndex;
arrayInt neighborIdxs;
for (int j = 0; j < 3; j++)
{
for (int dd = -1; dd < 2; dd += 2)
{
Vec3i neighbori = curBoxCoordi;
neighbori[j] += dd;
int nbIdx = m_hashTable.getBoxIndexFromVoxelCoord(neighbori);
if (nbIdx != -1)
{
neighborIdxs.push_back(nbIdx);
}
}
}
m_boxShareFaceWithBox.push_back(neighborIdxs);
}
}
void voxelObject::drawVoxel(int mode)
{
m_octree.drawWireOctree(mode);
}
void voxelObject::drawVoxelLeaf(int mode)
{
for (int i = 0; i < m_boxes.size(); i++)
{
m_boxes[i].draw(mode);
}
}
// void voxelObject::decomposeConvexes()
// {
// // Construct voxel bit set
// // test by hard code first
// std::vector<Box> boxDecompose;
// boxDecompose.push_back(Box(Vec3f(-20, -20, -20), Vec3f(0, 20, 20)));
// boxDecompose.push_back(Box(Vec3f(0, -20, 0), Vec3f(20, 20, 20)));
// boxDecompose.push_back(Box(Vec3f(0, -20, -20), Vec3f(20, 20, 0)));
//
// // Check voxel inside these boxes.
// // Assign to decomposed box
// m_voxelBitSet.hashTable = &m_hashTable;
// m_voxelBitSet.m_leftDownf = m_octree.m_root->leftDownf;
// m_voxelBitSet.m_rightUpf = m_octree.m_root->rightUpf;
//
// GeometricFunc geoFunc;
// for (int i = 0; i < boxDecompose.size(); i++)
// {
// voxelBitConvex newCVBitset;
// for (int j = 0; j < m_boxes.size(); j++)
// {
// if (geoFunc.isPointInBox(boxDecompose[i].leftDown, boxDecompose[i].rightUp, m_boxes[j].center))
// {
// Vec3i coordi = m_boxes[j].xyzIndex;
// newCVBitset.setValue1(coordi);
// }
// }
// newCVBitset.leftDowni = m_hashTable.leftDowni();
// newCVBitset.rightUpi = m_hashTable.rightUpi();
// newCVBitset.tightBoundingBox(&m_hashTable);
//
// m_voxelBitSet.groupVoxels.push_back(newCVBitset);
// }
//
// m_voxelBitSet.computeBoundingBox();
// }
//
// void voxelObject::drawBitSet(voxelSplitObj* vBitSet)
// {
// vBitSet->drawVoxelBox();
// }
//
// void voxelObject::drawVoxelBitDecomposed()
// {
// voxelBitConvex_array *bitSetA = m_voxelBitSet.getBitSetArray();
//
// static arrayVec3f colors = Util_w::randColor(bitSetA->size()+1);
//
// for (int i = 0; i < bitSetA->size(); i++)
// {
// glColor3fv(colors[i+1].data());
// bitSetA->at(i).drawBoxWire(&m_hashTable);
//
// glColor3fv(colors[i].data());
// bitSetA->at(i).drawBoxSolid(&m_hashTable);
// }
// }
//
// void voxelObject::drawBitSetBoundingBox()
// {
// voxelBitConvex_array *bitSetA = m_voxelBitSet.getBitSetArray();
//
// static arrayVec3f colors = Util_w::randColor(bitSetA->size() + 1);
//
// for (int i = 0; i < bitSetA->size(); i++)
// {
// glColor3fv(colors[i].data());
// bitSetA->at(i).drawBoudingBox(&m_hashTable);
// }
// }
// void voxelObject::constructBitSetMesh()
// {
// using namespace energy;
//
// meshBitSet = bitSetObjectPtr(new bitSetObject(m_hashTable.NumXYZ));
// for (auto b : m_boxes)
// {
// Vec3i posi = b.xyzIndex;
// meshBitSet->setAtPos(posi);
// }
// }
float voxelObject::volumef() const
{
return m_boxes.size() * std::pow(m_voxelSizef, 3);
}
// void voxelObject::updateSphereOccupy(energyMngerPtr curEnergyObj)
// {
// std::vector<skeSpherePtr> sArray = curEnergyObj->sphereArray();
//
// arrayInt voxeHash = m_hashTable.voxelHash;
// // Clear voxel state
// for (auto b:m_boxes)
// {
// b.state = 0;
// }
//
// for (auto s:sArray)
// {
//
// }
// }
void voxelObject::drawVoxelIndex()
{
for (int i = 0; i < m_boxes.size(); i++)
{
Vec3f c = m_boxes[i].center;
Util::printw(c[0], c[1], c[2], "%d", i);
}
}
|
#include "stdafx.h"
#include <stdint.h>
// From http://stackoverflow.com/questions/17432502/how-can-i-measure-cpu-time-and-wall-clock-time-on-both-linux-windows
// Only works in Windows
#include <Windows.h>
double get_wall_time() {
LARGE_INTEGER time, freq;
if (!QueryPerformanceFrequency(&freq)) {
// Handle error
return 0;
}
if (!QueryPerformanceCounter(&time)) {
// Handle error
return 0;
}
return (double)time.QuadPart / freq.QuadPart;
}
double get_cpu_time() {
FILETIME a, b, c, d;
if (GetProcessTimes(GetCurrentProcess(), &a, &b, &c, &d) != 0) {
// Returns total user time.
// Can be tweaked to include kernel times as well.
return
(double)(d.dwLowDateTime |
((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
}
else {
// Handle error
return 0;
}
}
int32_t* arrayInsert(int32_t *a, int32_t l, int32_t r, int32_t e) {
int32_t *newA = new int32_t[l + 1];
for (int32_t k = 0; k < r; k++) {
newA[k] = a[k];
}
for (int32_t k = r; k < l; k++) {
newA[k + 1] = a[k];
}
delete[] a;
newA[r] = e;
return newA;
}
int32_t* arrayRemove(int32_t *a, int32_t l, int32_t r) {
int32_t *newA = new int32_t[l - 1];
for (int32_t k = 0; k < r; k++) {
newA[k] = a[k];
}
for (int32_t k = r; k < l - 1; k++) {
newA[k] = a[k + 1];
}
delete[] a;
return newA;
}
|
#ifndef CONTROLLER_H_
#define CONTROLLER_H_
#include "bno055.h"
#include "motor_driver.h"
extern "C"
{
#include "ch.h"
}
class Controller
{
public:
Controller();
~Controller();
void Update();
void SetOrientation(vector3 setpoint);
void SetThrottle(double throttle);
private:
void velocityLoopUpdate(vector3 setpoint);
double m_throttle;
MotorDriver *md1;
MotorDriver *md2;
MotorDriver *md3;
MotorDriver *md4;
};
#endif /* CONTROLLER_H_ */
|
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
int t[4],in[4],ma[4],n,a,b,tb[4],inb[4];
//while (cin >> t[0] >> t[1] >> t[2] >> t[3]){
while (scanf("%d %d %d %d",&t[0],&t[1],&t[2],&t[3])==4){ //改成scanf printf比較快
//cin >>n;
scanf("%d",&n);
for(int i=0;i<n;i++){
a=b=0;
for(int j=0;j<4;j++){
tb[j]=0;//用於B的輸出,目標值該位置是否比較過,tb[i]=1,表示已經用過
inb[j]=0;//用於B的輸出,輸入值該位置是否比較過,inb[i]=1,表示已經用過
//cin >> in[j];
scanf("%d",&in[j]);
if (t[j]==in[j]) {
ma[j]=1;
a++;
}else{
ma[j]=0;
}
}
for(int j=0;j<4;j++){
for(int k=0;k<4;k++){
if ((j!=k)&&(!ma[j])&&(!ma[k])&&(!tb[j])&&(!inb[k])){//沒有用過的A與B位置,可以比較產生B
if (t[j]==in[k]) {
b++;
tb[j]=1;
inb[k]=1;
break;
}
}
}
}
printf("%dA%dB\n",a,b);
}
}
return 0;
}
|
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <map>
#include <string>
using namespace std;
/*
template <typename T, typename U>
class create_map
{
private:
std::map<T, U> m_map;
public:
create_map(const T& key, const U& val)
{
m_map[key] = val;
}
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return *this;
}
operator std::map<T, U>()
{
return m_map;
}
};*/
class CPeptideTools {
public:
CPeptideTools();
static map<char,double> mapMonoisotopic;
static double dHydroneMass;
static double massQuantity(const string source)
{
double dmassQuantify=0.0;
for (int i = 0;i<source.length();i++)
{
dmassQuantify+=mapMonoisotopic[source.at(i)];
}
return dmassQuantify;
}
//Ëã·¨,calculate edit distance
static int ldistance(const string source,const string target)
{
//step 1
int n=source.length();
int m=target.length();
if (m==0) return n;
if (n==0) return m;
//Construct a matrix
typedef vector< vector<int> > Tmatrix;
Tmatrix matrix(n+1);
for(int i=0; i<=n; i++) matrix[i].resize(m+1);
//step 2 Initialize
for(int i=1;i<=n;i++) matrix[i][0]=i;
for(int i=1;i<=m;i++) matrix[0][i]=i;
//step 3
for(int i=1;i<=n;i++)
{
const char si=source[i-1];
//step 4
for(int j=1;j<=m;j++)
{
const char dj=target[j-1];
//step 5
int cost;
if(si==dj){
cost=0;
}
else{
cost=1;
}
//step 6
const int above=matrix[i-1][j]+1;
const int left=matrix[i][j-1]+1;
const int diag=matrix[i-1][j-1]+cost;
matrix[i][j]=min(above,min(left,diag));
}
}//step7
return matrix[n][m];
}
static void getnextval(const char* T,int next[])
{
int j=0,k=-1;
next[0]=-1;
while(T[j]!='\0')
{
if(k==-1||T[j]==T[k])
{
j++; k++;
if(T[j]!=T[k]) next[j]=k;
else next[j]=next[k];
}
else k=next[k];
}
}
//ÉèÔÚ×Ö·û´®SÖвéÕÒģʽ´®T,ÈôS[m]!=T[n],È¡T[n]ģʽº¯ÊýÖµnext[n],
//Èç¹ûnext[n]=-1,±íʾS[m]ºÍT[0]¼ä½Ó±È½Ï¹ýÁË,²»ÏàµÈ,ÏÂÒ»´Î±È½Ï S[m+1] ºÍT[0]
//Èç¹ûnext[n]=0 ±íʾ±È½Ï¹ý³ÌÖвúÉúÁ˲»ÏàµÈ£¬ÏÂÒ»´Î±È½Ï S[m] ºÍT[0]
//Èç¹ûnext[n]= k >0 µ«k<n, ±íʾ,S[m]µÄǰk¸ö×Ö·ûÓëTÖеĿªÊ¼k¸ö×Ö·ûÒѾ¼ä½Ó±È½ÏÏàµÈÁË£¬ÏÂÒ»´Î±È½ÏS[m]ºÍT[k]ÏàµÈÂð£¿
//////////////////////////////////////////////////////////////////////////
//parameterÔʼ´®£¬Ä£Ê½´®
static int KMP(char *Text,const char *Pattern)
{
if(!Text||!Pattern||Text=='\0'||Pattern=='\0') return -1;
int len=strlen(Pattern);
int *next=new int[len+1];
getnextval(Pattern,next);
int i=0,j=0,index=0;
while(Text[i]!='\0'&&Pattern[j]!='\0')
{
if(Text[i]==Pattern[j])
{
i++; j++;
}
else
{
index+=j-next[j];
if(next[j]!=-1) j=next[j];
else
{
i++; j=0;
}
}
}
if(Pattern[j]=='\0') return index;
return -1;
}
//////////////////////////////////////////////////////////////////////////
//the efficience is better than kmp
static int SUNDAYFindSigle(char *text, char *patt){
size_t temp[256];
size_t *shift = temp;
size_t i, patt_size = strlen(patt), text_size = strlen(text);
// cout << "size : " << patt_size << endl;
for( i=0; i < 256; i++ ) *(shift+i) = patt_size+1;
for( i=0; i < patt_size; i++ )
*(shift + (unsigned char)(*(patt+i))) = patt_size-i;
//shift['s']=6?,shitf['e']=5 ????
size_t limit = text_size-patt_size+1;
for( i=0; i < limit; i += shift[ text[i+patt_size] ] )
if( text[i] == *patt ){
char *match_text = text+i+1;
size_t match_size = 1;
do{// Êä³öËùÓÐÆ¥ÅäµÄλÖÃ
if( match_size == patt_size ) return i;//cout << "the NO. is " << i << endl;
}while( (*match_text++) == patt[match_size++] );
}
return -1;//no find pattern string
// cout << endl;
}
//////////////////////////////////////////////////////////////////////////
//the efficience is better than kmp
static int SUNDAYFind(char *text, char *patt, int iLine,int iIsform,ofstream& out1,string& name){
size_t temp[256];
size_t *shift = temp;
size_t i, patt_size = strlen(patt), text_size = strlen(text);
// cout << "size : " << patt_size << endl;
for( i=0; i < 256; i++ ) *(shift+i) = patt_size+1;
for( i=0; i < patt_size; i++ )
*(shift + (unsigned char)(*(patt+i))) = patt_size-i;
//shift['s']=6?,shitf['e']=5 ????
size_t limit = text_size-patt_size+1;
for( i=0; i < limit; i += shift[ text[i+patt_size] ] )
if( text[i] == *patt ){
char *match_text = text+i+1;
size_t match_size = 1;
do{// Êä³öËùÓÐÆ¥ÅäµÄλÖÃ
// if( match_size == patt_size ) return i;//cout << "the NO. is " << i << endl;
if( match_size == patt_size ) out1 << iLine<<'\t'<< name<<'\t'<<iIsform<<'\t'<<text<<'\t'<<patt<<'\t'<<i<<endl;;
}while( (*match_text++) == patt[match_size++] );
}
return -1;//no find pattern string
// cout << endl;
}
/*int main(){
string s;
string d;
cout<<"source=";
cin>>s;
cout<<"diag=";
cin>>d;
int dist=ldistance(s,d);
cout<<"dist="<<dist<<endl;
}}*/
};
|
#include "Parser.h"
#include <fstream>
void Parser::readCommands(std::string& fileName, std::vector<ICommand*>& commands, std::vector<int>& executeOrder) {
std::ifstream fin(fileName);
if (!fin) throw std::string("Can't open file " + fileName + "!");
std::string buffer;
std::getline(fin, buffer);
if (buffer != "desc") throw std::string("Invalid input file beginning. \"desc\" is missing! ");
std::getline(fin, buffer);
while (buffer != "csed") {
std::string sIndex = buffer.substr(0, buffer.find(" = "));
std::string sCommand = buffer;
sCommand.erase(0, 3 + sCommand.find(" = "));
int index = std::atoi(sIndex.c_str());
if (commands.size() <= index) commands.resize(index + 1);
std::string key = sCommand.substr(0, sCommand.find(" "));
std::string parametrs = sCommand.erase(0, 1 + sCommand.find(" "));
//commands[index] = WorkerFactory::GetInstance().Create(key, parametrs);
commands[index] = CommandFactory::Instance().CreateCommand(key, parametrs);
std::getline(fin, buffer);
if (fin.eof()) throw std::string("Invalid input file beginning. \"csed\" is missing! ");
}
{
std::getline(fin, buffer);
int commandIndex;
while (buffer.find("->") != std::string::npos) {
commandIndex = atoi(buffer.c_str());
executeOrder.push_back(commandIndex);
buffer.erase(0, 2 + buffer.find("->"));
}
commandIndex = atoi(buffer.c_str());
executeOrder.push_back(commandIndex);
}
fin.close();
}
|
// fileread.cpp
// Kellan Cerveny and Jake Yoon
// Priebe 312
// 30 April 2020
#include <iostream>
#include <sys/types.h>
#include <fstream>
#include <cstdlib>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <queue>
#include "fileread.h"
using namespace std;
/* This is a collection of helper functions that:
* - Reads the input of all .txt files in a directory
* - Creates sequences of length N based on terminal command
* - Populates the hash table with entries from text sequences of each file
* - Calculates the number of collisions/coocurrences of phrases between files
* - Outputs the files with a high number of collisions in a table
*/
// Opens a directory path, makes and populates a vector containing all of the file names inside the dir
// Files 0 and 1 are . and .. respectively (current directory, parent directory)
int getdir (string dir, vector<string> &files)
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
files.push_back(string(dirp->d_name));
}
// need to remove . and ..
files.erase(files.begin(), files.begin() + 2);
closedir(dp);
return 0;
}
// hashes ALL consecutive sequences of length N from a given .txt file
// Adds hashes to hash table
// Input: directory where .txt files held, name of file to open, index of file to be stored, length of sequence to hash, hash table by reference
void hashFile(string directory,string fileName, unsigned int fileIndex, int seqLen, Hash_Table &hash_table){
ifstream file;
string toOpen = directory; // Need to loop through all the file names in "files" variable
toOpen.append(fileName);
file.open(toOpen);
if (!file.is_open()){
cout << "Unable to open file: " << toOpen << endl;
return; // Default return current and parent directory
}
string word; // receives words from file one at a time
queue<string> strQ; // Holds queue of words taken from file
unsigned long int hashValue;
int index = 0; // Populate the queue with seqLen values (length of queue)
while (file >> word && index < seqLen){
strQ.push(word);
index ++;
}
//printQueue(strQ); // DEBUGGING TOOL
hashValue = hash_table.hash_function(strQ); // return hash value of string queue
//cout << "HashValue " << hashValue << " ";
hash_table.addNode(hashValue, fileIndex); // Makes a new node in hash table with hashValue, stores fileName
//cout << hast_table.at(hash_table.get_values(fileIndex)) << endl;
//Finish all other variations from the file
while (file >> word){
strQ.pop(); // Get rid of string at the front of the queue
strQ.push(word); // Add next read-in string to back
hashValue = hash_table.hash_function(strQ); // return hash value of string queue
hash_table.addNode(hashValue, fileIndex); // Makes a new node in hash table with hashValue, stores fileName
}
}
//Function: hashes all N-length sequences of words from all text files in the given directory
//Input: directory files are stored in, vector of all file names, length of sequence we are searching for, hash table we deposit the results in
void hashFiles(string dir, vector<string> files, int seqLen, Hash_Table& hash_table){
string direct = dir;
//direct.append("\\"); // Append directory delimiter (escaped) for fopen() later
//cout << direct << endl;
//cout << files.size() << endl;
// Hash sequences of length N in all files in dir
for (unsigned int i = 0;i < files.size();i++) {
//cout << i << ": " << files[i] << endl; // DEBUGGING: Outputs file name and index
hashFile(direct, files[i], i, seqLen, hash_table);
}
}
// Function: DEBUGGING TOOL, shows matrix collisions
// Input: matrix with frequencies of collisions between files
void printCollisions(vector<vector<int>> collMatrix){
cout << " ";
for (int i = 0; i < collMatrix.size(); ++i) {
cout << i << " ";
}
cout << endl;
for (int j = 0; j < collMatrix.size(); ++j) {
cout << "__";
}
cout << endl;
for (int k = 0; k < collMatrix.size(); ++k) {
cout << k << "| ";
for (int i = 0; i < collMatrix.size(); ++i) {
cout << collMatrix[k][i] << " ";
}
cout << endl;
}
}
// Function: iterates through hash table, adds file collisions to matrix
// Input: hash table holding collisions, size of NxN matrix to show file overlap,NxN matrix with number of collisions between files
// Output:
void populateMatrix(Hash_Table &hashTable, vector<vector<int>> &frequencies){
vector<int> collisions;
int row;
int col;
// Iterate through the hash table, plot frequencies of overlap
for (int i = 0; i < (42949672); ++i) {
// When hash table is not empty, add fileIndex values to matrix
if(!hashTable.get_values(i).empty()){
collisions = hashTable.get_values(i);
//For each file index, add collisions with following indices
for (int j = 0; j < collisions.size(); ++j) {
row = collisions[j];
for (int k = j; k < collisions.size(); ++k) {
col = collisions[k]; //column for collision
// DO WE NEED TO REMOVE REPEAT COLLISIONS WITH OTHER FILES?
if (collisions[j] != collisions[k]){
//cout << collisions[j] << " " << collisions[k] << endl;
frequencies[row][col] ++; //Add a collision between two files
}
}
}
}
}
// printCollisions(frequencies); // Displays file collisions in a matrix
}
// Function: Create an N*N matrix, populate with frequencies of colliding sequences between files
// Input: vector of files, hash table holding overlap occurrences,
void printFrequencies(const int occurrences, vector<vector<int>> collisionsMatrix, vector<string> files){
for (unsigned int i = 0; i < collisionsMatrix.size(); ++i) {
for (unsigned int j = i; j < collisionsMatrix.size(); ++j) {
if (collisionsMatrix[i][j] >= occurrences){
// Print: #, file1, file2
cout << collisionsMatrix[i][j] << ": ";
cout << files[i] << ", ";
cout << files[j] << endl;
}
}
}
}
// ******************************************
// Print Sorted Array Using MergeSort
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printSortedFrequencies(const int occurrences, vector<vector<int>> collisionsMatrix, vector<string> files){
int sortedArray[(collisionsMatrix.size()*collisionsMatrix.size())/2];
int size = 0;
for (unsigned int i = 0; i < collisionsMatrix.size(); ++i) {
for (unsigned int j = i; j < collisionsMatrix.size(); ++j) {
if (collisionsMatrix[i][j] >= occurrences){
sortedArray[size] = collisionsMatrix[i][j];
size++;
}
}
}
//MergeSort
size--;
mergeSort(sortedArray, 0, size);
cout << "Sorted Array" << endl;
while(size > 0){
for (int i = 0; i < collisionsMatrix.size(); ++i) {
for (int j = i; j < collisionsMatrix.size(); ++j) {
if (collisionsMatrix[i][j] == sortedArray[size] && sortedArray[size] > occurrences) {
cout << sortedArray[size];
cout << ": " << files[i] << ", " << files[j] << endl;
size--;
}
}
}
}
}
|
#ifndef ROBOT_H
#define ROBOT_H
#include <vector>
#include <iostream>
#include <random>
#include <time.h>
#include <math.h>
#include <map.h>
using namespace std;
typedef struct position{
float x;
float y;
float orientation;
}position;
typedef struct noise{
float forward_noise;
float turn_noise;
float sense_noise;
}noise;
typedef struct movement{
int dist;
float angle;
}movement;
class Robot
{
private:
Map *map;
public:
Robot(Map *myMap);
position robot_pose;
noise noises;
vector< vector<float> > Measurements;
vector<float> temp2;
void init_map();
void set_position(position n);
void set_noise(float foward, float turn, float sense);
void move(movement mv);
float measurement_prob(vector<float> measurements);
float gaussian(float dist, float sense_noise, float measurement);
void representation();
void show_measur(vector<float> measur);
float mod(float a, float b);
vector<float> sense();
};
#endif // ROBOT_H
|
#include<iostream>
using namespace std;
void insertionSort(int arr[],int len){
int val;
int hole;
for(int i=1;i<len;i++){
hole=i;
val=arr[hole];
while(hole>0 && arr[hole-1]>val){
arr[hole]=arr[hole-1];
hole--;
}
arr[hole]=val;
}
}
int main(){
int len;
cout<<"Enter your array length"<<endl;
cin>>len;
int array[len];
cout<<"Enter "<<len<<" elements now!"<<endl;
for(int i=0;i<len;i++){
cin>>array[i];
}
cout<<"Before Merging\n";
for(int i=0;i<len;i++){
cout<<array[i]<<"\t";
}
cout<<endl;
insertionSort(array,len);
cout<<"After Merging\n";
for(int i=0;i<len;i++){
cout<<array[i]<<"\t";
}
cout<<endl;
return 0;
}
|
#include "RBFDeform.h"
RBFDeform::RBFDeform()
{
centers = NULL;
fctValues = NULL;
rbf_coeff = NULL;
}
RBFDeform::RBFDeform(int numberCenters, int dimension, double * centers, double * functionValues, double standDev,
bool approximateRBF)
{
initialize(numberCenters, dimension, centers, functionValues, standDev);
approximation = approximateRBF;
}
RBFDeform::~RBFDeform()
{
if(centers != NULL)
{
delete [] centers;
centers = NULL;
}
if(fctValues != NULL)
{
delete [] fctValues;
fctValues = NULL;
}
if(rbf_coeff != NULL)
{
delete [] rbf_coeff;
rbf_coeff = NULL;
}
}
void RBFDeform::initialize(int numberCenters, int dimension, double * centers, double * functionValues, double standDev)
{
int i;
rbf_coeff = NULL;
this->numberCenters = numberCenters;
this->dimension = dimension;
srbfcoeff= numberCenters + 4;
this->standDev = standDev;
variance = standDev * standDev;
this->centers = new double [numberCenters * dimension];
for(i = 0; i < numberCenters * dimension; i++)
{
this->centers[i] = centers[i];
}
fctValues = new double [numberCenters * dimension];
for(i = 0; i < numberCenters * dimension; i++)
{
fctValues[i] = functionValues[i];
}
compute_RBFCoeff();
}
void RBFDeform::compute_RBFCoeff()
{
int i, j;
double *A = new double[srbfcoeff*srbfcoeff];
//initialize everything to 0:
for(i = 0; i < srbfcoeff*srbfcoeff; i++)
A[i] = 0.0;
rbf_coeff = new double[srbfcoeff * dimension];
for(i = 0; i < srbfcoeff * dimension; i++)
rbf_coeff[i] = 0.0;
//set values for computation:
for ( i = 0 ; i < numberCenters; i++ )
{
for ( j = 0; j < numberCenters; j++ )
A[j * srbfcoeff + i] = RBFunction(i, j);
for ( j = 0 ; j < dimension; j ++ )
{
// Added if rigid tranformation + RBF
A[(j + numberCenters + 1) * srbfcoeff + i] = centers[i * dimension + j];
A[i * srbfcoeff + (j + numberCenters + 1)] = centers[i * dimension + j];
rbf_coeff[j * srbfcoeff + i] = fctValues[i * dimension + j];
}
// Added if rigid tranformation + RBF
A[numberCenters * srbfcoeff + i] = 1;
A[i * srbfcoeff + numberCenters] = 1;
}
//Only use this for approximate RBF
if(approximation)
{
//make it an approximate RBF by setting rho: maybe use cross-validation later
//use mean distance for now: like Jain, Zhang and van Kaick:
double rho = 0;
double squaredDist = 0;
for (i = 0; i < numberCenters; i++ )
{
squaredDist = 0;
for(j = 0; j < dimension; j++)
squaredDist += pow((centers[i * dimension + j]-fctValues[i * dimension + j]), 2);
rho += sqrt(squaredDist);
}
rho = rho / numberCenters;
for ( i = 0 ; i < numberCenters; i++ )A[i * srbfcoeff + i]+=rho;
}
long int info;
char uplo = 'U';
long int * ipiv = new long int[srbfcoeff];
long int n = (long int) srbfcoeff;
long int m = (long int) dimension;
char fact = 'E';
char trans = 'N';
char equed;
double * af = new double[srbfcoeff*srbfcoeff];
double * r = new double[srbfcoeff];
double * c = new double[srbfcoeff];
double * x = new double[srbfcoeff * dimension];
double rcond;
double * ferr = new double[dimension];
double * berr = new double[dimension];
double * work = new double [4*srbfcoeff];
long int * iwork = new long int[srbfcoeff];
clapack::dgesvx_(&fact, &trans, &n, &m, A, &n, af, &n, ipiv, &equed, r, c, rbf_coeff, &n, x, &n, &rcond, ferr, berr, work,
iwork, &info);
//copy x to rbf_coeff:
for(i = 0; i < srbfcoeff * dimension; i++)
rbf_coeff[i] = x[i];
//delete stuff:
delete [] af;
delete [] r;
delete [] c;
delete [] x;
delete [] ferr;
delete [] berr;
delete [] work;
delete [] iwork;
delete [] A;
delete [] ipiv;
}
inline double RBFDeform::RBFunction( unsigned int id1, unsigned int id2)
{
double squaredDist = 0;
for(int i = 0; i < dimension; i++)
squaredDist += pow((centers[id1 * dimension + i]-centers[id2 * dimension + i]), 2);
//Thin plate spline:
if(squaredDist < RBF_EPSILON) return 0;
else return squaredDist * log(sqrt(squaredDist));
//Gauss:
//return exp( - squaredDist / (2*variance)) / (standDev * sqrt(2.0 * RBF_PI));
}
inline double RBFDeform::RBFunction(unsigned int id1, double * pointToEvaluate)
{
double squaredDist = 0;
for(int i = 0; i < dimension; i++)
squaredDist += pow((pointToEvaluate[i]-centers[id1 * dimension + i]), 2);
//Thin plate spline:
if(squaredDist < RBF_EPSILON) return 0;
else return squaredDist * log(sqrt(squaredDist));
//Gauss:
//return exp( - squaredDist / (2*variance)) / (standDev * sqrt(2.0 * RBF_PI));
}
void RBFDeform::evaluate(double * point, double * result)
{
int i, j;
double rbfunction;
//initialize the result to 0:
for(i = 0; i < dimension; i++) result[i] = 0;
//evaluate the function using previously computed rbf_coeff
for(j = 0; j < numberCenters; j++)
{
rbfunction = RBFunction(j, point);
for(i = 0; i < dimension; i++)
{
result[i] += rbf_coeff[i * srbfcoeff + j] * rbfunction;
}
}
for(i = 0; i < dimension; i++)
{
result[i] += rbf_coeff[i * srbfcoeff + numberCenters];
for(j = 0; j < dimension; j++)
result[i] += rbf_coeff[i * srbfcoeff + (numberCenters + j + 1)] * point[j];
}
}
|
#include <windows.h>
#include <windowsx.h>
#include <iostream>
#include <tchar.h>
#include <xstring>
#include <process.h>
#include <stdio.h>
#include <thread>
/////////////////////////////////////////////////// COLOR ///////////////////////////////////////////////////
#define BLACK 0x00,0x00,0x00
#define WHITE 0xFF,0xFF,0xFF
#define BLUE 0x00,0x00,0xFF
#define YELLOW 0xFF,0xFF,0x00
#define GREEN 0x00,0xFF,0x00
#define MAGENTA 0xFF,0x00,0xFF
#define RED 0xFF,0x00,0x00
#define CYAN 0x00,0xFF,0xFF
#define GREY 0x80,0x80,0x80
#define GRAY 0x80,0x80,0x80
#define LIGHT_GREY 0xC0,0xC0,0xC0
#define LIGHT_GRAY 0xC0,0xC0,0xC0
#define PALE_GREY 0xE0,0xE0,0xE0
#define PALE_GRAY 0xE0,0xE0,0xE0
#define DARK_GREY 0x40,0x40,0x40
#define DARK_GRAY 0x40,0x40,0x40
#define DARK_BLUE 0x00,0x00,0x80
#define DARK_GREEN 0x00,0x80,0x00
#define DARK_RED 0x80,0x00,0x00
#define LIGHT_BLUE 0x80,0xC0,0xFF
#define LIGHT_GREEN 0x80,0xFF,0x80
#define LIGHT_RED 0xFF,0xC0,0xFF
#define PINK 0xFF,0xAF,0xAF
#define BROWN 0x60,0x30,0x00
#define ORANGE 0xFF,0x80,0x00
#define PURPLE 0xC0,0x00,0xFF
#define LIME 0x80,0xFF,0x00
/////////////////////////////////////////////////// COLOR ///////////////////////////////////////////////////
enum ERWIFlagsShot
{
eAmmoFlags = 0x31F,
eAmmoWallShot = 0x10,
eAmmoWallShotF = 0x75,
eAmmoWallShotE = 0x7E
};
enum EIDWeapons
{
Rifle = 1818650994,
Pistol = 1953720688,
Knife = 1718185579,
Grenade = 1852142183,
AmmoBox = 1869442401,
MedicineChest = 1801741677,
Defibrillator = 26212,
ArmorPlate = 1634755954,
Mine = 30574
};
enum EClassId
{
Sturm = 0,
Medic = 3,
Engineer = 4,
Sniper = 2
};
bool Fast2_Enabled = false;
bool WallShoot_Enabled = false;
Vec3 TargetPos = ZERO;
f32 PriorityLimit = 10000.0f;
BOOL IsMyTeam(INT mTeam, INT pTeam) { return !(mTeam != pTeam || pTeam == 0); }
BOOL IsMyTeam(INT mTeam, IActor * pActor) { return !(mTeam != pActor->TeamId || pActor->TeamId == 0); }
bool IsMyTeam(IActor * mActor, IActor * pActor) { return !(mActor->TeamId != pActor->TeamId || pActor->TeamId == 0); }
Vec3 GetMPos(Vec3 vBonePos, Vec3 CamPos, FLOAT popravka)
{
Vec3 vOut = vBonePos - CamPos;
FLOAT sqr = (FLOAT)_sqrt(vOut.x * vOut.x + vOut.y * vOut.y + vOut.z * vOut.z);
vOut /= sqr;
vOut *= sqr - popravka;
return vOut;
}
int get_bone_object(ISkeletonPose* m_pSkeleton, const char* Name, const char* ClassName) {
if (_strstr(ClassName, "SED")) return 58;
if (_strstr(Name, "HeavyTurret")) return 52;
if (!_strcmp(ClassName, "Turret")) return m_pSkeleton->GetJointIdByNameing("bone_head");
if (_strstr(Name, "Cyborg") || _strstr(Name, "Destroyer")) return 3;
return m_pSkeleton->GetJointIdByNameing("Bip01 Head");
}
void SetVisionParams(EntityId uiEntityId, float r, float g, float b, float a)
{
IEntity* BadEntity = gGlobal->pEntitySystem->GetEntity(uiEntityId);
if (!BadEntity) return;
IEntityRenderProxy* pEntityRenderProxy = (IEntityRenderProxy*)(BadEntity->GetProxy(ENTITY_PROXY_RENDER));
if (!pEntityRenderProxy) return;
pEntityRenderProxy->SetHUDSilhouettesParams(r, g, b, a);
*(DWORD*)((DWORD)pEntityRenderProxy + 0x14) |= 0x10;
}
void SetVisionParams2(EntityId uiEntityId, float r, float g, float b, float a, int iType = 0, int CheckDistance = 0, float MinDistance = 0.0f)
{
((void(__stdcall*)(EntityId, float, float, float, float, int, int, float))0x11F6FE0)(uiEntityId, r, g, b, a, iType, CheckDistance, MinDistance);
}
Vec3 vGetBone(Matrix34 m_pWorld, ISkeletonPose* m_pSkeleton, const char* szJointName)
{
if (!m_pSkeleton)
return Vec3{ ZERO };
__int16 BoneId = m_pSkeleton->GetJointIdByNameing(szJointName);
Matrix34 mOut = m_pWorld * Matrix34(m_pSkeleton->GetAbsJointByID(BoneId));
return mOut.GetTranslation();
}
bool is_Visible(Vec3 vBonePos, FLOAT popravka)
{
ray_hit tmpHit;
Vec3 CamPos = gRen->vPos;
Vec3 vOut(GetMPos(vBonePos, CamPos, popravka));
return !gGlobal->MyPhysicalWorld->RayWorldIntersection1337(CamPos, vOut, 0x100 | 1, 0xA | 0x400, &tmpHit, 1);
}
void ClimbExtraHeight(f32 Value)
{
DWORD v0 = *(DWORD*)(*(DWORD*)(*(DWORD*)((DWORD)gGlobal->pGame + 0x144) + 0x4) + 0x4);
if (!v0) return;
*(f32*)(v0 + 0x14) = 2.250f + Value;
}
const auto myTask = []()
{
Sleep(500);
};
//
//
void GameFunction(IDirect3DDevice9* m_pDevice)
{
IActor* MeActor = nullptr;
IGameFramework* meFramework = gGlobal->pGame->GetIGameFramework();
if (!meFramework || !meFramework->GetClientActor(&MeActor) || MeActor->IsDead()) return;
//
IItem* MyItem = MeActor->GetCurrentItem();
if (!MyItem) return;
MyItem->GetIWeapon()->ResetFiringPos();
Fast2_Enabled = false;
WallShoot_Enabled = false;
TargetPos = ZERO;
PriorityLimit = 5000.0f;
//
//
SCVars2->g_chat_enabled_ingame = 1;
SCVars2->g_kickvote_pve_max_checkpoints = 999;
//
SCVars2->g_gameroom_afk_timeout = 60 * 60 * 2;
SCVars2->g_ingame_afk_timeout = 60 * 60 * 2;
//
SCVars2->cl_fov = 95.0f;
//
MeActor->claymore_detector_radius = 10000.0f;
MeActor->slideDistanceMult = 1.5f;
//
//Env->pGame->GetIWeaponSystem()->m_pItemSystem->GetItemParams("mg23_sp_d");
//
if (/*!(m_pActor->WeaponId == EIDWeapons::Rifle || m_pActor->WeaponId == EIDWeapons::Pistol) || */_strstr(MyItem->GetEntity()->GetName(), "arl")) return;
//
IEntityIt* pEntityIt = gGlobal->pEntitySystem->GetEntityIterator();
while (IEntity * pExp = pEntityIt->Next())
{
////////////////////////////////////// TRIGGER BOT //////////////////////////////////////
if (MeActor->ClassId == 3 || MeActor->ClassId == 2)
{
int TriggerId = NULL;
if (auto mWeapon = MeActor->GetCurrentItem()->GetIWeapon())
{
auto mTriggerId = MeActor->IsTriggerID();
if (mTriggerId && GetAsyncKeyState(VK_RBUTTON))
{
if (IActor * pActor = meFramework->GetIActorSystem()->GetActor(mTriggerId))
{
if (IsMyTeam(MeActor, pActor))
{
continue;
}
//std::thread(myTask).detach();
MyItem->GetIWeapon()->StartFire();
MyItem->GetIWeapon()->StopFire();
}
}
}
else
{
continue;
}
}
////////////////////////////////////// TRIGGER BOT //////////////////////////////////////
IEntityClass* pEntClass = pExp->GetClass();
if (!pEntClass) continue;
const char* ClassName = pEntClass->GetName();
const char* Name = pExp->GetName();
if (!_strcmp(ClassName, "Dummy")) continue;
IEntityRenderProxy * pRenderProxy = pExp->GetRenderProxy();
if (!pRenderProxy) continue;
uint32 RenderFlags = pRenderProxy->GetFlags();
if (IActor * pActor = meFramework->GetIActorSystem()->GetActor(pExp->GetId()))
{
AABB aabb;
pExp->GetWorldBounds(aabb);
Vec3 vBonePos = aabb.GetCenter();
if (pActor->IsDead() || pActor == MeActor || pActor->IsDead() || IsMyTeam(MeActor, pActor)) continue;
if (is_Visible(vBonePos, 0.0f))
pRenderProxy->SetHUDSilhouettesParams(RED); // green_light
else
pRenderProxy->SetHUDSilhouettesParams(WHITE); // black
}
}
}
|
// ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2018.2
// Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved.
//
// ===========================================================
#include "Random.h"
#include "AESL_pkg.h"
using namespace std;
namespace ap_rtl {
const sc_logic Random::ap_const_logic_1 = sc_dt::Log_1;
const sc_logic Random::ap_const_logic_0 = sc_dt::Log_0;
const sc_lv<3> Random::ap_ST_fsm_state1 = "1";
const sc_lv<3> Random::ap_ST_fsm_pp0_stage0 = "10";
const sc_lv<3> Random::ap_ST_fsm_state4 = "100";
const sc_lv<32> Random::ap_const_lv32_0 = "00000000000000000000000000000000";
const bool Random::ap_const_boolean_1 = true;
const sc_lv<1> Random::ap_const_lv1_0 = "0";
const sc_lv<1> Random::ap_const_lv1_1 = "1";
const sc_lv<2> Random::ap_const_lv2_0 = "00";
const sc_lv<2> Random::ap_const_lv2_2 = "10";
const sc_lv<2> Random::ap_const_lv2_3 = "11";
const sc_lv<2> Random::ap_const_lv2_1 = "1";
const sc_lv<32> Random::ap_const_lv32_1 = "1";
const bool Random::ap_const_boolean_0 = false;
const int Random::C_S_AXI_DATA_WIDTH = "100000";
const sc_lv<23> Random::ap_const_lv23_0 = "00000000000000000000000";
const sc_lv<32> Random::ap_const_lv32_2 = "10";
const sc_lv<23> Random::ap_const_lv23_7FBC00 = "11111111011110000000000";
const sc_lv<23> Random::ap_const_lv23_1 = "1";
const sc_lv<32> Random::ap_const_lv32_37 = "110111";
const sc_lv<31> Random::ap_const_lv31_0 = "0000000000000000000000000000000";
const sc_lv<32> Random::ap_const_lv32_20 = "100000";
const sc_lv<32> Random::ap_const_lv32_36 = "110110";
Random::Random(sc_module_name name) : sc_module(name), mVcdFile(0) {
Random_CONTROL_BUS_s_axi_U = new Random_CONTROL_BUS_s_axi<C_S_AXI_CONTROL_BUS_ADDR_WIDTH,C_S_AXI_CONTROL_BUS_DATA_WIDTH>("Random_CONTROL_BUS_s_axi_U");
Random_CONTROL_BUS_s_axi_U->AWVALID(s_axi_CONTROL_BUS_AWVALID);
Random_CONTROL_BUS_s_axi_U->AWREADY(s_axi_CONTROL_BUS_AWREADY);
Random_CONTROL_BUS_s_axi_U->AWADDR(s_axi_CONTROL_BUS_AWADDR);
Random_CONTROL_BUS_s_axi_U->WVALID(s_axi_CONTROL_BUS_WVALID);
Random_CONTROL_BUS_s_axi_U->WREADY(s_axi_CONTROL_BUS_WREADY);
Random_CONTROL_BUS_s_axi_U->WDATA(s_axi_CONTROL_BUS_WDATA);
Random_CONTROL_BUS_s_axi_U->WSTRB(s_axi_CONTROL_BUS_WSTRB);
Random_CONTROL_BUS_s_axi_U->ARVALID(s_axi_CONTROL_BUS_ARVALID);
Random_CONTROL_BUS_s_axi_U->ARREADY(s_axi_CONTROL_BUS_ARREADY);
Random_CONTROL_BUS_s_axi_U->ARADDR(s_axi_CONTROL_BUS_ARADDR);
Random_CONTROL_BUS_s_axi_U->RVALID(s_axi_CONTROL_BUS_RVALID);
Random_CONTROL_BUS_s_axi_U->RREADY(s_axi_CONTROL_BUS_RREADY);
Random_CONTROL_BUS_s_axi_U->RDATA(s_axi_CONTROL_BUS_RDATA);
Random_CONTROL_BUS_s_axi_U->RRESP(s_axi_CONTROL_BUS_RRESP);
Random_CONTROL_BUS_s_axi_U->BVALID(s_axi_CONTROL_BUS_BVALID);
Random_CONTROL_BUS_s_axi_U->BREADY(s_axi_CONTROL_BUS_BREADY);
Random_CONTROL_BUS_s_axi_U->BRESP(s_axi_CONTROL_BUS_BRESP);
Random_CONTROL_BUS_s_axi_U->ACLK(ap_clk);
Random_CONTROL_BUS_s_axi_U->ARESET(ap_rst_n_inv);
Random_CONTROL_BUS_s_axi_U->ACLK_EN(ap_var_for_const0);
Random_CONTROL_BUS_s_axi_U->ap_start(ap_start);
Random_CONTROL_BUS_s_axi_U->interrupt(interrupt);
Random_CONTROL_BUS_s_axi_U->ap_ready(ap_ready);
Random_CONTROL_BUS_s_axi_U->ap_done(ap_done);
Random_CONTROL_BUS_s_axi_U->ap_idle(ap_idle);
Random_CONTROL_BUS_s_axi_U->agg_result_a(value_1_reg_232);
Random_CONTROL_BUS_s_axi_U->agg_result_a_ap_vld(agg_result_a_ap_vld);
Random_CONTROL_BUS_s_axi_U->agg_result_b(agg_result_b);
Random_CONTROL_BUS_s_axi_U->agg_result_b_ap_vld(agg_result_b_ap_vld);
Random_CONTROL_BUS_s_axi_U->agg_result_c(first_2_reg_243);
Random_CONTROL_BUS_s_axi_U->agg_result_c_ap_vld(agg_result_c_ap_vld);
Random_CONTROL_BUS_s_axi_U->agg_result_d(agg_result_d);
Random_CONTROL_BUS_s_axi_U->agg_result_d_ap_vld(agg_result_d_ap_vld);
Random_CONTROL_BUS_s_axi_U->agg_result_e(agg_result_e);
Random_CONTROL_BUS_s_axi_U->agg_result_e_ap_vld(agg_result_e_ap_vld);
Random_CONTROL_BUS_s_axi_U->agg_result_f(agg_result_f);
Random_CONTROL_BUS_s_axi_U->agg_result_f_ap_vld(agg_result_f_ap_vld);
Random_CONTROL_BUS_s_axi_U->last_V(last_V);
SC_METHOD(thread_ap_clk_no_reset_);
dont_initialize();
sensitive << ( ap_clk.pos() );
SC_METHOD(thread_INPUT_STREAM_TDATA_blk_n);
sensitive << ( INPUT_STREAM_V_data_V_0_state );
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( ap_block_pp0_stage0 );
sensitive << ( tmp_fu_268_p2 );
SC_METHOD(thread_INPUT_STREAM_TREADY);
sensitive << ( INPUT_STREAM_V_dest_V_0_state );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_ack_in);
sensitive << ( INPUT_STREAM_V_data_V_0_state );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_ack_out);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( tmp_fu_268_p2 );
sensitive << ( ap_block_pp0_stage0_11001 );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_data_out);
sensitive << ( INPUT_STREAM_V_data_V_0_payload_A );
sensitive << ( INPUT_STREAM_V_data_V_0_payload_B );
sensitive << ( INPUT_STREAM_V_data_V_0_sel );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_load_A);
sensitive << ( INPUT_STREAM_V_data_V_0_sel_wr );
sensitive << ( INPUT_STREAM_V_data_V_0_state_cmp_full );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_load_B);
sensitive << ( INPUT_STREAM_V_data_V_0_sel_wr );
sensitive << ( INPUT_STREAM_V_data_V_0_state_cmp_full );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_sel);
sensitive << ( INPUT_STREAM_V_data_V_0_sel_rd );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_state_cmp_full);
sensitive << ( INPUT_STREAM_V_data_V_0_state );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_vld_in);
sensitive << ( INPUT_STREAM_TVALID );
SC_METHOD(thread_INPUT_STREAM_V_data_V_0_vld_out);
sensitive << ( INPUT_STREAM_V_data_V_0_state );
SC_METHOD(thread_INPUT_STREAM_V_dest_V_0_ack_out);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( tmp_fu_268_p2 );
sensitive << ( ap_block_pp0_stage0_11001 );
SC_METHOD(thread_INPUT_STREAM_V_dest_V_0_vld_in);
sensitive << ( INPUT_STREAM_TVALID );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_ack_in);
sensitive << ( INPUT_STREAM_V_last_V_0_state );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_ack_out);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( tmp_fu_268_p2 );
sensitive << ( ap_block_pp0_stage0_11001 );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_data_out);
sensitive << ( INPUT_STREAM_V_last_V_0_payload_A );
sensitive << ( INPUT_STREAM_V_last_V_0_payload_B );
sensitive << ( INPUT_STREAM_V_last_V_0_sel );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_load_A);
sensitive << ( INPUT_STREAM_V_last_V_0_sel_wr );
sensitive << ( INPUT_STREAM_V_last_V_0_state_cmp_full );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_load_B);
sensitive << ( INPUT_STREAM_V_last_V_0_sel_wr );
sensitive << ( INPUT_STREAM_V_last_V_0_state_cmp_full );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_sel);
sensitive << ( INPUT_STREAM_V_last_V_0_sel_rd );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_state_cmp_full);
sensitive << ( INPUT_STREAM_V_last_V_0_state );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_vld_in);
sensitive << ( INPUT_STREAM_TVALID );
SC_METHOD(thread_INPUT_STREAM_V_last_V_0_vld_out);
sensitive << ( INPUT_STREAM_V_last_V_0_state );
SC_METHOD(thread_agg_result_a_ap_vld);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_b);
sensitive << ( in1Count_1_reg_254 );
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_b_ap_vld);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_c_ap_vld);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_d);
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( tmp_9_fu_366_p4 );
SC_METHOD(thread_agg_result_d_ap_vld);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_e);
sensitive << ( last_V_read_reg_391 );
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( tmp_10_fu_362_p1 );
SC_METHOD(thread_agg_result_e_ap_vld);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_f);
sensitive << ( temperature_V );
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_agg_result_f_ap_vld);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_ap_CS_fsm_pp0_stage0);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state1);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state4);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_block_pp0_stage0);
SC_METHOD(thread_ap_block_pp0_stage0_11001);
sensitive << ( INPUT_STREAM_V_data_V_0_vld_out );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( tmp_fu_268_p2 );
SC_METHOD(thread_ap_block_pp0_stage0_subdone);
sensitive << ( INPUT_STREAM_V_data_V_0_vld_out );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( tmp_fu_268_p2 );
SC_METHOD(thread_ap_block_state2_pp0_stage0_iter0);
sensitive << ( INPUT_STREAM_V_data_V_0_vld_out );
sensitive << ( tmp_fu_268_p2 );
SC_METHOD(thread_ap_block_state3_pp0_stage0_iter1);
SC_METHOD(thread_ap_condition_542);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_block_pp0_stage0_11001 );
sensitive << ( ap_enable_reg_pp0_iter1 );
SC_METHOD(thread_ap_done);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_ap_enable_pp0);
sensitive << ( ap_idle_pp0 );
SC_METHOD(thread_ap_idle);
sensitive << ( ap_start );
sensitive << ( ap_CS_fsm_state1 );
SC_METHOD(thread_ap_idle_pp0);
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( ap_enable_reg_pp0_iter1 );
SC_METHOD(thread_ap_phi_mux_i_phi_fu_190_p4);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_block_pp0_stage0 );
sensitive << ( i_reg_186 );
sensitive << ( tmp_reg_406 );
sensitive << ( in1Count_reg_410 );
sensitive << ( tmp_last_V_reg_422 );
sensitive << ( ap_enable_reg_pp0_iter1 );
SC_METHOD(thread_ap_phi_mux_p_0_phi_fu_179_p4);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_block_pp0_stage0 );
sensitive << ( p_0_reg_176 );
sensitive << ( tmp_reg_406 );
sensitive << ( tmp_last_V_reg_422 );
sensitive << ( sum_V_reg_426 );
sensitive << ( ap_enable_reg_pp0_iter1 );
SC_METHOD(thread_ap_predicate_tran3to4_state2);
sensitive << ( INPUT_STREAM_V_last_V_0_data_out );
sensitive << ( tmp_fu_268_p2 );
SC_METHOD(thread_ap_ready);
sensitive << ( ap_CS_fsm_state4 );
SC_METHOD(thread_ap_rst_n_inv);
sensitive << ( ap_rst_n );
SC_METHOD(thread_in1Count_fu_274_p2);
sensitive << ( ap_phi_mux_i_phi_fu_190_p4 );
SC_METHOD(thread_lhs_V_cast_fu_298_p1);
sensitive << ( sum_V_reg_426 );
SC_METHOD(thread_r_V_2_fu_349_p3);
sensitive << ( tmp_2_fu_311_p3 );
sensitive << ( tmp_8_fu_335_p2 );
sensitive << ( tmp_7_fu_341_p3 );
SC_METHOD(thread_r_V_fu_305_p2);
sensitive << ( rhs_V_cast_fu_301_p1 );
sensitive << ( lhs_V_cast_fu_298_p1 );
SC_METHOD(thread_rhs_V_cast_fu_301_p1);
sensitive << ( i_op_assign_reg_198 );
SC_METHOD(thread_sum_V_cast_fu_264_p1);
sensitive << ( temperature_V );
SC_METHOD(thread_sum_V_fu_292_p2);
sensitive << ( ap_phi_mux_p_0_phi_fu_179_p4 );
sensitive << ( tmp_2_cast_fu_288_p1 );
SC_METHOD(thread_tmp_10_fu_362_p1);
sensitive << ( lhs_V_reg_222 );
SC_METHOD(thread_tmp_2_cast_fu_288_p1);
sensitive << ( INPUT_STREAM_V_data_V_0_data_out );
SC_METHOD(thread_tmp_2_fu_311_p3);
sensitive << ( r_V_fu_305_p2 );
SC_METHOD(thread_tmp_4_fu_319_p1);
sensitive << ( r_V_fu_305_p2 );
SC_METHOD(thread_tmp_5_fu_323_p1);
sensitive << ( r_V_fu_305_p2 );
SC_METHOD(thread_tmp_6_fu_327_p3);
sensitive << ( tmp_5_fu_323_p1 );
SC_METHOD(thread_tmp_7_fu_341_p3);
sensitive << ( tmp_4_fu_319_p1 );
SC_METHOD(thread_tmp_8_fu_335_p2);
sensitive << ( tmp_6_fu_327_p3 );
SC_METHOD(thread_tmp_9_fu_366_p4);
sensitive << ( lhs_V_reg_222 );
SC_METHOD(thread_tmp_fu_268_p2);
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( ap_block_pp0_stage0_11001 );
sensitive << ( ap_phi_mux_i_phi_fu_190_p4 );
SC_METHOD(thread_ap_NS_fsm);
sensitive << ( ap_start );
sensitive << ( ap_CS_fsm );
sensitive << ( ap_CS_fsm_state1 );
sensitive << ( ap_CS_fsm_pp0_stage0 );
sensitive << ( ap_enable_reg_pp0_iter0 );
sensitive << ( ap_enable_reg_pp0_iter1 );
sensitive << ( ap_block_pp0_stage0_subdone );
SC_THREAD(thread_hdltv_gen);
sensitive << ( ap_clk.pos() );
SC_THREAD(thread_ap_var_for_const0);
ap_CS_fsm = "001";
INPUT_STREAM_V_data_V_0_sel_rd = SC_LOGIC_0;
INPUT_STREAM_V_data_V_0_sel_wr = SC_LOGIC_0;
INPUT_STREAM_V_data_V_0_state = "00";
INPUT_STREAM_V_last_V_0_sel_rd = SC_LOGIC_0;
INPUT_STREAM_V_last_V_0_sel_wr = SC_LOGIC_0;
INPUT_STREAM_V_last_V_0_state = "00";
INPUT_STREAM_V_dest_V_0_state = "00";
ap_enable_reg_pp0_iter0 = SC_LOGIC_0;
ap_enable_reg_pp0_iter1 = SC_LOGIC_0;
static int apTFileNum = 0;
stringstream apTFilenSS;
apTFilenSS << "Random_sc_trace_" << apTFileNum ++;
string apTFn = apTFilenSS.str();
mVcdFile = sc_create_vcd_trace_file(apTFn.c_str());
mVcdFile->set_time_unit(1, SC_PS);
if (1) {
#ifdef __HLS_TRACE_LEVEL_PORT__
sc_trace(mVcdFile, ap_clk, "(port)ap_clk");
sc_trace(mVcdFile, ap_rst_n, "(port)ap_rst_n");
sc_trace(mVcdFile, INPUT_STREAM_TDATA, "(port)INPUT_STREAM_TDATA");
sc_trace(mVcdFile, INPUT_STREAM_TVALID, "(port)INPUT_STREAM_TVALID");
sc_trace(mVcdFile, INPUT_STREAM_TREADY, "(port)INPUT_STREAM_TREADY");
sc_trace(mVcdFile, INPUT_STREAM_TKEEP, "(port)INPUT_STREAM_TKEEP");
sc_trace(mVcdFile, INPUT_STREAM_TSTRB, "(port)INPUT_STREAM_TSTRB");
sc_trace(mVcdFile, INPUT_STREAM_TUSER, "(port)INPUT_STREAM_TUSER");
sc_trace(mVcdFile, INPUT_STREAM_TLAST, "(port)INPUT_STREAM_TLAST");
sc_trace(mVcdFile, INPUT_STREAM_TID, "(port)INPUT_STREAM_TID");
sc_trace(mVcdFile, INPUT_STREAM_TDEST, "(port)INPUT_STREAM_TDEST");
sc_trace(mVcdFile, temperature_V, "(port)temperature_V");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_AWVALID, "(port)s_axi_CONTROL_BUS_AWVALID");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_AWREADY, "(port)s_axi_CONTROL_BUS_AWREADY");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_AWADDR, "(port)s_axi_CONTROL_BUS_AWADDR");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_WVALID, "(port)s_axi_CONTROL_BUS_WVALID");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_WREADY, "(port)s_axi_CONTROL_BUS_WREADY");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_WDATA, "(port)s_axi_CONTROL_BUS_WDATA");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_WSTRB, "(port)s_axi_CONTROL_BUS_WSTRB");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_ARVALID, "(port)s_axi_CONTROL_BUS_ARVALID");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_ARREADY, "(port)s_axi_CONTROL_BUS_ARREADY");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_ARADDR, "(port)s_axi_CONTROL_BUS_ARADDR");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_RVALID, "(port)s_axi_CONTROL_BUS_RVALID");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_RREADY, "(port)s_axi_CONTROL_BUS_RREADY");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_RDATA, "(port)s_axi_CONTROL_BUS_RDATA");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_RRESP, "(port)s_axi_CONTROL_BUS_RRESP");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_BVALID, "(port)s_axi_CONTROL_BUS_BVALID");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_BREADY, "(port)s_axi_CONTROL_BUS_BREADY");
sc_trace(mVcdFile, s_axi_CONTROL_BUS_BRESP, "(port)s_axi_CONTROL_BUS_BRESP");
sc_trace(mVcdFile, interrupt, "(port)interrupt");
#endif
#ifdef __HLS_TRACE_LEVEL_INT__
sc_trace(mVcdFile, ap_rst_n_inv, "ap_rst_n_inv");
sc_trace(mVcdFile, ap_start, "ap_start");
sc_trace(mVcdFile, ap_done, "ap_done");
sc_trace(mVcdFile, ap_idle, "ap_idle");
sc_trace(mVcdFile, ap_CS_fsm, "ap_CS_fsm");
sc_trace(mVcdFile, ap_CS_fsm_state1, "ap_CS_fsm_state1");
sc_trace(mVcdFile, ap_ready, "ap_ready");
sc_trace(mVcdFile, agg_result_a_ap_vld, "agg_result_a_ap_vld");
sc_trace(mVcdFile, agg_result_b, "agg_result_b");
sc_trace(mVcdFile, agg_result_b_ap_vld, "agg_result_b_ap_vld");
sc_trace(mVcdFile, agg_result_c_ap_vld, "agg_result_c_ap_vld");
sc_trace(mVcdFile, agg_result_d, "agg_result_d");
sc_trace(mVcdFile, agg_result_d_ap_vld, "agg_result_d_ap_vld");
sc_trace(mVcdFile, agg_result_e, "agg_result_e");
sc_trace(mVcdFile, agg_result_e_ap_vld, "agg_result_e_ap_vld");
sc_trace(mVcdFile, agg_result_f, "agg_result_f");
sc_trace(mVcdFile, agg_result_f_ap_vld, "agg_result_f_ap_vld");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_data_out, "INPUT_STREAM_V_data_V_0_data_out");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_vld_in, "INPUT_STREAM_V_data_V_0_vld_in");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_vld_out, "INPUT_STREAM_V_data_V_0_vld_out");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_ack_in, "INPUT_STREAM_V_data_V_0_ack_in");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_ack_out, "INPUT_STREAM_V_data_V_0_ack_out");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_payload_A, "INPUT_STREAM_V_data_V_0_payload_A");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_payload_B, "INPUT_STREAM_V_data_V_0_payload_B");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_sel_rd, "INPUT_STREAM_V_data_V_0_sel_rd");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_sel_wr, "INPUT_STREAM_V_data_V_0_sel_wr");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_sel, "INPUT_STREAM_V_data_V_0_sel");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_load_A, "INPUT_STREAM_V_data_V_0_load_A");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_load_B, "INPUT_STREAM_V_data_V_0_load_B");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_state, "INPUT_STREAM_V_data_V_0_state");
sc_trace(mVcdFile, INPUT_STREAM_V_data_V_0_state_cmp_full, "INPUT_STREAM_V_data_V_0_state_cmp_full");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_data_out, "INPUT_STREAM_V_last_V_0_data_out");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_vld_in, "INPUT_STREAM_V_last_V_0_vld_in");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_vld_out, "INPUT_STREAM_V_last_V_0_vld_out");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_ack_in, "INPUT_STREAM_V_last_V_0_ack_in");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_ack_out, "INPUT_STREAM_V_last_V_0_ack_out");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_payload_A, "INPUT_STREAM_V_last_V_0_payload_A");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_payload_B, "INPUT_STREAM_V_last_V_0_payload_B");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_sel_rd, "INPUT_STREAM_V_last_V_0_sel_rd");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_sel_wr, "INPUT_STREAM_V_last_V_0_sel_wr");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_sel, "INPUT_STREAM_V_last_V_0_sel");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_load_A, "INPUT_STREAM_V_last_V_0_load_A");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_load_B, "INPUT_STREAM_V_last_V_0_load_B");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_state, "INPUT_STREAM_V_last_V_0_state");
sc_trace(mVcdFile, INPUT_STREAM_V_last_V_0_state_cmp_full, "INPUT_STREAM_V_last_V_0_state_cmp_full");
sc_trace(mVcdFile, INPUT_STREAM_V_dest_V_0_vld_in, "INPUT_STREAM_V_dest_V_0_vld_in");
sc_trace(mVcdFile, INPUT_STREAM_V_dest_V_0_ack_out, "INPUT_STREAM_V_dest_V_0_ack_out");
sc_trace(mVcdFile, INPUT_STREAM_V_dest_V_0_state, "INPUT_STREAM_V_dest_V_0_state");
sc_trace(mVcdFile, last_V, "last_V");
sc_trace(mVcdFile, INPUT_STREAM_TDATA_blk_n, "INPUT_STREAM_TDATA_blk_n");
sc_trace(mVcdFile, ap_CS_fsm_pp0_stage0, "ap_CS_fsm_pp0_stage0");
sc_trace(mVcdFile, ap_enable_reg_pp0_iter0, "ap_enable_reg_pp0_iter0");
sc_trace(mVcdFile, ap_block_pp0_stage0, "ap_block_pp0_stage0");
sc_trace(mVcdFile, tmp_fu_268_p2, "tmp_fu_268_p2");
sc_trace(mVcdFile, p_0_reg_176, "p_0_reg_176");
sc_trace(mVcdFile, i_reg_186, "i_reg_186");
sc_trace(mVcdFile, i_op_assign_reg_198, "i_op_assign_reg_198");
sc_trace(mVcdFile, first_s_reg_210, "first_s_reg_210");
sc_trace(mVcdFile, last_V_read_reg_391, "last_V_read_reg_391");
sc_trace(mVcdFile, sum_V_cast_fu_264_p1, "sum_V_cast_fu_264_p1");
sc_trace(mVcdFile, tmp_reg_406, "tmp_reg_406");
sc_trace(mVcdFile, ap_block_state2_pp0_stage0_iter0, "ap_block_state2_pp0_stage0_iter0");
sc_trace(mVcdFile, ap_block_state3_pp0_stage0_iter1, "ap_block_state3_pp0_stage0_iter1");
sc_trace(mVcdFile, ap_block_pp0_stage0_11001, "ap_block_pp0_stage0_11001");
sc_trace(mVcdFile, in1Count_fu_274_p2, "in1Count_fu_274_p2");
sc_trace(mVcdFile, in1Count_reg_410, "in1Count_reg_410");
sc_trace(mVcdFile, tmp_data_V_reg_416, "tmp_data_V_reg_416");
sc_trace(mVcdFile, tmp_last_V_reg_422, "tmp_last_V_reg_422");
sc_trace(mVcdFile, sum_V_fu_292_p2, "sum_V_fu_292_p2");
sc_trace(mVcdFile, sum_V_reg_426, "sum_V_reg_426");
sc_trace(mVcdFile, r_V_2_fu_349_p3, "r_V_2_fu_349_p3");
sc_trace(mVcdFile, ap_enable_reg_pp0_iter1, "ap_enable_reg_pp0_iter1");
sc_trace(mVcdFile, ap_block_pp0_stage0_subdone, "ap_block_pp0_stage0_subdone");
sc_trace(mVcdFile, ap_predicate_tran3to4_state2, "ap_predicate_tran3to4_state2");
sc_trace(mVcdFile, ap_phi_mux_p_0_phi_fu_179_p4, "ap_phi_mux_p_0_phi_fu_179_p4");
sc_trace(mVcdFile, ap_phi_mux_i_phi_fu_190_p4, "ap_phi_mux_i_phi_fu_190_p4");
sc_trace(mVcdFile, lhs_V_reg_222, "lhs_V_reg_222");
sc_trace(mVcdFile, value_1_reg_232, "value_1_reg_232");
sc_trace(mVcdFile, first_2_reg_243, "first_2_reg_243");
sc_trace(mVcdFile, in1Count_1_reg_254, "in1Count_1_reg_254");
sc_trace(mVcdFile, ap_CS_fsm_state4, "ap_CS_fsm_state4");
sc_trace(mVcdFile, tmp_2_cast_fu_288_p1, "tmp_2_cast_fu_288_p1");
sc_trace(mVcdFile, rhs_V_cast_fu_301_p1, "rhs_V_cast_fu_301_p1");
sc_trace(mVcdFile, lhs_V_cast_fu_298_p1, "lhs_V_cast_fu_298_p1");
sc_trace(mVcdFile, r_V_fu_305_p2, "r_V_fu_305_p2");
sc_trace(mVcdFile, tmp_5_fu_323_p1, "tmp_5_fu_323_p1");
sc_trace(mVcdFile, tmp_6_fu_327_p3, "tmp_6_fu_327_p3");
sc_trace(mVcdFile, tmp_4_fu_319_p1, "tmp_4_fu_319_p1");
sc_trace(mVcdFile, tmp_2_fu_311_p3, "tmp_2_fu_311_p3");
sc_trace(mVcdFile, tmp_8_fu_335_p2, "tmp_8_fu_335_p2");
sc_trace(mVcdFile, tmp_7_fu_341_p3, "tmp_7_fu_341_p3");
sc_trace(mVcdFile, tmp_9_fu_366_p4, "tmp_9_fu_366_p4");
sc_trace(mVcdFile, tmp_10_fu_362_p1, "tmp_10_fu_362_p1");
sc_trace(mVcdFile, ap_NS_fsm, "ap_NS_fsm");
sc_trace(mVcdFile, ap_idle_pp0, "ap_idle_pp0");
sc_trace(mVcdFile, ap_enable_pp0, "ap_enable_pp0");
sc_trace(mVcdFile, ap_condition_542, "ap_condition_542");
#endif
}
mHdltvinHandle.open("Random.hdltvin.dat");
mHdltvoutHandle.open("Random.hdltvout.dat");
}
Random::~Random() {
if (mVcdFile)
sc_close_vcd_trace_file(mVcdFile);
mHdltvinHandle << "] " << endl;
mHdltvoutHandle << "] " << endl;
mHdltvinHandle.close();
mHdltvoutHandle.close();
delete Random_CONTROL_BUS_s_axi_U;
}
void Random::thread_ap_var_for_const0() {
ap_var_for_const0 = ap_const_logic_1;
}
void Random::thread_ap_clk_no_reset_() {
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_data_V_0_sel_rd = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_ack_out.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_vld_out.read()))) {
INPUT_STREAM_V_data_V_0_sel_rd = (sc_logic) (~INPUT_STREAM_V_data_V_0_sel_rd.read());
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_data_V_0_sel_wr = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_ack_in.read()))) {
INPUT_STREAM_V_data_V_0_sel_wr = (sc_logic) (~INPUT_STREAM_V_data_V_0_sel_wr.read());
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_data_V_0_state = ap_const_lv2_0;
} else {
if (((esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_3)) ||
(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_vld_in.read()) &&
esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_2)))) {
INPUT_STREAM_V_data_V_0_state = ap_const_lv2_2;
} else if (((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_3)) ||
(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_1)))) {
INPUT_STREAM_V_data_V_0_state = ap_const_lv2_1;
} else if (((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_vld_in.read()) &&
esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_2)) ||
(esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_1)) ||
(esl_seteq<1,2,2>(INPUT_STREAM_V_data_V_0_state.read(), ap_const_lv2_3) &&
!(esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_ack_out.read())) &&
!(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_ack_out.read()))))) {
INPUT_STREAM_V_data_V_0_state = ap_const_lv2_3;
} else {
INPUT_STREAM_V_data_V_0_state = ap_const_lv2_2;
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_dest_V_0_state = ap_const_lv2_0;
} else {
if (((esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_dest_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_dest_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_3, INPUT_STREAM_V_dest_V_0_state.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_dest_V_0_vld_in.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_2, INPUT_STREAM_V_dest_V_0_state.read())))) {
INPUT_STREAM_V_dest_V_0_state = ap_const_lv2_2;
} else if (((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_dest_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_dest_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_3, INPUT_STREAM_V_dest_V_0_state.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_dest_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_1, INPUT_STREAM_V_dest_V_0_state.read())))) {
INPUT_STREAM_V_dest_V_0_state = ap_const_lv2_1;
} else if (((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_dest_V_0_vld_in.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_2, INPUT_STREAM_V_dest_V_0_state.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_dest_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_1, INPUT_STREAM_V_dest_V_0_state.read())) ||
(esl_seteq<1,2,2>(ap_const_lv2_3, INPUT_STREAM_V_dest_V_0_state.read()) &&
!(esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_dest_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_dest_V_0_ack_out.read())) &&
!(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_dest_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_dest_V_0_ack_out.read()))))) {
INPUT_STREAM_V_dest_V_0_state = ap_const_lv2_3;
} else {
INPUT_STREAM_V_dest_V_0_state = ap_const_lv2_2;
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_last_V_0_sel_rd = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_ack_out.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_vld_out.read()))) {
INPUT_STREAM_V_last_V_0_sel_rd = (sc_logic) (~INPUT_STREAM_V_last_V_0_sel_rd.read());
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_last_V_0_sel_wr = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_ack_in.read()))) {
INPUT_STREAM_V_last_V_0_sel_wr = (sc_logic) (~INPUT_STREAM_V_last_V_0_sel_wr.read());
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
INPUT_STREAM_V_last_V_0_state = ap_const_lv2_0;
} else {
if (((esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_last_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_3, INPUT_STREAM_V_last_V_0_state.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_last_V_0_vld_in.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_2, INPUT_STREAM_V_last_V_0_state.read())))) {
INPUT_STREAM_V_last_V_0_state = ap_const_lv2_2;
} else if (((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_vld_in.read()) &&
esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_last_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_3, INPUT_STREAM_V_last_V_0_state.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_last_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_1, INPUT_STREAM_V_last_V_0_state.read())))) {
INPUT_STREAM_V_last_V_0_state = ap_const_lv2_1;
} else if (((esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_vld_in.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_2, INPUT_STREAM_V_last_V_0_state.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_ack_out.read()) &&
esl_seteq<1,2,2>(ap_const_lv2_1, INPUT_STREAM_V_last_V_0_state.read())) ||
(esl_seteq<1,2,2>(ap_const_lv2_3, INPUT_STREAM_V_last_V_0_state.read()) &&
!(esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_last_V_0_ack_out.read())) &&
!(esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_last_V_0_vld_in.read()) && esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_ack_out.read()))))) {
INPUT_STREAM_V_last_V_0_state = ap_const_lv2_3;
} else {
INPUT_STREAM_V_last_V_0_state = ap_const_lv2_2;
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
ap_CS_fsm = ap_ST_fsm_state1;
} else {
ap_CS_fsm = ap_NS_fsm.read();
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
ap_enable_reg_pp0_iter0 = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_boolean_0, ap_block_pp0_stage0_subdone.read()) &&
esl_seteq<1,1,1>(ap_predicate_tran3to4_state2.read(), ap_const_boolean_1) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()))) {
ap_enable_reg_pp0_iter0 = ap_const_logic_0;
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
ap_enable_reg_pp0_iter0 = ap_const_logic_1;
}
}
if ( ap_rst_n_inv.read() == ap_const_logic_1) {
ap_enable_reg_pp0_iter1 = ap_const_logic_0;
} else {
if (esl_seteq<1,1,1>(ap_const_boolean_0, ap_block_pp0_stage0_subdone.read())) {
ap_enable_reg_pp0_iter1 = ap_enable_reg_pp0_iter0.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
ap_enable_reg_pp0_iter1 = ap_const_logic_0;
}
}
if (esl_seteq<1,1,1>(ap_condition_542.read(), ap_const_boolean_1)) {
if ((esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_last_V_reg_422.read()))) {
first_2_reg_243 = tmp_data_V_reg_416.read();
} else if (esl_seteq<1,1,1>(ap_const_lv1_0, tmp_reg_406.read())) {
first_2_reg_243 = first_s_reg_210.read();
}
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) &&
esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_last_V_reg_422.read()))) {
i_reg_186 = in1Count_reg_410.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
i_reg_186 = ap_const_lv23_0;
}
if (esl_seteq<1,1,1>(ap_condition_542.read(), ap_const_boolean_1)) {
if ((esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_last_V_reg_422.read()))) {
in1Count_1_reg_254 = in1Count_reg_410.read();
} else if (esl_seteq<1,1,1>(ap_const_lv1_0, tmp_reg_406.read())) {
in1Count_1_reg_254 = i_reg_186.read();
}
}
if (esl_seteq<1,1,1>(ap_condition_542.read(), ap_const_boolean_1)) {
if ((esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_last_V_reg_422.read()))) {
lhs_V_reg_222 = sum_V_reg_426.read();
} else if (esl_seteq<1,1,1>(ap_const_lv1_0, tmp_reg_406.read())) {
lhs_V_reg_222 = p_0_reg_176.read();
}
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) &&
esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_last_V_reg_422.read()))) {
p_0_reg_176 = sum_V_reg_426.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
p_0_reg_176 = sum_V_cast_fu_264_p1.read();
}
if (esl_seteq<1,1,1>(ap_condition_542.read(), ap_const_boolean_1)) {
if ((esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_last_V_reg_422.read()))) {
value_1_reg_232 = r_V_2_fu_349_p3.read();
} else if (esl_seteq<1,1,1>(ap_const_lv1_0, tmp_reg_406.read())) {
value_1_reg_232 = i_op_assign_reg_198.read();
}
}
if (esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_load_A.read())) {
INPUT_STREAM_V_data_V_0_payload_A = INPUT_STREAM_TDATA.read();
}
if (esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_load_B.read())) {
INPUT_STREAM_V_data_V_0_payload_B = INPUT_STREAM_TDATA.read();
}
if (esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_load_A.read())) {
INPUT_STREAM_V_last_V_0_payload_A = INPUT_STREAM_TLAST.read();
}
if (esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_load_B.read())) {
INPUT_STREAM_V_last_V_0_payload_B = INPUT_STREAM_TLAST.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_last_V_reg_422.read()))) {
first_s_reg_210 = tmp_data_V_reg_416.read();
i_op_assign_reg_198 = r_V_2_fu_349_p3.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
in1Count_reg_410 = in1Count_fu_274_p2.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
last_V_read_reg_391 = last_V.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
sum_V_reg_426 = sum_V_fu_292_p2.read();
tmp_data_V_reg_416 = INPUT_STREAM_V_data_V_0_data_out.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
tmp_last_V_reg_422 = INPUT_STREAM_V_last_V_0_data_out.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
tmp_reg_406 = tmp_fu_268_p2.read();
}
}
void Random::thread_INPUT_STREAM_TDATA_blk_n() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0.read(), ap_const_boolean_0) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()))) {
INPUT_STREAM_TDATA_blk_n = INPUT_STREAM_V_data_V_0_state.read()[0];
} else {
INPUT_STREAM_TDATA_blk_n = ap_const_logic_1;
}
}
void Random::thread_INPUT_STREAM_TREADY() {
INPUT_STREAM_TREADY = INPUT_STREAM_V_dest_V_0_state.read()[1];
}
void Random::thread_INPUT_STREAM_V_data_V_0_ack_in() {
INPUT_STREAM_V_data_V_0_ack_in = INPUT_STREAM_V_data_V_0_state.read()[1];
}
void Random::thread_INPUT_STREAM_V_data_V_0_ack_out() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
INPUT_STREAM_V_data_V_0_ack_out = ap_const_logic_1;
} else {
INPUT_STREAM_V_data_V_0_ack_out = ap_const_logic_0;
}
}
void Random::thread_INPUT_STREAM_V_data_V_0_data_out() {
if (esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_data_V_0_sel.read())) {
INPUT_STREAM_V_data_V_0_data_out = INPUT_STREAM_V_data_V_0_payload_B.read();
} else {
INPUT_STREAM_V_data_V_0_data_out = INPUT_STREAM_V_data_V_0_payload_A.read();
}
}
void Random::thread_INPUT_STREAM_V_data_V_0_load_A() {
INPUT_STREAM_V_data_V_0_load_A = (INPUT_STREAM_V_data_V_0_state_cmp_full.read() & ~INPUT_STREAM_V_data_V_0_sel_wr.read());
}
void Random::thread_INPUT_STREAM_V_data_V_0_load_B() {
INPUT_STREAM_V_data_V_0_load_B = (INPUT_STREAM_V_data_V_0_sel_wr.read() & INPUT_STREAM_V_data_V_0_state_cmp_full.read());
}
void Random::thread_INPUT_STREAM_V_data_V_0_sel() {
INPUT_STREAM_V_data_V_0_sel = INPUT_STREAM_V_data_V_0_sel_rd.read();
}
void Random::thread_INPUT_STREAM_V_data_V_0_state_cmp_full() {
INPUT_STREAM_V_data_V_0_state_cmp_full = (sc_logic) ((!INPUT_STREAM_V_data_V_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(INPUT_STREAM_V_data_V_0_state.read() != ap_const_lv2_1))[0];
}
void Random::thread_INPUT_STREAM_V_data_V_0_vld_in() {
INPUT_STREAM_V_data_V_0_vld_in = INPUT_STREAM_TVALID.read();
}
void Random::thread_INPUT_STREAM_V_data_V_0_vld_out() {
INPUT_STREAM_V_data_V_0_vld_out = INPUT_STREAM_V_data_V_0_state.read()[0];
}
void Random::thread_INPUT_STREAM_V_dest_V_0_ack_out() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
INPUT_STREAM_V_dest_V_0_ack_out = ap_const_logic_1;
} else {
INPUT_STREAM_V_dest_V_0_ack_out = ap_const_logic_0;
}
}
void Random::thread_INPUT_STREAM_V_dest_V_0_vld_in() {
INPUT_STREAM_V_dest_V_0_vld_in = INPUT_STREAM_TVALID.read();
}
void Random::thread_INPUT_STREAM_V_last_V_0_ack_in() {
INPUT_STREAM_V_last_V_0_ack_in = INPUT_STREAM_V_last_V_0_state.read()[1];
}
void Random::thread_INPUT_STREAM_V_last_V_0_ack_out() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0))) {
INPUT_STREAM_V_last_V_0_ack_out = ap_const_logic_1;
} else {
INPUT_STREAM_V_last_V_0_ack_out = ap_const_logic_0;
}
}
void Random::thread_INPUT_STREAM_V_last_V_0_data_out() {
if (esl_seteq<1,1,1>(ap_const_logic_1, INPUT_STREAM_V_last_V_0_sel.read())) {
INPUT_STREAM_V_last_V_0_data_out = INPUT_STREAM_V_last_V_0_payload_B.read();
} else {
INPUT_STREAM_V_last_V_0_data_out = INPUT_STREAM_V_last_V_0_payload_A.read();
}
}
void Random::thread_INPUT_STREAM_V_last_V_0_load_A() {
INPUT_STREAM_V_last_V_0_load_A = (INPUT_STREAM_V_last_V_0_state_cmp_full.read() & ~INPUT_STREAM_V_last_V_0_sel_wr.read());
}
void Random::thread_INPUT_STREAM_V_last_V_0_load_B() {
INPUT_STREAM_V_last_V_0_load_B = (INPUT_STREAM_V_last_V_0_sel_wr.read() & INPUT_STREAM_V_last_V_0_state_cmp_full.read());
}
void Random::thread_INPUT_STREAM_V_last_V_0_sel() {
INPUT_STREAM_V_last_V_0_sel = INPUT_STREAM_V_last_V_0_sel_rd.read();
}
void Random::thread_INPUT_STREAM_V_last_V_0_state_cmp_full() {
INPUT_STREAM_V_last_V_0_state_cmp_full = (sc_logic) ((!INPUT_STREAM_V_last_V_0_state.read().is_01() || !ap_const_lv2_1.is_01())? sc_lv<1>(): sc_lv<1>(INPUT_STREAM_V_last_V_0_state.read() != ap_const_lv2_1))[0];
}
void Random::thread_INPUT_STREAM_V_last_V_0_vld_in() {
INPUT_STREAM_V_last_V_0_vld_in = INPUT_STREAM_TVALID.read();
}
void Random::thread_INPUT_STREAM_V_last_V_0_vld_out() {
INPUT_STREAM_V_last_V_0_vld_out = INPUT_STREAM_V_last_V_0_state.read()[0];
}
void Random::thread_agg_result_a_ap_vld() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
agg_result_a_ap_vld = ap_const_logic_1;
} else {
agg_result_a_ap_vld = ap_const_logic_0;
}
}
void Random::thread_agg_result_b() {
agg_result_b = esl_zext<32,23>(in1Count_1_reg_254.read());
}
void Random::thread_agg_result_b_ap_vld() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
agg_result_b_ap_vld = ap_const_logic_1;
} else {
agg_result_b_ap_vld = ap_const_logic_0;
}
}
void Random::thread_agg_result_c_ap_vld() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
agg_result_c_ap_vld = ap_const_logic_1;
} else {
agg_result_c_ap_vld = ap_const_logic_0;
}
}
void Random::thread_agg_result_d() {
agg_result_d = esl_zext<32,23>(tmp_9_fu_366_p4.read());
}
void Random::thread_agg_result_d_ap_vld() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
agg_result_d_ap_vld = ap_const_logic_1;
} else {
agg_result_d_ap_vld = ap_const_logic_0;
}
}
void Random::thread_agg_result_e() {
agg_result_e = (tmp_10_fu_362_p1.read() ^ last_V_read_reg_391.read());
}
void Random::thread_agg_result_e_ap_vld() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
agg_result_e_ap_vld = ap_const_logic_1;
} else {
agg_result_e_ap_vld = ap_const_logic_0;
}
}
void Random::thread_agg_result_f() {
agg_result_f = esl_zext<32,12>(temperature_V.read());
}
void Random::thread_agg_result_f_ap_vld() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
agg_result_f_ap_vld = ap_const_logic_1;
} else {
agg_result_f_ap_vld = ap_const_logic_0;
}
}
void Random::thread_ap_CS_fsm_pp0_stage0() {
ap_CS_fsm_pp0_stage0 = ap_CS_fsm.read()[1];
}
void Random::thread_ap_CS_fsm_state1() {
ap_CS_fsm_state1 = ap_CS_fsm.read()[0];
}
void Random::thread_ap_CS_fsm_state4() {
ap_CS_fsm_state4 = ap_CS_fsm.read()[2];
}
void Random::thread_ap_block_pp0_stage0() {
ap_block_pp0_stage0 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1);
}
void Random::thread_ap_block_pp0_stage0_11001() {
ap_block_pp0_stage0_11001 = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) && esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_vld_out.read()));
}
void Random::thread_ap_block_pp0_stage0_subdone() {
ap_block_pp0_stage0_subdone = (esl_seteq<1,1,1>(ap_const_logic_1, ap_enable_reg_pp0_iter0.read()) && esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) && esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_vld_out.read()));
}
void Random::thread_ap_block_state2_pp0_stage0_iter0() {
ap_block_state2_pp0_stage0_iter0 = (esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) && esl_seteq<1,1,1>(ap_const_logic_0, INPUT_STREAM_V_data_V_0_vld_out.read()));
}
void Random::thread_ap_block_state3_pp0_stage0_iter1() {
ap_block_state3_pp0_stage0_iter1 = !esl_seteq<1,1,1>(ap_const_boolean_1, ap_const_boolean_1);
}
void Random::thread_ap_condition_542() {
ap_condition_542 = (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) && esl_seteq<1,1,1>(ap_block_pp0_stage0_11001.read(), ap_const_boolean_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1));
}
void Random::thread_ap_done() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
ap_done = ap_const_logic_1;
} else {
ap_done = ap_const_logic_0;
}
}
void Random::thread_ap_enable_pp0() {
ap_enable_pp0 = (ap_idle_pp0.read() ^ ap_const_logic_1);
}
void Random::thread_ap_idle() {
if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_start.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()))) {
ap_idle = ap_const_logic_1;
} else {
ap_idle = ap_const_logic_0;
}
}
void Random::thread_ap_idle_pp0() {
if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter0.read()) &&
esl_seteq<1,1,1>(ap_const_logic_0, ap_enable_reg_pp0_iter1.read()))) {
ap_idle_pp0 = ap_const_logic_1;
} else {
ap_idle_pp0 = ap_const_logic_0;
}
}
void Random::thread_ap_phi_mux_i_phi_fu_190_p4() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0.read(), ap_const_boolean_0) &&
esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_last_V_reg_422.read()))) {
ap_phi_mux_i_phi_fu_190_p4 = in1Count_reg_410.read();
} else {
ap_phi_mux_i_phi_fu_190_p4 = i_reg_186.read();
}
}
void Random::thread_ap_phi_mux_p_0_phi_fu_179_p4() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()) &&
esl_seteq<1,1,1>(ap_block_pp0_stage0.read(), ap_const_boolean_0) &&
esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_reg_406.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_last_V_reg_422.read()))) {
ap_phi_mux_p_0_phi_fu_179_p4 = sum_V_reg_426.read();
} else {
ap_phi_mux_p_0_phi_fu_179_p4 = p_0_reg_176.read();
}
}
void Random::thread_ap_predicate_tran3to4_state2() {
ap_predicate_tran3to4_state2 = (esl_seteq<1,1,1>(ap_const_lv1_0, tmp_fu_268_p2.read()) || (esl_seteq<1,1,1>(ap_const_lv1_1, tmp_fu_268_p2.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, INPUT_STREAM_V_last_V_0_data_out.read())));
}
void Random::thread_ap_ready() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
ap_ready = ap_const_logic_1;
} else {
ap_ready = ap_const_logic_0;
}
}
void Random::thread_ap_rst_n_inv() {
ap_rst_n_inv = (sc_logic) (~ap_rst_n.read());
}
void Random::thread_in1Count_fu_274_p2() {
in1Count_fu_274_p2 = (!ap_phi_mux_i_phi_fu_190_p4.read().is_01() || !ap_const_lv23_1.is_01())? sc_lv<23>(): (sc_biguint<23>(ap_phi_mux_i_phi_fu_190_p4.read()) + sc_biguint<23>(ap_const_lv23_1));
}
void Random::thread_lhs_V_cast_fu_298_p1() {
lhs_V_cast_fu_298_p1 = esl_zext<56,55>(sum_V_reg_426.read());
}
void Random::thread_r_V_2_fu_349_p3() {
r_V_2_fu_349_p3 = (!tmp_2_fu_311_p3.read()[0].is_01())? sc_lv<32>(): ((tmp_2_fu_311_p3.read()[0].to_bool())? tmp_8_fu_335_p2.read(): tmp_7_fu_341_p3.read());
}
void Random::thread_r_V_fu_305_p2() {
r_V_fu_305_p2 = (!rhs_V_cast_fu_301_p1.read().is_01() || !lhs_V_cast_fu_298_p1.read().is_01())? sc_lv<56>(): (sc_bigint<56>(rhs_V_cast_fu_301_p1.read()) + sc_biguint<56>(lhs_V_cast_fu_298_p1.read()));
}
void Random::thread_rhs_V_cast_fu_301_p1() {
rhs_V_cast_fu_301_p1 = esl_sext<56,32>(i_op_assign_reg_198.read());
}
void Random::thread_sum_V_cast_fu_264_p1() {
sum_V_cast_fu_264_p1 = esl_zext<55,12>(temperature_V.read());
}
void Random::thread_sum_V_fu_292_p2() {
sum_V_fu_292_p2 = (!ap_phi_mux_p_0_phi_fu_179_p4.read().is_01() || !tmp_2_cast_fu_288_p1.read().is_01())? sc_lv<55>(): (sc_biguint<55>(ap_phi_mux_p_0_phi_fu_179_p4.read()) + sc_biguint<55>(tmp_2_cast_fu_288_p1.read()));
}
void Random::thread_tmp_10_fu_362_p1() {
tmp_10_fu_362_p1 = lhs_V_reg_222.read().range(32-1, 0);
}
void Random::thread_tmp_2_cast_fu_288_p1() {
tmp_2_cast_fu_288_p1 = esl_zext<55,32>(INPUT_STREAM_V_data_V_0_data_out.read());
}
void Random::thread_tmp_2_fu_311_p3() {
tmp_2_fu_311_p3 = r_V_fu_305_p2.read().range(55, 55);
}
void Random::thread_tmp_4_fu_319_p1() {
tmp_4_fu_319_p1 = r_V_fu_305_p2.read().range(1-1, 0);
}
void Random::thread_tmp_5_fu_323_p1() {
tmp_5_fu_323_p1 = r_V_fu_305_p2.read().range(1-1, 0);
}
void Random::thread_tmp_6_fu_327_p3() {
tmp_6_fu_327_p3 = esl_concat<31,1>(ap_const_lv31_0, tmp_5_fu_323_p1.read());
}
void Random::thread_tmp_7_fu_341_p3() {
tmp_7_fu_341_p3 = esl_concat<31,1>(ap_const_lv31_0, tmp_4_fu_319_p1.read());
}
void Random::thread_tmp_8_fu_335_p2() {
tmp_8_fu_335_p2 = (!ap_const_lv32_0.is_01() || !tmp_6_fu_327_p3.read().is_01())? sc_lv<32>(): (sc_biguint<32>(ap_const_lv32_0) - sc_biguint<32>(tmp_6_fu_327_p3.read()));
}
void Random::thread_tmp_9_fu_366_p4() {
tmp_9_fu_366_p4 = lhs_V_reg_222.read().range(54, 32);
}
void Random::thread_tmp_fu_268_p2() {
tmp_fu_268_p2 = (!ap_phi_mux_i_phi_fu_190_p4.read().is_01() || !ap_const_lv23_7FBC00.is_01())? sc_lv<1>(): (sc_biguint<23>(ap_phi_mux_i_phi_fu_190_p4.read()) < sc_biguint<23>(ap_const_lv23_7FBC00));
}
void Random::thread_ap_NS_fsm() {
switch (ap_CS_fsm.read().to_uint64()) {
case 1 :
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
ap_NS_fsm = ap_ST_fsm_pp0_stage0;
} else {
ap_NS_fsm = ap_ST_fsm_state1;
}
break;
case 2 :
if (!(esl_seteq<1,1,1>(ap_const_boolean_0, ap_block_pp0_stage0_subdone.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter0.read(), ap_const_logic_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()))) {
ap_NS_fsm = ap_ST_fsm_pp0_stage0;
} else if ((esl_seteq<1,1,1>(ap_const_boolean_0, ap_block_pp0_stage0_subdone.read()) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter0.read(), ap_const_logic_0) && esl_seteq<1,1,1>(ap_enable_reg_pp0_iter1.read(), ap_const_logic_1) && esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_pp0_stage0.read()))) {
ap_NS_fsm = ap_ST_fsm_state4;
} else {
ap_NS_fsm = ap_ST_fsm_pp0_stage0;
}
break;
case 4 :
ap_NS_fsm = ap_ST_fsm_state1;
break;
default :
ap_NS_fsm = "XXX";
break;
}
}
void Random::thread_hdltv_gen() {
const char* dump_tv = std::getenv("AP_WRITE_TV");
if (!(dump_tv && string(dump_tv) == "on")) return;
wait();
mHdltvinHandle << "[ " << endl;
mHdltvoutHandle << "[ " << endl;
int ap_cycleNo = 0;
while (1) {
wait();
const char* mComma = ap_cycleNo == 0 ? " " : ", " ;
mHdltvinHandle << mComma << "{" << " \"ap_rst_n\" : \"" << ap_rst_n.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TDATA\" : \"" << INPUT_STREAM_TDATA.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TVALID\" : \"" << INPUT_STREAM_TVALID.read() << "\" ";
mHdltvoutHandle << mComma << "{" << " \"INPUT_STREAM_TREADY\" : \"" << INPUT_STREAM_TREADY.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TKEEP\" : \"" << INPUT_STREAM_TKEEP.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TSTRB\" : \"" << INPUT_STREAM_TSTRB.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TUSER\" : \"" << INPUT_STREAM_TUSER.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TLAST\" : \"" << INPUT_STREAM_TLAST.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TID\" : \"" << INPUT_STREAM_TID.read() << "\" ";
mHdltvinHandle << " , " << " \"INPUT_STREAM_TDEST\" : \"" << INPUT_STREAM_TDEST.read() << "\" ";
mHdltvinHandle << " , " << " \"temperature_V\" : \"" << temperature_V.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_AWVALID\" : \"" << s_axi_CONTROL_BUS_AWVALID.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_AWREADY\" : \"" << s_axi_CONTROL_BUS_AWREADY.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_AWADDR\" : \"" << s_axi_CONTROL_BUS_AWADDR.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_WVALID\" : \"" << s_axi_CONTROL_BUS_WVALID.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_WREADY\" : \"" << s_axi_CONTROL_BUS_WREADY.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_WDATA\" : \"" << s_axi_CONTROL_BUS_WDATA.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_WSTRB\" : \"" << s_axi_CONTROL_BUS_WSTRB.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_ARVALID\" : \"" << s_axi_CONTROL_BUS_ARVALID.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_ARREADY\" : \"" << s_axi_CONTROL_BUS_ARREADY.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_ARADDR\" : \"" << s_axi_CONTROL_BUS_ARADDR.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_RVALID\" : \"" << s_axi_CONTROL_BUS_RVALID.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_RREADY\" : \"" << s_axi_CONTROL_BUS_RREADY.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_RDATA\" : \"" << s_axi_CONTROL_BUS_RDATA.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_RRESP\" : \"" << s_axi_CONTROL_BUS_RRESP.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_BVALID\" : \"" << s_axi_CONTROL_BUS_BVALID.read() << "\" ";
mHdltvinHandle << " , " << " \"s_axi_CONTROL_BUS_BREADY\" : \"" << s_axi_CONTROL_BUS_BREADY.read() << "\" ";
mHdltvoutHandle << " , " << " \"s_axi_CONTROL_BUS_BRESP\" : \"" << s_axi_CONTROL_BUS_BRESP.read() << "\" ";
mHdltvoutHandle << " , " << " \"interrupt\" : \"" << interrupt.read() << "\" ";
mHdltvinHandle << "}" << std::endl;
mHdltvoutHandle << "}" << std::endl;
ap_cycleNo++;
}
}
}
|
#ifndef HTML5STANDALONE_H
#define HTML5STANDALONE_H
#ifdef HTML5_STANDALONE
#ifndef CONST_ARRAY
# if 1//def HAS_COMPLEX_GLOBALS
# define CONST_ARRAY(name, type) const type const name[] = {
# define CONST_ENTRY(x) x
# define CONST_END(name) };
# define CONST_ARRAY_INIT(name) ((void)0)
# else
# define CONST_ARRAY(name, type) void init_##name () { const type *local = name; int i=0;
# define CONST_ENTRY(x) local[i++] = x
# define CONST_END(name) ;}
# define CONST_ARRAY_INIT(name) init_##name()
# endif // HAS_COMPLEX_GLOBALS
#endif // CONST_ARRAY
class Ragnarok_UTF16toUTF8Converter
{
public:
Ragnarok_UTF16toUTF8Converter() : m_surrogate(0), m_num_converted(0) {}
virtual int Convert(const void *src, unsigned len, void *dest, int maxlen,
int *read);
virtual void Reset() { m_surrogate = 0; m_num_converted = 0; }
private:
UINT16 m_surrogate; ///< Stored surrogate value
unsigned m_num_converted;
};
#endif // HTML5_STANDALONE
#endif // HTML5STANDALONE_H
|
#pragma once
#include "ConstNode.hpp"
template<class Type>
struct ConstSingleValueNode : ConstNode<Type>
{
ConstSingleValueNode(Type & value)
: m_value(value)
{}
ArrayView<Type const> getOutputValues() const override
{
return ArrayView<Type const>(&m_value, 1);
}
std::size_t getNumOutputs() const override
{
return 1;
}
private:
Type & m_value;
};
|
#include <gtest/gtest.h>
#include "../vector.hpp"
TEST(vectorTests, DemonstrateGTestmacros)
{
vector<int> vec = {1, 2, 3, 4};
EXPECT_TRUE(vec[0] == 1 && vec[1] == 2 && vec[2] == 3 && vec[3] == 4);
EXPECT_TRUE(true);
//ASSERT_TRUE(false);
EXPECT_TRUE(true);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.