blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2991f21aeb2acbe29c60e3b30bd79a5c597c3984 | e788a7c2c5705e180dbbce01ff4d7cb3e815d167 | /LifeSim2D/LifeSim2DMain.cpp | 90b6fff607fcc60b49a86cc1816730668075d7d7 | [] | no_license | krille94/LifeSim2D | 8c6abdfd27454f0cef0b1c8f84c56edd272d5fec | 0a5c9e64af391b52cdce02d17d47e1707ffddc8c | refs/heads/master | 2020-07-07T14:29:30.371310 | 2019-08-20T12:48:31 | 2019-08-20T12:48:31 | 203,375,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,420 | cpp | #include "pch.h"
#include "LifeSim2DMain.h"
#include "Common\DirectXHelper.h"
using namespace LifeSim2D;
using namespace Windows::Foundation;
using namespace Windows::System::Threading;
using namespace Concurrency;
// Loads and initializes application assets when the application is loaded.
LifeSim2DMain::LifeSim2DMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
m_deviceResources(deviceResources)
{
// Register to be notified if the Device is lost or recreated
m_deviceResources->RegisterDeviceNotify(this);
// TODO: Replace this with your app's content initialization.
m_sceneRenderer = std::unique_ptr<Sample3DSceneRenderer>(new Sample3DSceneRenderer(m_deviceResources));
m_fpsTextRenderer = std::unique_ptr<SampleFpsTextRenderer>(new SampleFpsTextRenderer(m_deviceResources));
// TODO: Change the timer settings if you want something other than the default variable timestep mode.
// e.g. for 60 FPS fixed timestep update logic, call:
/*
m_timer.SetFixedTimeStep(true);
m_timer.SetTargetElapsedSeconds(1.0 / 60);
*/
}
LifeSim2DMain::~LifeSim2DMain()
{
// Deregister device notification
m_deviceResources->RegisterDeviceNotify(nullptr);
}
// Updates application state when the window size changes (e.g. device orientation change)
void LifeSim2DMain::CreateWindowSizeDependentResources()
{
// TODO: Replace this with the size-dependent initialization of your app's content.
m_sceneRenderer->CreateWindowSizeDependentResources();
}
// Updates the application state once per frame.
void LifeSim2DMain::Update()
{
// Update scene objects.
m_timer.Tick([&]()
{
// TODO: Replace this with your app's content update functions.
m_sceneRenderer->Update(m_timer);
m_fpsTextRenderer->Update(m_timer);
});
}
// Renders the current frame according to the current application state.
// Returns true if the frame was rendered and is ready to be displayed.
bool LifeSim2DMain::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return false;
}
auto context = m_deviceResources->GetD3DDeviceContext();
// Reset the viewport to target the whole screen.
auto viewport = m_deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
// Reset render targets to the screen.
ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() };
context->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());
// Clear the back buffer and depth stencil view.
context->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), DirectX::Colors::CornflowerBlue);
context->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
// Render the scene objects.
// TODO: Replace this with your app's content rendering functions.
m_sceneRenderer->Render();
m_fpsTextRenderer->Render();
return true;
}
// Notifies renderers that device resources need to be released.
void LifeSim2DMain::OnDeviceLost()
{
m_sceneRenderer->ReleaseDeviceDependentResources();
m_fpsTextRenderer->ReleaseDeviceDependentResources();
}
// Notifies renderers that device resources may now be recreated.
void LifeSim2DMain::OnDeviceRestored()
{
m_sceneRenderer->CreateDeviceDependentResources();
m_fpsTextRenderer->CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
| [
"kristian.timmermand@gmail.com"
] | kristian.timmermand@gmail.com |
fe039c6f4ef9e1b2bbb6f65bf751c14eb3222860 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/58/1ef51570bfab36/main.cpp | 91973b05018c03a840dd323fde97a72e19f747d0 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | #include <iostream>
#include <map>
int main()
{
std::map<float,float> mymap;
mymap[1.0] = 1.0;
std::cout << mymap[1.0] << std::endl;
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
7d399d846266571c95b8cda3a9877225e70aa014 | 39ab815dfdbab9628ede8ec3b4aedb5da3fd456a | /aql/benchmark/lib_50/class_7.cpp | f8da999746e0a2b8052fc122ef7c777717671d18 | [
"MIT"
] | permissive | menify/sandbox | c03b1bf24c1527b47eb473f1acc433f17bfb1d4f | 32166c71044f0d5b414335b2b6559adc571f568c | refs/heads/master | 2016-09-05T21:46:53.369065 | 2015-04-20T06:35:27 | 2015-04-20T06:35:27 | 25,891,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311 | cpp | #include "class_7.h"
#include "class_9.h"
#include "class_7.h"
#include "class_4.h"
#include "class_8.h"
#include "class_2.h"
#include <lib_46/class_6.h>
#include <lib_41/class_5.h>
#include <lib_0/class_3.h>
#include <lib_40/class_2.h>
#include <lib_20/class_9.h>
class_7::class_7() {}
class_7::~class_7() {}
| [
"menify@a28edc5c-ec3e-0410-a3da-1b30b3a8704b"
] | menify@a28edc5c-ec3e-0410-a3da-1b30b3a8704b |
8fc1b2af6c4f60763c48efb8954de301fac28c87 | 33a52c90e59d8d2ffffd3e174bb0d01426e48b4e | /uva/00400-/00498.cc | 0480daefb6eeaf3b5961df2ed9292451ed88e8f3 | [] | no_license | Hachimori/onlinejudge | eae388bc39bc852c8d9b791b198fc4e1f540da6e | 5446bd648d057051d5fdcd1ed9e17e7f217c2a41 | refs/heads/master | 2021-01-10T17:42:37.213612 | 2016-05-09T13:00:21 | 2016-05-09T13:00:21 | 52,657,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | cc | #include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
vector<int> coeff, xList;
bool read(){
coeff.clear();
xList.clear();
string s;
if(!getline(cin,s)) return false;
stringstream in(s);
int v;
while(in >> v) coeff.push_back(v);
in.clear();
getline(cin,s);
in.str(s);
while(in >> v) xList.push_back(v);
return true;
}
int mypow(int p, int n){
int ret = 1;
for(int i=0;i<n;i++) ret *= p;
return ret;
}
void work(){
for(int i=0;i<xList.size();i++){
int sum = 0;
for(int j=0;j<coeff.size();j++)
sum += coeff[j]*mypow(xList[i],coeff.size()-j-1);
if(i) cout << ' ';
cout << sum;
}cout << endl;
}
int main(){
while(read()) work();
return 0;
}
| [
"ben.shooter2@gmail.com"
] | ben.shooter2@gmail.com |
400d512063b2f6e2a464b653e173975c4b0ecdb2 | f4765d7d297c024289cad9816f929619db44710c | /test/test_surfacefriction.cpp | 2027160b36f19c6a43365b770eccdc5f93338cfc | [
"MIT"
] | permissive | nightwav/metaf | 70d5a5f7b8ae3cdb9b6ed106982e9ab848a51801 | 9a03381bb668da96d2e14f7af2afed5e2c2bb8bd | refs/heads/master | 2020-06-20T12:05:43.168180 | 2019-07-14T16:12:12 | 2019-07-14T17:24:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,784 | cpp | /*
* Copyright (C) 2018-2019 Nick Naumenko (https://gitlab.com/nnaumenko)
* All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "gtest/gtest.h"
#include "metaf.h"
static const auto margin = 0.01 / 2;
TEST(SurfaceFriction, fromStringFrictionCoefficient) {
const auto sf1 = metaf::SurfaceFriction::fromString("90");
ASSERT_TRUE(sf1.has_value());
EXPECT_EQ(sf1->status(), metaf::SurfaceFriction::Status::SURFACE_FRICTION_REPORTED);
ASSERT_TRUE(sf1->coefficient().has_value());
EXPECT_NEAR(sf1->coefficient().value(), 0.9, margin);
const auto sf2 = metaf::SurfaceFriction::fromString("62");
ASSERT_TRUE(sf2.has_value());
EXPECT_EQ(sf2->status(), metaf::SurfaceFriction::Status::SURFACE_FRICTION_REPORTED);
ASSERT_TRUE(sf2->coefficient().has_value());
EXPECT_NEAR(sf2->coefficient().value(), 0.62, margin);
const auto sf3 = metaf::SurfaceFriction::fromString("08");
ASSERT_TRUE(sf3.has_value());
EXPECT_EQ(sf3->status(), metaf::SurfaceFriction::Status::SURFACE_FRICTION_REPORTED);
ASSERT_TRUE(sf3->coefficient().has_value());
EXPECT_NEAR(sf3->coefficient().value(), 0.08, margin);
const auto sf4 = metaf::SurfaceFriction::fromString("00");
ASSERT_TRUE(sf4.has_value());
EXPECT_EQ(sf4->status(), metaf::SurfaceFriction::Status::SURFACE_FRICTION_REPORTED);
ASSERT_TRUE(sf4->coefficient().has_value());
EXPECT_NEAR(sf4->coefficient().value(), 0.0, margin);
}
TEST(SurfaceFriction, fromStringBrakingActionPoor) {
const auto sf = metaf::SurfaceFriction::fromString("91");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::BRAKING_ACTION_REPORTED);
ASSERT_TRUE(sf->coefficient().has_value());
EXPECT_NEAR(sf->coefficient().value(), 0.0, margin);
}
TEST(SurfaceFriction, fromStringBrakingActionMediumPoor) {
const auto sf = metaf::SurfaceFriction::fromString("92");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::BRAKING_ACTION_REPORTED);
ASSERT_TRUE(sf->coefficient().has_value());
EXPECT_NEAR(sf->coefficient().value(), 0.26, margin);
}
TEST(SurfaceFriction, fromStringBrakingActionMedium) {
const auto sf = metaf::SurfaceFriction::fromString("93");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::BRAKING_ACTION_REPORTED);
ASSERT_TRUE(sf->coefficient().has_value());
EXPECT_NEAR(sf->coefficient().value(), 0.30, margin);
}
TEST(SurfaceFriction, fromStringBrakingActionMediumGood) {
const auto sf = metaf::SurfaceFriction::fromString("94");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::BRAKING_ACTION_REPORTED);
ASSERT_TRUE(sf->coefficient().has_value());
EXPECT_NEAR(sf->coefficient().value(), 0.36, margin);
}
TEST(SurfaceFriction, fromStringBrakingActionGood) {
const auto sf = metaf::SurfaceFriction::fromString("95");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::BRAKING_ACTION_REPORTED);
ASSERT_TRUE(sf->coefficient().has_value());
EXPECT_NEAR(sf->coefficient().value(), 0.40, margin);
}
TEST(SurfaceFriction, fromStringReservedValues) {
EXPECT_FALSE(metaf::SurfaceFriction::fromString("96").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("97").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("98").has_value());
}
TEST(SurfaceFriction, fromStringUnreliable) {
const auto sf = metaf::SurfaceFriction::fromString("99");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::UNRELIABLE);
EXPECT_FALSE(sf->coefficient().has_value());
}
TEST(SurfaceFriction, fromStringNotReported) {
const auto sf = metaf::SurfaceFriction::fromString("//");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->status(), metaf::SurfaceFriction::Status::NOT_REPORTED);
EXPECT_FALSE(sf->coefficient().has_value());
}
TEST(SurfaceFriction, fromStringWrongFormat) {
EXPECT_FALSE(metaf::SurfaceFriction::fromString("").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("6").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("062").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("0A").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("///").has_value());
EXPECT_FALSE(metaf::SurfaceFriction::fromString("/").has_value());
}
TEST(SurfaceFriction, brakingActionPoor) {
const auto sf1 = metaf::SurfaceFriction::fromString("00");
ASSERT_TRUE(sf1.has_value());
EXPECT_EQ(sf1->brakingAction(), metaf::SurfaceFriction::BrakingAction::POOR);
const auto sf2 = metaf::SurfaceFriction::fromString("25");
ASSERT_TRUE(sf2.has_value());
EXPECT_EQ(sf2->brakingAction(), metaf::SurfaceFriction::BrakingAction::POOR);
}
TEST(SurfaceFriction, brakingActionMediumPoor) {
const auto sf1 = metaf::SurfaceFriction::fromString("26");
ASSERT_TRUE(sf1.has_value());
EXPECT_EQ(sf1->brakingAction(), metaf::SurfaceFriction::BrakingAction::MEDIUM_POOR);
const auto sf2 = metaf::SurfaceFriction::fromString("29");
ASSERT_TRUE(sf2.has_value());
EXPECT_EQ(sf2->brakingAction(), metaf::SurfaceFriction::BrakingAction::MEDIUM_POOR);
}
TEST(SurfaceFriction, brakingActionMedium) {
const auto sf1 = metaf::SurfaceFriction::fromString("30");
ASSERT_TRUE(sf1.has_value());
EXPECT_EQ(sf1->brakingAction(), metaf::SurfaceFriction::BrakingAction::MEDIUM);
const auto sf2 = metaf::SurfaceFriction::fromString("35");
ASSERT_TRUE(sf2.has_value());
EXPECT_EQ(sf2->brakingAction(), metaf::SurfaceFriction::BrakingAction::MEDIUM);
}
TEST(SurfaceFriction, brakingActionMediumGood) {
const auto sf1 = metaf::SurfaceFriction::fromString("36");
ASSERT_TRUE(sf1.has_value());
EXPECT_EQ(sf1->brakingAction(), metaf::SurfaceFriction::BrakingAction::MEDIUM_GOOD);
const auto sf2 = metaf::SurfaceFriction::fromString("39");
ASSERT_TRUE(sf2.has_value());
EXPECT_EQ(sf2->brakingAction(), metaf::SurfaceFriction::BrakingAction::MEDIUM_GOOD);
}
TEST(SurfaceFriction, brakingActionGood) {
const auto sf1 = metaf::SurfaceFriction::fromString("40");
ASSERT_TRUE(sf1.has_value());
EXPECT_EQ(sf1->brakingAction(), metaf::SurfaceFriction::BrakingAction::GOOD);
const auto sf2 = metaf::SurfaceFriction::fromString("90");
ASSERT_TRUE(sf2.has_value());
EXPECT_EQ(sf2->brakingAction(), metaf::SurfaceFriction::BrakingAction::GOOD);
}
TEST(SurfaceFriction, brakingActionUnreliable) {
const auto sf = metaf::SurfaceFriction::fromString("99");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->brakingAction(), metaf::SurfaceFriction::BrakingAction::NONE);
}
TEST(SurfaceFriction, brakingActionNotReported) {
const auto sf = metaf::SurfaceFriction::fromString("//");
ASSERT_TRUE(sf.has_value());
EXPECT_EQ(sf->brakingAction(), metaf::SurfaceFriction::BrakingAction::NONE);
}
| [
"nikolai.naumenko@gmail.com"
] | nikolai.naumenko@gmail.com |
ca245fe67f2ec231e49e89f63b1154aef60d9542 | d96e1da56d183f9b821c704ff98e4c0c1b14f5ca | /rotl/include/CityActionFarm.h | 71a67cfe0e1f90e97c9cc5ffd20052a7cf05a152 | [] | no_license | rpgrca/rotl | ba54dda6604afe3e1c3dbaab6e4894c12ae46281 | ea828dfadca95f849a3ea2d38ce49c1744294449 | refs/heads/master | 2023-01-04T02:30:39.561617 | 2020-10-31T04:39:44 | 2020-10-31T04:39:44 | 308,795,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,636 | h | /******************************************************************************\
*
* File: ../../include/CityActionFarm.h
* Creation date: April 14, 2005 02:03
* Author: ClassBuilder
* XXXX
* Purpose: Declaration of class 'CCityActionFarm'
*
* Modifications: @INSERT_MODIFICATIONS(* )
* April 15, 2005 14:32 ReyBrujo, 2005
* Added method 'Execute'
* April 14, 2005 02:03 ReyBrujo, 2005
* Added method 'DestructorInclude'
* Added method 'ConstructorInclude'
* Added method '~CCityActionFarm'
* Added method 'CCityActionFarm'
* Added inheritance 'CCityAction'
*
* Copyright 2005, XXXXX
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
*
\******************************************************************************/
#ifndef _CITYACTIONFARM_H
#define _CITYACTIONFARM_H
//@START_USER1
//@END_USER1
/*@NOTE_1390
Develop the crops in a city.
The amount of Gold necessary to FARM depends on the number of soldiers in the division.
Farming increases the city's Crop Value and the ruler's Loyalty and Respect levels.
*/
class CCityActionFarm
: public CCityAction
{
//@START_USER2
//@END_USER2
//
// Group: ClassBuilder methods
//
private:
void ConstructorInclude();
void DestructorInclude();
//
// Non-Grouped Members
//
//
// Non-Grouped Methods
//
public:
CCityActionFarm();
virtual ~CCityActionFarm();
virtual bool Execute();
};
#endif
#ifdef CB_INLINES
#ifndef _CITYACTIONFARM_H_INLINES
#define _CITYACTIONFARM_H_INLINES
//@START_USER3
//@END_USER3
#endif
#endif
| [
""
] | |
b227f31efb022b659615b659bff228abd30f3927 | a4ace471f3a34bfe7bd9aa57470aaa6e131012a9 | /LintCode/628_Maximum-Subtree/628_Maximum-Subtree-V3.cpp | 6eb6c2e429948e3e5629f98d99c9b04be2d6dabc | [] | no_license | luqian2017/Algorithm | 52beca787056e8418f74d383f4ea697f5f8934b7 | 17f281fb1400f165b4c5f8bdd3e0500f6c765b45 | refs/heads/master | 2023-08-17T05:37:14.886220 | 2023-08-08T06:10:28 | 2023-08-08T06:10:28 | 143,100,735 | 1 | 3 | null | 2020-10-19T07:05:21 | 2018-08-01T03:45:48 | C++ | UTF-8 | C++ | false | false | 1,073 | cpp | /**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: the maximum weight node
*/
TreeNode * findSubtree(TreeNode * root) {
long long maxSum = INT_MIN;
TreeNode * maxSumNode = NULL;
treeSum(root, maxSum, maxSumNode);
return maxSumNode;
}
private:
long long treeSum (TreeNode * root, long long & maxSum, TreeNode * & maxSumNode) {
long long result;
if (!root) result = 0;
else if (!root->left && !root->right) result = root->val;
else {
result = treeSum(root->left, maxSum, maxSumNode) + treeSum(root->right, maxSum, maxSumNode) + root->val;
}
if (result > maxSum) {
maxSumNode = root;
maxSum = max(maxSum, result);
}
return result;
}
}; | [
"luqian.ncsu@gmail.com"
] | luqian.ncsu@gmail.com |
c0dac32d9b1f242eb5905c8f8e39142d7a7f0c50 | 5e8be2ac3fefbdb980b2b107c3f74b32aea300e2 | /src/vt/pipe/pipe_manager_base.h | 3f5b5ca9ba9b58911baf348bc709b00590581730 | [
"BSD-3-Clause"
] | permissive | YouCannotBurnMyShadow/vt | 23b73b531f0b9bdfcea41eb5b73c903805bd5170 | 8bbcce879f6dd5e125cf8908b41baded077dfcbe | refs/heads/master | 2023-03-18T22:16:32.288410 | 2021-01-11T20:37:31 | 2021-01-11T20:37:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,444 | h | /*
//@HEADER
// *****************************************************************************
//
// pipe_manager_base.h
// DARMA Toolkit v. 1.0.0
// DARMA/vt => Virtual Transport
//
// Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#if !defined INCLUDED_PIPE_PIPE_MANAGER_BASE_H
#define INCLUDED_PIPE_PIPE_MANAGER_BASE_H
#include "vt/config.h"
#include "vt/pipe/pipe_common.h"
#include "vt/pipe/pipe_manager.fwd.h"
#include "vt/pipe/state/pipe_state.h"
#include "vt/pipe/msg/callback.h"
#include "vt/pipe/signal/signal_holder.h"
#include "vt/pipe/callback/anon/callback_anon.fwd.h"
#include "vt/pipe/callback/handler_send/callback_send.fwd.h"
#include "vt/pipe/callback/handler_bcast/callback_bcast.fwd.h"
#include "vt/pipe/callback/proxy_send/callback_proxy_send_tl.fwd.h"
#include "vt/pipe/callback/proxy_bcast/callback_proxy_bcast_tl.fwd.h"
#include "vt/pipe/callback/objgroup_send/callback_objgroup_send.fwd.h"
#include "vt/pipe/callback/objgroup_bcast/callback_objgroup_bcast.fwd.h"
#include "vt/pipe/callback/anon/callback_anon_tl.fwd.h"
#include <functional>
namespace vt { namespace pipe {
struct PipeManagerBase {
using PipeStateType = PipeState;
template <typename MsgT>
using FuncMsgType = std::function<void(MsgT*)>;
template <typename MsgT, typename ContextT>
using FuncMsgCtxType = std::function<void(MsgT*, ContextT*)>;
template <typename ContextT>
using FuncCtxType = std::function<void(ContextT*)>;
using FuncType = std::function<void(void)>;
using FuncVoidType = std::function<void(void)>;
using DispatchFuncType = PipeState::DispatchFuncType;
PipeManagerBase() = default;
template <typename SignalT>
friend struct pipe::callback::CallbackAnon;
template <typename SignalT>
friend struct pipe::callback::CallbackSend;
template <typename SignalT>
friend struct pipe::callback::CallbackBcast;
friend struct pipe::callback::CallbackAnonTypeless;
friend struct pipe::callback::CallbackProxySendTypeless;
friend struct pipe::callback::CallbackProxyBcastTypeless;
friend struct pipe::callback::CallbackProxySendDirect;
friend struct pipe::callback::CallbackProxyBcastDirect;
friend struct pipe::callback::CallbackObjGroupSend;
friend struct pipe::callback::CallbackObjGroupBcast;
PipeType makeCallbackFuncVoid(
bool const& persist, FuncType fn, bool const& dispatch = false,
RefType num_signals = -1, RefType num_listeners = 1
);
template <typename MsgT>
PipeType makeCallbackFunc(
bool const& persist, FuncMsgType<MsgT> fn, bool const& dispatch = false,
RefType num_signals = -1, RefType num_listeners = 1
);
template <typename MsgT>
void addListener(PipeType const& pipe, FuncMsgType<MsgT> fn);
void addListenerVoid(PipeType const& pipe, FuncType fn);
protected:
template <typename MsgT, typename ListenerT>
PipeType makeCallbackAny(
bool const& persist, ListenerT&& fn, bool const& dispatch = false,
RefType num_signals = -1, RefType num_listeners = 1
);
template <typename MsgT, typename ListenerT>
void addListenerAny(PipeType const& pipe, ListenerT&& fn);
public:
static void triggerCallbackHan(CallbackMsg* msg);
template <typename MsgT>
static void triggerCallbackMsgHan(MsgT* msg);
protected:
template <typename MsgT>
void triggerPipeTyped(PipeType const& pipe, MsgT* msg);
template <typename MsgT>
void triggerPipeUnknown(PipeType const& pipe, MsgT* msg);
template <typename SignalT, typename ListenerT>
void registerCallback(
PipeType const& pipe, ListenerT&& listener, bool update_state = true
);
void triggerPipe(PipeType const& pipe);
void generalSignalTrigger(PipeType const& pipe);
void newPipeState(
PipeType const& pipe, bool persist, bool typeless, RefType num_sig,
RefType num_listeners, RefType num_reg_listeners,
DispatchFuncType fn = nullptr
);
friend void triggerPipe(PipeType const& pipe);
template <typename MsgT>
friend void triggerPipeTyped(PipeType const& pipe, MsgT* msg);
template <typename MsgT>
friend void triggerPipeUnknown(PipeType const& pipe, MsgT* msg);
protected:
PipeType makePipeID(bool const persist, bool const send_back);
private:
template <typename SignalT>
static signal::SignalHolder<SignalT> signal_holder_;
private:
// the current pipe id local to this node
PipeIDType cur_pipe_id_ = initial_pipe_id;
// the pipe state for pipes that have a send back
std::unordered_map<PipeType,PipeStateType> pipe_state_;
};
}} /* end namespace vt::pipe */
#endif /*INCLUDED_PIPE_PIPE_MANAGER_BASE_H*/
| [
"jliffla@sandia.gov"
] | jliffla@sandia.gov |
4b6bfed18dde82b983c5bff18e853abe68e47e05 | 4ae1fcecd4ca690b75a5a0f9cd228979b542aa1e | /Grafuri/Dijkstra/main.cpp | 0ef18a766b1784f3b4cfaa0b03a2f6e06be44c20 | [] | no_license | lucigrigo/CppProjects | 7188483ac7cb6c8708ac24d2e9fc05fefafb8e5a | 1019d4e0027f24dc6bb0aca6de390a58b28be8f2 | refs/heads/master | 2023-03-18T22:39:17.086736 | 2021-03-12T22:31:56 | 2021-03-12T22:31:56 | 69,991,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | cpp | #include <iostream>
#include <fstream>
#define INF 10001
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
unsigned long int n,p,C[101][101],D[101],Viz[101],T[101];
void Citire();
void Dijkstra();
int main()
{
for(int i=1;i<=100;i++)
{
for(int j=1;j<=100;j++)
{
C[i][j]=INF;
}
}
Citire();
for(int i=1;i<=n;i++)
{
D[i]=C[p][i];
T[i]=p;
}
Viz[p]=1;
T[p]=0;
Dijkstra();
for(int i=1;i<=n;i++)
{
if(D[i]==INF)
{
out<<-1<<' ';
}
else
{
out<<D[i]<<' ';
}
}
return 0;
}
void Citire()
{
in>>n>>p;
int a,b,c;
while(in>>a>>b>>c)
{
C[a][b]=c;
}
for(int i=1;i<=n;i++)
{
C[i][i]=0;
}
}
void Dijkstra()
{
int OK=1,k,min;
while(OK)
{
min=INF;
k=-1;
for(int i=1;i<=n;i++)
{
if(Viz[i]==0 && min>D[i])
{
min=D[i];
k=i;
}
}
if(min==INF)
{
OK=0;
}
else
{
Viz[k]=1;
for(int i=1;i<=n;i++)
{
if(Viz[i]==0 && D[i]>D[k]+C[k][i])
{
D[i]=D[k]+C[k][i];
T[i]=k;
}
}
}
}
}
| [
"lucigrigo@yahoo.com"
] | lucigrigo@yahoo.com |
44943f48d4f666041eed47ff098385d9c8579167 | 8888fb4af4000f02903299bda0ecc954c402452a | /BOJ/1260.cpp | a11cee579f244ce7f695206098038d0d24c43e53 | [
"MIT"
] | permissive | ReinforceIII/Algorithm | 48122e826c60a433cdfb5bb1283db3b3d1be64d1 | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | refs/heads/master | 2020-07-26T03:57:36.567702 | 2019-09-16T11:46:02 | 2019-09-16T11:46:02 | 208,526,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cpp | /* 1260 DFS와 BFS*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
vector<int> v[1001];
bool visited[1001];
void dfs(int node) {
visited[node] = true;
cout<<node<<" ";
for(int i=0; i<v[node].size(); i++) {
int next = v[node][i];
if(visited[next] == false) dfs(next);
}
}
void bfs(int node) {
queue<int> q;
visited[node] = true;
q.push(node);
while(!q.empty()) {
int now = q.front(); q.pop();
cout<<now<<" ";
for(int i=0; i<v[now].size(); i++) {
int next = v[now][i];
if(visited[next] == false) {
visited[next] = true;
q.push(next);
}
}
}
}
int main() {
int n,m,start;
cin>>n>>m>>start;
for(int i=0; i<m; i++) {
int from,to;
cin>>from>>to;
v[from].push_back(to);
v[to].push_back(from);
}
for(int i=1; i<=n; i++) {
sort(v[i].begin(),v[i].end());
}
dfs(start);
cout<<"\n";
memset(visited,false,sizeof(visited));
bfs(start);
cout<<"\n";
return 0;
} | [
"reinforce3733@gmail.com"
] | reinforce3733@gmail.com |
379ad73dbbb1b6b62ac8029cb2d59b2047d6c258 | e90f112b43e460aa3371402a3ecdea561f5ceea7 | /cp_2/MutexLock.cpp | 9f3075775fead7f4e19028c12d14a812f1a8bc4a | [] | no_license | Ranper/muduo_cpp | d63e812d18548d1c4a0f4d341e2dc9eaa50a579f | d724c1693ea25b0188f0d35dfa1af9082e808be2 | refs/heads/master | 2021-01-08T02:55:01.149435 | 2020-02-20T13:39:45 | 2020-02-20T13:39:45 | 241,891,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | #include<pthread.h>
#include<cassert>
/*
用到的函数
pthread_mutex_init()
pthread_mutex_destory()
pthread_mutex_lock()
pthread_mutex_unlock()
@data: 2020/02/18
*/
class MutexLock
{
public:
explicit MutexLock(pthread_mutex_t & mutex):
mutex_(mutex),holder_(0)
{
pthread_mutex_init(&mutex_, NULL); // 初始化
}
void lock()
{
pthread_mutex_lock(&mutex_);
holder_ = CurrentThread::tid(); //持有该锁的线程id
}
void unlock()
{
holder_ = 0;
pthread_mutex_destroy(&mutex_); // 先清零,再释放
}
bool isLockedByThisThread() // 判断是不是当前进程持有锁
{
return holder_ == CurrentThrad::tid();
}
void assertLocked() // 如果是当前进程获得了锁,不报错。如果是其他线程或者没有线程获得锁,报错
{
assert(isLockedByThisThread());
}
pthread_mutex_t * getPthreadMutex() // 返回该线程持有的锁,返回的是地址,可以更改其状态
{
return &mutex_;
}
~MutexLock()
{
pthread_mutex_destroy(&mutex_);
}
private:
pthread_mutex_t &mutex_; //这里要声明为引用形式,表明用的是初始化时传递的那个mutex
pid_t holder_;
}; | [
"ranpeiwahaha@gmail.com"
] | ranpeiwahaha@gmail.com |
58c7b3b05111897b986ad923407332dd89459507 | 3784495ba55d26e22302a803861c4ba197fd82c7 | /src/torch/lib/include/torch/csrc/jit/variable_flags.h | 43c3ef9bf89a1ab7daf2fa3e68fe3c342f6eb357 | [
"MIT"
] | permissive | databill86/HyperFoods | cf7c31f5a6eb5c0d0ddb250fd045ca68eb5e0789 | 9267937c8c70fd84017c0f153c241d2686a356dd | refs/heads/master | 2021-01-06T17:08:48.736498 | 2020-02-11T05:02:18 | 2020-02-11T05:02:18 | 241,407,659 | 3 | 0 | MIT | 2020-02-18T16:15:48 | 2020-02-18T16:15:47 | null | UTF-8 | C++ | false | false | 442 | h | #pragma once
#include <iostream>
namespace torch { namespace autograd {
struct Variable;
}}
namespace torch { namespace jit {
struct VariableFlags {
static VariableFlags of(const autograd::Variable& var);
bool requires_grad;
bool defined;
};
static inline std::ostream & operator<<(std::ostream & out, const VariableFlags& v) {
return out
<< "(requires_grad=" << v.requires_grad
<< ", defined=" << v.defined << ")";
}
}}
| [
"luis20dr@gmail.com"
] | luis20dr@gmail.com |
9abb57f7bda24927b674089381522bc9f4d746f3 | 1b3ab88f023fbcff7d3c942db40607d105b6a5e8 | /geo.h | b2dfc713ccb735f0ab52109ec2f0c45ef2796798 | [] | no_license | pj12520/sinking_bim_new | a39dbb59a65de833de6299d634836c18c221d4d9 | a666167c1412e609baa86b746a1ce06c3390421c | refs/heads/master | 2021-07-17T03:27:11.223706 | 2021-02-07T10:30:00 | 2021-02-07T10:30:00 | 41,294,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,118 | h | //Header file containing function declarations relating to geometry
#ifndef __GEO_H__
#define __GEO_H__
#pragma once
#include <vector>
#include <fstream> //Included for debugging purposes only
#include "interp_1d.h"
using std::ofstream; //Using for debugging purposes only
//struct rad_diff_params { Spline_interp *rad_spline(vector<double>&, vector<double>&, double, double); double fit_const0; double fit_const1; double arc_max; };
//struct rad_diff_params { Spline_interp *rad_spline; double fit_const0; double fit_const1; double arc_max; };
//struct vert_diff_params { Spline_interp *vert_spline(vector<double>&, vector<double>&, double, double); double fit_const2; double fit_const3; double arc_max; };
//struct rad_diff_params { Spline_interp rad_spline(const Spline_interp&); double fit_const0; double fit_const1; double arc_max; };
//struct vert_diff_params { Spline_interp vert_spline; double fit_const2; double fit_const3; double arc_max; };
//Function to calculate hypotenuse of a right angled triangle given the length of the other sides.
double Pythag(double side1, double side2);
//Function to calculate the components of the normal vector and it's divergence at a point along the interface
void Normal(Spline_interp rad, Spline_interp height, double arc, double init_step, double *norm_rad, double *norm_vert, double *div_norm, double rad_coord, vector<double>* midpoints, vector<double>* pos_rad, vector<double>* pos_vert, double fit_const0, double fit_const1, double fit_const2, double fit_const3, double arc_max, ofstream& out, double fit_const_a, double fit_const_b);
//Function to calculate the normal components and the divergence of the normal to the interface when it is described by the extrapolated functions
void Normal_fit(double fit_const1, double fit_const2, double fit_const3, double arc, double arc4, double *norm_rad, double *norm_vert, double *div_norm, double rad_coord);
//Function to calculate divergence of the normal of the interface at given point along it
double Div_norm(Spline_interp rad, Spline_interp height, double arc, double init_step);
/*
//Function to calculate a tangent vector to a line at each point along it
void Tangent(vector<double>* rad, vector<double>* height, vector<double>* tangent_rad, vector<double>* tangent_height, int n_eval);
*/
//Function to calculate the radial component of the normal vector at a point along it
double Normal_rad(Spline_interp rad, Spline_interp height, double arc, double init_step);
//Function to calculate the vertical component of the normal vector at a point along it
double Normal_height(Spline_interp rad, Spline_interp height, double arc, double init_step);
/*
//Function to rotate a 2D vector in an anticlockwise direction by an angle theta
void Rotate(vector<double>* init_vector, vector<double>* final_vector, double theta);
*/
//Function to calculate the volume of upper phase fluid entrained below z=0
double Ent_vol(Spline_interp rad, Spline_interp vert, double max_arc, int n_int, double fit_const2, double fit_const3, double sphere_pos, double fit_const_b, double arc_trunc);
#endif /* GEO_H */
| [
"paul.jarvis@bristol.ac.uk"
] | paul.jarvis@bristol.ac.uk |
5b6b6b32a77715e9b46d5cc3af9ee807401e2389 | a6dd54cb560dddccef0b2233fa2990f25e818c7b | /POJ/2248.cpp | 96f44fc948d8ec8b8efaae585062ed59e4361859 | [] | no_license | renzov/Red_Crown | ec11106389196aac03d04167ad6703acc62aaef6 | 449fe413dbbd67cb0ca673af239f7d616249599a | refs/heads/master | 2021-07-08T04:56:22.617893 | 2021-05-14T18:41:06 | 2021-05-14T18:41:06 | 4,538,198 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | cpp | #include<cstdio>
#include<climits>
int d[205] = {0};
int a[105];
int b[105];
int best;
int n;
void dfs(int p){
if ( p + d[a[p]] >= best) return;
if (a[p] == n){
best = p;
for (int i=0; i <= p; ++i) b[i] = a[i];
return;
}
for(int i=p; i >= 0; --i)
for (int j=p; j >= i; --j)
if ( (a[i]+a[j] > a[p]) && (a[i] + a[j] <= n) ){
a[p+1] = a[i] + a[j];
dfs( p+1 );
}
}
void pre_calc(){
for (int i=n+n; i >= n; i--) d[i] = 0;
for (int i=n-1; i >= 1; --i) d[i] = 1 + d[i<<1];
a[0] = 1;
best = INT_MAX;
dfs(0);
for (int i=0;i < best; ++i)
printf("%d ",b[i]);
printf("%d\n",b[best]);
}
int main(){
while (scanf("%d",&n) && n){
pre_calc();
}
return 0;
} | [
"rgomez@lab13-31-i11.local"
] | rgomez@lab13-31-i11.local |
84c4319fd368afc6678d4aaca138017d4408f867 | 88296cd4ecc37ed59b47975e0acb3bf7c869e245 | /Codes/MLFramework/MLFramework/mlfmath.h | 181e59e7ec075182593e5a8ec446062f09687a76 | [] | no_license | YvensFaos/DisciplinaAprendizado | c17899770e50e0304a308d8d035dd2cc1d3f1142 | 7ba75e160660b3d45f68038b14b4d5277eed1a3f | refs/heads/master | 2020-12-02T12:35:01.180881 | 2014-12-15T13:56:23 | 2014-12-15T13:56:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | h | #ifndef __MLF_MATH__
#define __MLF_MATH__
#include <math.h>
//Inner Constants
#define CLOSE_RANGE 0.0005
//Constants
#define E 2.718281828f
class MLFMath
{
public:
static bool checkClose(float v1, float v2)
{
return ((v1 + CLOSE_RANGE > v2 && v1 - CLOSE_RANGE < v2) || (v2 + CLOSE_RANGE > v1 && v2 - CLOSE_RANGE < v1));
}
};
#endif | [
"yvensre@gmail.com"
] | yvensre@gmail.com |
eaed32d55644cd82c1dd2a5c5950c4750489db43 | bf1ddda8f27ba355f2d676645301649214a5335e | /SteeringBehaviour/SteeringBehaviour/Vec2.h | 660816ce8d16e86d70680a937cb69a9f39bd07e4 | [] | no_license | WaldiDev/SteeringBehaviour | 696a1bf49afabc68ed88ab45b7bbb5f1dc7bf50a | cbcc2ec0a0d94effbfcc91dce74151c1498d2f81 | refs/heads/master | 2021-01-10T14:33:03.718617 | 2016-04-01T09:39:48 | 2016-04-01T09:39:48 | 54,848,745 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | h | #pragma once
class Vec2
{
public:
Vec2();
Vec2(float x, float y);
void operator=(const Vec2 &rhs);
void operator+=(const Vec2 &rhs);
Vec2 operator+(const Vec2 &rhs) const;
Vec2 operator-(const Vec2 &rhs) const;
Vec2 operator*(const float &rhs) const;
Vec2 operator*(const Vec2 &rhs) const;
Vec2 operator/(const float &rhs) const;
bool operator==(const Vec2 &rhs) const;
Vec2 invert() const;
Vec2 rotate(float angle) const;
Vec2 normalize() const;
float length() const;
float lengthSqrt() const;
float getAngle() const;
float dot(const Vec2& rhs) const;
public:
float x;
float y;
const float m_Pi = 3.1415927410125732421875f;
const float m_Epsilon = 0.00001f;
}; | [
"marcuswald@hotmail.com"
] | marcuswald@hotmail.com |
5468e044dad94760648a3a820fc1a9eeae4c67f4 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /lto/include/alibabacloud/lto/model/EnableDeviceGroupRequest.h | ed631ad0d3e1de2106d9bc920b8f3c609a2de27d | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,501 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_LTO_MODEL_ENABLEDEVICEGROUPREQUEST_H_
#define ALIBABACLOUD_LTO_MODEL_ENABLEDEVICEGROUPREQUEST_H_
#include <alibabacloud/lto/LtoExport.h>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace Lto {
namespace Model {
class ALIBABACLOUD_LTO_EXPORT EnableDeviceGroupRequest : public RpcServiceRequest {
public:
EnableDeviceGroupRequest();
~EnableDeviceGroupRequest();
std::string getRegionId() const;
void setRegionId(const std::string ®ionId);
std::string getDeviceGroupId() const;
void setDeviceGroupId(const std::string &deviceGroupId);
private:
std::string regionId_;
std::string deviceGroupId_;
};
} // namespace Model
} // namespace Lto
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_LTO_MODEL_ENABLEDEVICEGROUPREQUEST_H_
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
c813fdfab86d577d062a269c1cb625aab6b73126 | 0b952169b8cac85519a8dd5c8bd19a311af231ad | /src/Router.h | 6a1879751788506a5e3dcafd784b84497ab78933 | [] | no_license | tingyingwu2010/simpleroute | 7fde6ec54e650de18d16a9bc95dd9d638d75992f | 4f2cce262ed1578524996becdebcd922dc31906f | refs/heads/master | 2021-09-26T10:00:38.266487 | 2018-10-28T22:33:46 | 2018-10-28T22:33:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,423 | h | #ifndef SIMPLE_ROUTE_ROUTER_H
#define SIMPLE_ROUTE_ROUTER_H
#include "Graph.h"
#include "CHGraph.h"
#include <unordered_set>
namespace simpleroute {
class Router {
public:
struct PathVisitor {
virtual void visit(uint32_t nodeRef) = 0;
};
struct AccessAllowanceEdgePreferences {
//set the allowed access types
uint32_t accessTypeMask;
AccessAllowanceEdgePreferences(uint32_t accessTypeMask = Graph::Edge::AT_ALL) : accessTypeMask(accessTypeMask) {}
virtual ~AccessAllowanceEdgePreferences() {}
virtual bool accessAllowed(const Graph::Edge & e) const;
};
struct AccessAllowanceWeightEdgePreferences: AccessAllowanceEdgePreferences {
AccessAllowanceWeightEdgePreferences(uint32_t accessTypeMask) : AccessAllowanceEdgePreferences(accessTypeMask) {}
virtual ~AccessAllowanceWeightEdgePreferences() {}
virtual double weight(const Graph::Edge & e) const = 0;
};
typedef enum {
HOP_DISTANCE,
DIJKSTRA_SET_DISTANCE, DIJKSTRA_SET_TIME,
DIJKSTRA_PRIO_QUEUE_DISTANCE, DIJKSTRA_PRIO_QUEUE_TIME,
A_STAR_DISTANCE, A_STAR_TIME
} RouterTypes;
public:
Router(const Graph * g) : m_g(g) {}
virtual ~Router() {}
virtual void route(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor) = 0;
protected:
inline const Graph & graph() const { return *m_g; }
private:
const Graph * m_g;
};
namespace detail {
class HopDistanceRouter: public Router {
public:
HopDistanceRouter(const Graph * g);
virtual ~HopDistanceRouter();
///takes ownership of ep
void setEP(AccessAllowanceEdgePreferences * ep);
virtual void route(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor) override;
private:
AccessAllowanceEdgePreferences * m_ep;
};
class DijkstraRouter: public Router {
public:
struct DistanceEdgePreferences: AccessAllowanceWeightEdgePreferences {
DistanceEdgePreferences(uint32_t accessTypeMask) : AccessAllowanceWeightEdgePreferences(accessTypeMask) {}
virtual ~DistanceEdgePreferences() {}
virtual double weight(const Graph::Edge& e) const override;
};
struct TimeEdgePreferences: AccessAllowanceWeightEdgePreferences {
///@param vehicleMaxSpeed in km/h
TimeEdgePreferences(uint32_t accessTypeMask, double vehicleMaxSpeed);
virtual ~TimeEdgePreferences() {}
virtual double weight(const Graph::Edge& e) const override;
double vehicleMaxSpeed;
};
public:
DijkstraRouter(const Graph * g);
virtual ~DijkstraRouter();
///takes ownership of ep
void setEP(AccessAllowanceWeightEdgePreferences * ep);
void setHeapType(bool usePrioQueue) { m_heapRoute = usePrioQueue; }
virtual void route(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor) override;
protected:
void routeSet(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor);
void routeHeap(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor);
private:
AccessAllowanceWeightEdgePreferences * m_ep;
bool m_heapRoute;
};
class AStarRouter: public Router {
public:
AStarRouter(const Graph * g) : Router(g) {}
virtual ~AStarRouter() {}
virtual void route(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor);
};
class CHRouter: public Router {
public:
CHRouter(const Graph * g, const CHInfo * chinfo, Graph::Edge::AccessTypes at);
virtual ~CHRouter() {}
virtual void route(uint32_t startNode, uint32_t endNode, PathVisitor * pathVisitor);
private:
const CHInfo * m_chInfo;
Graph::Edge::AccessTypes at;
};
}}//end namespace
#endif
| [
"daniel.git@funroll-loops.de"
] | daniel.git@funroll-loops.de |
6fad451bcad0165078b6915f89a3cb1391291adf | 0149a18329517d09305285f16ab41a251835269f | /Problem Set Volumes/Volume 9 (900-999)/UVa_988_Many_Paths_One_Destination.cpp | 05751dd83e3c932c134ce85869bdd0ce796e28e5 | [] | no_license | keisuke-kanao/my-UVa-solutions | 138d4bf70323a50defb3a659f11992490f280887 | f5d31d4760406378fdd206dcafd0f984f4f80889 | refs/heads/master | 2021-05-14T13:35:56.317618 | 2019-04-16T10:13:45 | 2019-04-16T10:13:45 | 116,445,001 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cpp |
/*
UVa 988 - Many Paths, One Destination
To build using Visual Studio 2012:
cl -EHsc -O2 UVa_988_Many_Paths_One_Destination.cpp
*/
#include <iostream>
#include <vector>
using namespace std;
int count_events(int i, const vector< vector<int> >& paths, vector<int>& nr_ways)
{
if (nr_ways[i] != -1)
return nr_ways[i];
else if (paths[i].empty())
return nr_ways[i] = 1;
else {
int nr = 0;
for (size_t j = 0, k = paths[i].size(); j < k; j++)
nr += count_events(paths[i][j], paths, nr_ways);
return nr_ways[i] = nr;
}
}
int main()
{
int n;
bool printed = false;
while (cin >> n) {
if (printed)
cout << endl;
else
printed = true;
vector< vector<int> > paths(n);
for (int i = 0; i < n; i++) {
int j;
cin >> j;
while (j--) {
int k;
cin >> k;
paths[i].push_back(k);
}
}
vector<int> nr_ways(n, -1);
// nr_ways[i] is the number of ways from i-th event
cout << count_events(0, paths, nr_ways) << endl;
}
return 0;
}
| [
"keisuke.kanao.154@gmail.com"
] | keisuke.kanao.154@gmail.com |
b74b5e27ba9ea578dff36e8ded684899e8d4a9ea | 966818603978f073d4f4ed85709ec1ad0c794be4 | /INSIGHT_20191106/include/ACE_Wrappers/ace/Active_Map_Manager_T.h | c43b521236c68e295e7aa0996cfaa3d5a0327444 | [] | no_license | lastvangogh/YANGZE | c337743e29dafadbfb1ed532f6c9ce35ce7f24df | 870eb6066b360036a49ebe40bd9435cdd31ff5ac | refs/heads/master | 2020-09-01T13:43:02.027589 | 2019-11-06T08:40:09 | 2019-11-06T08:40:09 | 218,970,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,137 | h | /* -*- C++ -*- */
//=============================================================================
/**
* @file Active_Map_Manager_T.h
*
* @author Irfan Pyarali
*/
//=============================================================================
#ifndef ACE_ACTIVE_MAP_MANAGER_T_H
#define ACE_ACTIVE_MAP_MANAGER_T_H
#include /**/ "ace/pre.h"
#include "ace/Map_Manager.h"
#include "ace/Active_Map_Manager.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/Null_Mutex.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
/**
* @class ACE_Active_Map_Manager
*
* @brief Define a map abstraction that associates system generated
* keys with user specified values.
*
* Since the key is system generated, searches are very fast and
* take a constant amount of time.
*/
template <class T>
class ACE_Active_Map_Manager : public ACE_Map_Manager<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex>
{
public:
// = Traits.
typedef ACE_Active_Map_Manager_Key key_type;
typedef T mapped_type;
typedef ACE_Map_Entry<ACE_Active_Map_Manager_Key, T> ENTRY;
typedef ACE_Map_Iterator<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> ITERATOR;
typedef ACE_Map_Reverse_Iterator<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> REVERSE_ITERATOR;
typedef ENTRY entry;
typedef ITERATOR iterator;
typedef REVERSE_ITERATOR reverse_iterator;
// = Initialization and termination methods.
/// Initialize a Active_Map_Manager with the ACE_DEFAULT_MAP_SIZE.
ACE_Active_Map_Manager (ACE_Allocator *alloc = 0);
/// Initialize a Active_Map_Manager with @a size entries.
ACE_Active_Map_Manager (size_t size,
ACE_Allocator *alloc = 0);
/// Close down a Active_Map_Manager and release dynamically
/// allocated resources.
~ACE_Active_Map_Manager (void);
/// Initialize a Active_Map_Manager with size @a length.
int open (size_t length = ACE_DEFAULT_MAP_SIZE,
ACE_Allocator *alloc = 0);
/// Close down a Active_Map_Manager and release dynamically
/// allocated resources.
int close (void);
/// Add @a value to the map, and the corresponding key produced by the
/// Active_Map_Manager is returned through @a key.
int bind (const T &value,
ACE_Active_Map_Manager_Key &key);
/// Add @a value to the map. The user does not care about the
/// corresponding key produced by the Active_Map_Manager.
int bind (const T &value);
/**
* Reserves a slot in the internal structure and returns the key and
* a pointer to the value. User should place their @a value into
* @a internal_value. This method is useful in reducing the number
* of copies required in some cases. Note that @a internal_value is
* only a temporary pointer and will change when the map resizes.
* Therefore, the user should use the pointer immediately and not
* hold on to it.
*/
int bind (ACE_Active_Map_Manager_Key &key,
T *&internal_value);
/// Reassociate @a key with @a value. The function fails if @a key is
/// not in the map.
int rebind (const ACE_Active_Map_Manager_Key &key,
const T &value);
/**
* Reassociate @a key with @a value, storing the old value into the
* "out" parameter @a old_value. The function fails if @a key is not
* in the map.
*/
int rebind (const ACE_Active_Map_Manager_Key &key,
const T &value,
T &old_value);
/**
* Reassociate @a key with @a value, storing the old key and value
* into the "out" parameter @a old_key and @a old_value. The function
* fails if @a key is not in the map.
*/
int rebind (const ACE_Active_Map_Manager_Key &key,
const T &value,
ACE_Active_Map_Manager_Key &old_key,
T &old_value);
/// Locate @a value associated with @a key.
int find (const ACE_Active_Map_Manager_Key &key,
T &value) const;
/// Is @a key in the map?
int find (const ACE_Active_Map_Manager_Key &key) const;
/**
* Locate @a value associated with @a key. The value is returned via
* @a internal_value and hence a copy is saved. Note that
* @a internal_value is only a temporary pointer and will change when
* the map resizes. Therefore, the user should use the pointer
* immediately and not hold on to it.
*/
int find (const ACE_Active_Map_Manager_Key &key,
T *&internal_value) const;
// Creates a key. User should place their @a value into
// <*internal_value>. This method is useful in reducing the number
// of copies required in some cases.
/// Remove @a key from the map.
int unbind (const ACE_Active_Map_Manager_Key &key);
/// Remove @a key from the map, and return the @a value associated with
/// @a key.
int unbind (const ACE_Active_Map_Manager_Key &key,
T &value);
/**
* Locate @a value associated with @a key. The value is returned via
* @a internal_value and hence a copy is saved. Note that
* @a internal_value is only a temporary pointer and will change when
* the map resizes or when this slot is reused. Therefore, the user
* should use the pointer immediately and not hold on to it.
*/
int unbind (const ACE_Active_Map_Manager_Key &key,
T *&internal_value);
/// Return the current size of the map.
size_t current_size (void) const;
/// Return the total size of the map.
size_t total_size (void) const;
/// Returns a key that cannot be found in the map.
static const ACE_Active_Map_Manager_Key npos (void);
/// Dump the state of an object.
void dump (void) const;
// = STL styled iterator factory functions.
/// Return forward iterator.
ACE_Map_Iterator<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> begin (void);
ACE_Map_Iterator<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> end (void);
/// Return reverse iterator.
ACE_Map_Reverse_Iterator<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> rbegin (void);
ACE_Map_Reverse_Iterator<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> rend (void);
/// Declare the dynamic allocation hooks.
ACE_ALLOC_HOOK_DECLARE;
protected:
/// Private base class
typedef ACE_Map_Manager<ACE_Active_Map_Manager_Key, T, ACE_Null_Mutex> ACE_AMM_BASE;
private:
// = Disallow these operations.
ACE_UNIMPLEMENTED_FUNC (void operator= (const ACE_Active_Map_Manager<T> &))
ACE_UNIMPLEMENTED_FUNC (ACE_Active_Map_Manager (const ACE_Active_Map_Manager<T> &))
};
ACE_END_VERSIONED_NAMESPACE_DECL
#if defined (__ACE_INLINE__)
#include "ace/Active_Map_Manager_T.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "ace/Active_Map_Manager_T.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */
#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Active_Map_Manager_T.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */
#include /**/ "ace/post.h"
#endif /* ACE_ACTIVE_MAP_MANAGER_T_H */
| [
"zhangzhuo@yangzeinvest.com"
] | zhangzhuo@yangzeinvest.com |
a78770606337c5dd5ed0213cbc9a54c554756190 | a83eb027e7e99b2900ed517b91870be9416a87ee | /cpp/clipper.cpp | d932da06434c8f66d91b22accfbd6b90176b6021 | [
"BSL-1.0"
] | permissive | mapnik/clipper | 33ac3da024322cd442f956b4ccad64f872445474 | 33c9329c743e49cb04be76d1c8923aa5f3bde6a3 | refs/heads/r493-mapnik | 2023-08-20T19:06:33.456141 | 2015-07-07T17:07:43 | 2015-07-07T17:07:43 | 36,896,304 | 8 | 5 | null | 2016-04-13T17:18:20 | 2015-06-04T21:25:55 | C++ | WINDOWS-1252 | C++ | false | false | 140,418 | cpp | /*******************************************************************************
* *
* Author : Angus Johnson *
* Version : 6.2.9 *
* Date : 16 February 2015 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2015 *
* *
* License: *
* Use, modification & distribution is subject to Boost Software License Ver 1. *
* http://www.boost.org/LICENSE_1_0.txt *
* *
* Attributions: *
* The code in this library is an extension of Bala Vatti's clipping algorithm: *
* "A generic solution to polygon clipping" *
* Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. *
* http://portal.acm.org/citation.cfm?id=129906 *
* *
* Computer graphics and geometric modeling: implementation and algorithms *
* By Max K. Agoston *
* Springer; 1 edition (January 4, 2005) *
* http://books.google.com/books?q=vatti+clipping+agoston *
* *
* See also: *
* "Polygon Offsetting by Computing Winding Numbers" *
* Paper no. DETC2005-85513 pp. 565-575 *
* ASME 2005 International Design Engineering Technical Conferences *
* and Computers and Information in Engineering Conference (IDETC/CIE2005) *
* September 24-28, 2005 , Long Beach, California, USA *
* http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf *
* *
*******************************************************************************/
/*******************************************************************************
* *
* This is a translation of the Delphi Clipper library and the naming style *
* used has retained a Delphi flavour. *
* *
*******************************************************************************/
#include "clipper.hpp"
#include <cmath>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <cstring>
#include <cstdlib>
#include <ostream>
#include <functional>
#include <sstream>
namespace ClipperLib {
static double const pi = 3.141592653589793238;
static double const two_pi = pi *2;
static double const def_arc_tolerance = 0.25;
enum Direction { dRightToLeft, dLeftToRight };
static int const Unassigned = -1; //edge not currently 'owning' a solution
static int const Skip = -2; //edge that would otherwise close a path
#define HORIZONTAL (-1.0E+40)
#define TOLERANCE (1.0e-20)
#define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE))
struct TEdge {
IntPoint Bot;
IntPoint Curr;
IntPoint Top;
IntPoint Delta;
double Dx;
PolyType PolyTyp;
EdgeSide Side;
int WindDelta; //1 or -1 depending on winding direction
int WindCnt;
int WindCnt2; //winding count of the opposite polytype
int OutIdx;
TEdge *Next;
TEdge *Prev;
TEdge *NextInLML;
TEdge *NextInAEL;
TEdge *PrevInAEL;
TEdge *NextInSEL;
TEdge *PrevInSEL;
};
struct IntersectNode {
TEdge *Edge1;
TEdge *Edge2;
IntPoint Pt;
};
struct LocalMinimum {
cInt Y;
TEdge *LeftBound;
TEdge *RightBound;
};
struct OutPt;
struct OutRec {
int Idx;
bool IsHole;
bool IsOpen;
OutRec *FirstLeft; //see comments in clipper.pas
PolyNode *PolyNd;
OutPt *Pts;
OutPt *BottomPt;
};
struct OutPt {
int Idx;
IntPoint Pt;
OutPt *Next;
OutPt *Prev;
};
struct Join {
OutPt *OutPt1;
OutPt *OutPt2;
IntPoint OffPt;
};
struct LocMinSorter
{
inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2)
{
return locMin2.Y < locMin1.Y;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
inline cInt Round(double val)
{
if ((val < 0)) return static_cast<cInt>(val - 0.5);
else return static_cast<cInt>(val + 0.5);
}
//------------------------------------------------------------------------------
inline cInt Abs(cInt val)
{
return val < 0 ? -val : val;
}
//------------------------------------------------------------------------------
// PolyTree methods ...
//------------------------------------------------------------------------------
void PolyTree::Clear()
{
for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
delete AllNodes[i];
AllNodes.resize(0);
Childs.resize(0);
}
//------------------------------------------------------------------------------
PolyNode* PolyTree::GetFirst() const
{
if (!Childs.empty())
return Childs[0];
else
return 0;
}
//------------------------------------------------------------------------------
int PolyTree::Total() const
{
int result = (int)AllNodes.size();
//with negative offsets, ignore the hidden outer polygon ...
if (result > 0 && Childs[0] != AllNodes[0]) result--;
return result;
}
//------------------------------------------------------------------------------
// PolyNode methods ...
//------------------------------------------------------------------------------
PolyNode::PolyNode(): Childs(), Parent(0), Index(0), m_IsOpen(false)
{
}
//------------------------------------------------------------------------------
int PolyNode::ChildCount() const
{
return (int)Childs.size();
}
//------------------------------------------------------------------------------
void PolyNode::AddChild(PolyNode& child)
{
unsigned cnt = (unsigned)Childs.size();
Childs.push_back(&child);
child.Parent = this;
child.Index = cnt;
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNext() const
{
if (!Childs.empty())
return Childs[0];
else
return GetNextSiblingUp();
}
//------------------------------------------------------------------------------
PolyNode* PolyNode::GetNextSiblingUp() const
{
if (!Parent) //protects against PolyTree.GetNextSiblingUp()
return 0;
else if (Index == Parent->Childs.size() - 1)
return Parent->GetNextSiblingUp();
else
return Parent->Childs[Index + 1];
}
//------------------------------------------------------------------------------
bool PolyNode::IsHole() const
{
bool result = true;
PolyNode* node = Parent;
while (node)
{
result = !result;
node = node->Parent;
}
return result;
}
//------------------------------------------------------------------------------
bool PolyNode::IsOpen() const
{
return m_IsOpen;
}
//------------------------------------------------------------------------------
#ifndef use_int32
//------------------------------------------------------------------------------
// Int128 class (enables safe math on signed 64bit integers)
// eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1
// Int128 val2((long64)9223372036854775807);
// Int128 val3 = val1 * val2;
// val3.AsString => "85070591730234615847396907784232501249" (8.5e+37)
//------------------------------------------------------------------------------
class Int128
{
public:
ulong64 lo;
long64 hi;
Int128(long64 _lo = 0)
{
lo = (ulong64)_lo;
if (_lo < 0) hi = -1; else hi = 0;
}
Int128(const Int128 &val): lo(val.lo), hi(val.hi){}
Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){}
Int128& operator = (const long64 &val)
{
lo = (ulong64)val;
if (val < 0) hi = -1; else hi = 0;
return *this;
}
bool operator == (const Int128 &val) const
{return (hi == val.hi && lo == val.lo);}
bool operator != (const Int128 &val) const
{ return !(*this == val);}
bool operator > (const Int128 &val) const
{
if (hi != val.hi)
return hi > val.hi;
else
return lo > val.lo;
}
bool operator < (const Int128 &val) const
{
if (hi != val.hi)
return hi < val.hi;
else
return lo < val.lo;
}
bool operator >= (const Int128 &val) const
{ return !(*this < val);}
bool operator <= (const Int128 &val) const
{ return !(*this > val);}
Int128& operator += (const Int128 &rhs)
{
hi += rhs.hi;
lo += rhs.lo;
if (lo < rhs.lo) hi++;
return *this;
}
Int128 operator + (const Int128 &rhs) const
{
Int128 result(*this);
result+= rhs;
return result;
}
Int128& operator -= (const Int128 &rhs)
{
*this += -rhs;
return *this;
}
Int128 operator - (const Int128 &rhs) const
{
Int128 result(*this);
result -= rhs;
return result;
}
Int128 operator-() const //unary negation
{
if (lo == 0)
return Int128(-hi, 0);
else
return Int128(~hi, ~lo + 1);
}
operator double() const
{
const double shift64 = 18446744073709551616.0; //2^64
if (hi < 0)
{
if (lo == 0) return (double)hi * shift64;
else return -(double)(~lo + ~hi * shift64);
}
else
return (double)(lo + hi * shift64);
}
};
//------------------------------------------------------------------------------
Int128 Int128Mul (long64 lhs, long64 rhs)
{
bool negate = (lhs < 0) != (rhs < 0);
if (lhs < 0) lhs = -lhs;
ulong64 int1Hi = ulong64(lhs) >> 32;
ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF);
if (rhs < 0) rhs = -rhs;
ulong64 int2Hi = ulong64(rhs) >> 32;
ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF);
//nb: see comments in clipper.pas
ulong64 a = int1Hi * int2Hi;
ulong64 b = int1Lo * int2Lo;
ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi;
Int128 tmp;
tmp.hi = long64(a + (c >> 32));
tmp.lo = long64(c << 32);
tmp.lo += long64(b);
if (tmp.lo < b) tmp.hi++;
if (negate) tmp = -tmp;
return tmp;
};
#endif
//------------------------------------------------------------------------------
// Miscellaneous global functions
//------------------------------------------------------------------------------
bool Orientation(const Path &poly)
{
return Area(poly) >= 0;
}
//------------------------------------------------------------------------------
double Area(const Path &poly)
{
int size = (int)poly.size();
if (size < 3) return 0;
double a = 0;
for (int i = 0, j = size -1; i < size; ++i)
{
a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y);
j = i;
}
return -a * 0.5;
}
//------------------------------------------------------------------------------
double Area(const OutRec &outRec)
{
OutPt *op = outRec.Pts;
if (!op) return 0;
double a = 0;
do {
a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y);
op = op->Next;
} while (op != outRec.Pts);
return a * 0.5;
}
//------------------------------------------------------------------------------
bool PointIsVertex(const IntPoint &Pt, OutPt *pp)
{
OutPt *pp2 = pp;
do
{
if (pp2->Pt == Pt) return true;
pp2 = pp2->Next;
}
while (pp2 != pp);
return false;
}
//------------------------------------------------------------------------------
//See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf
int PointInPolygon(const IntPoint &pt, const Path &path)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
size_t cnt = path.size();
if (cnt < 3) return 0;
IntPoint ip = path[0];
for(size_t i = 1; i <= cnt; ++i)
{
IntPoint ipNext = (i == cnt ? path[0] : path[i]);
if (ipNext.Y == pt.Y)
{
if ((ipNext.X == pt.X) || (ip.Y == pt.Y &&
((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1;
}
if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y))
{
if (ip.X >= pt.X)
{
if (ipNext.X > pt.X) result = 1 - result;
else
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
} else
{
if (ipNext.X > pt.X)
{
double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) -
(double)(ipNext.X - pt.X) * (ip.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result;
}
}
}
ip = ipNext;
}
return result;
}
//------------------------------------------------------------------------------
int PointInPolygon (const IntPoint &pt, OutPt *op)
{
//returns 0 if false, +1 if true, -1 if pt ON polygon boundary
int result = 0;
OutPt* startOp = op;
for(;;)
{
if (op->Next->Pt.Y == pt.Y)
{
if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y &&
((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1;
}
if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y))
{
if (op->Pt.X >= pt.X)
{
if (op->Next->Pt.X > pt.X) result = 1 - result;
else
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
} else
{
if (op->Next->Pt.X > pt.X)
{
double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) -
(double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y);
if (!d) return -1;
if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result;
}
}
}
op = op->Next;
if (startOp == op) break;
}
return result;
}
//------------------------------------------------------------------------------
bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2)
{
OutPt* op = OutPt1;
do
{
//nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon
int res = PointInPolygon(op->Pt, OutPt2);
if (res >= 0) return res > 0;
op = op->Next;
}
while (op != OutPt1);
return true;
}
//----------------------------------------------------------------------
bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(e1.Delta.Y, e2.Delta.X) == Int128Mul(e1.Delta.X, e2.Delta.Y);
else
#endif
return e1.Delta.Y * e2.Delta.X == e1.Delta.X * e2.Delta.Y;
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y);
}
//------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range)
{
#ifndef use_int32
if (UseFullInt64Range)
return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y);
else
#endif
return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y);
}
//------------------------------------------------------------------------------
inline bool IsHorizontal(TEdge &e)
{
return e.Delta.Y == 0;
}
//------------------------------------------------------------------------------
inline double GetDx(const IntPoint pt1, const IntPoint pt2)
{
return (pt1.Y == pt2.Y) ?
HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
}
//---------------------------------------------------------------------------
inline void SetDx(TEdge &e)
{
e.Delta.X = (e.Top.X - e.Bot.X);
e.Delta.Y = (e.Top.Y - e.Bot.Y);
if (e.Delta.Y == 0) e.Dx = HORIZONTAL;
else e.Dx = (double)(e.Delta.X) / e.Delta.Y;
}
//---------------------------------------------------------------------------
inline void SwapSides(TEdge &Edge1, TEdge &Edge2)
{
EdgeSide Side = Edge1.Side;
Edge1.Side = Edge2.Side;
Edge2.Side = Side;
}
//------------------------------------------------------------------------------
inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2)
{
int OutIdx = Edge1.OutIdx;
Edge1.OutIdx = Edge2.OutIdx;
Edge2.OutIdx = OutIdx;
}
//------------------------------------------------------------------------------
inline cInt TopX(TEdge &edge, const cInt currentY)
{
return ( currentY == edge.Top.Y ) ?
edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y));
}
//------------------------------------------------------------------------------
void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip)
{
#ifdef use_xyz
ip.Z = 0;
#endif
double b1, b2;
if (Edge1.Dx == Edge2.Dx)
{
ip.Y = Edge1.Curr.Y;
ip.X = TopX(Edge1, ip.Y);
return;
}
else if (Edge1.Delta.X == 0)
{
ip.X = Edge1.Bot.X;
if (IsHorizontal(Edge2))
ip.Y = Edge2.Bot.Y;
else
{
b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx);
ip.Y = Round(ip.X / Edge2.Dx + b2);
}
}
else if (Edge2.Delta.X == 0)
{
ip.X = Edge2.Bot.X;
if (IsHorizontal(Edge1))
ip.Y = Edge1.Bot.Y;
else
{
b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx);
ip.Y = Round(ip.X / Edge1.Dx + b1);
}
}
else
{
b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx;
b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx;
double q = (b2-b1) / (Edge1.Dx - Edge2.Dx);
ip.Y = Round(q);
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = Round(Edge1.Dx * q + b1);
else
ip.X = Round(Edge2.Dx * q + b2);
}
if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y)
{
if (Edge1.Top.Y > Edge2.Top.Y)
ip.Y = Edge1.Top.Y;
else
ip.Y = Edge2.Top.Y;
if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx))
ip.X = TopX(Edge1, ip.Y);
else
ip.X = TopX(Edge2, ip.Y);
}
//finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ...
if (ip.Y > Edge1.Curr.Y)
{
ip.Y = Edge1.Curr.Y;
//use the more vertical edge to derive X ...
if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx))
ip.X = TopX(Edge2, ip.Y); else
ip.X = TopX(Edge1, ip.Y);
}
}
//------------------------------------------------------------------------------
void ReversePolyPtLinks(OutPt *pp)
{
if (!pp) return;
OutPt *pp1, *pp2;
pp1 = pp;
do {
pp2 = pp1->Next;
pp1->Next = pp1->Prev;
pp1->Prev = pp2;
pp1 = pp2;
} while( pp1 != pp );
}
//------------------------------------------------------------------------------
void DisposeOutPts(OutPt*& pp)
{
if (pp == 0) return;
pp->Prev->Next = 0;
while( pp )
{
OutPt *tmpPp = pp;
pp = pp->Next;
delete tmpPp;
}
}
//------------------------------------------------------------------------------
inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
{
std::memset(e, 0, sizeof(TEdge));
e->Next = eNext;
e->Prev = ePrev;
e->Curr = Pt;
e->OutIdx = Unassigned;
}
//------------------------------------------------------------------------------
void InitEdge2(TEdge& e, PolyType Pt)
{
if (e.Curr.Y >= e.Next->Curr.Y)
{
e.Bot = e.Curr;
e.Top = e.Next->Curr;
} else
{
e.Top = e.Curr;
e.Bot = e.Next->Curr;
}
SetDx(e);
e.PolyTyp = Pt;
}
//------------------------------------------------------------------------------
TEdge* RemoveEdge(TEdge* e)
{
//removes e from double_linked_list (but without removing from memory)
e->Prev->Next = e->Next;
e->Next->Prev = e->Prev;
TEdge* result = e->Next;
e->Prev = 0; //flag as removed (see ClipperBase.Clear)
return result;
}
//------------------------------------------------------------------------------
inline void ReverseHorizontal(TEdge &e)
{
//swap horizontal edges' Top and Bottom x's so they follow the natural
//progression of the bounds - ie so their xbots will align with the
//adjoining lower edge. [Helpful in the ProcessHorizontal() method.]
std::swap(e.Top.X, e.Bot.X);
#ifdef use_xyz
std::swap(e.Top.Z, e.Bot.Z);
#endif
}
//------------------------------------------------------------------------------
void SwapPoints(IntPoint &pt1, IntPoint &pt2)
{
IntPoint tmp = pt1;
pt1 = pt2;
pt2 = tmp;
}
//------------------------------------------------------------------------------
bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a,
IntPoint pt2b, IntPoint &pt1, IntPoint &pt2)
{
//precondition: segments are Collinear.
if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y))
{
if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b);
if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b);
if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b;
return pt1.X < pt2.X;
} else
{
if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b);
if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b);
if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a;
if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b;
return pt1.Y > pt2.Y;
}
}
//------------------------------------------------------------------------------
bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2)
{
OutPt *p = btmPt1->Prev;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev;
double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt1->Next;
while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next;
double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt));
p = btmPt2->Prev;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev;
double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt));
p = btmPt2->Next;
while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next;
double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt));
return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n);
}
//------------------------------------------------------------------------------
OutPt* GetBottomPt(OutPt *pp)
{
OutPt* dups = 0;
OutPt* p = pp->Next;
while (p != pp)
{
if (p->Pt.Y > pp->Pt.Y)
{
pp = p;
dups = 0;
}
else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X)
{
if (p->Pt.X < pp->Pt.X)
{
dups = 0;
pp = p;
} else
{
if (p->Next != pp && p->Prev != pp) dups = p;
}
}
p = p->Next;
}
if (dups)
{
//there appears to be at least 2 vertices at BottomPt so ...
while (dups != p)
{
if (!FirstIsBottomPt(p, dups)) pp = dups;
dups = dups->Next;
while (dups->Pt != pp->Pt) dups = dups->Next;
}
}
return pp;
}
//------------------------------------------------------------------------------
bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1,
const IntPoint pt2, const IntPoint pt3)
{
if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
return false;
else if (pt1.X != pt3.X)
return (pt2.X > pt1.X) == (pt2.X < pt3.X);
else
return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y);
}
//------------------------------------------------------------------------------
bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
{
if (seg1a > seg1b) std::swap(seg1a, seg1b);
if (seg2a > seg2b) std::swap(seg2a, seg2b);
return (seg1a < seg2b) && (seg2a < seg1b);
}
//------------------------------------------------------------------------------
// ClipperBase class methods ...
//------------------------------------------------------------------------------
ClipperBase::ClipperBase() //constructor
{
m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
m_UseFullRange = false;
}
//------------------------------------------------------------------------------
ClipperBase::~ClipperBase() //destructor
{
Clear();
}
//------------------------------------------------------------------------------
void RangeTest(const IntPoint& Pt, bool& useFullRange)
{
if (useFullRange)
{
if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange)
{
std::stringstream s;
s << "Coordinate outside allowed range: ";
s << std::fixed << Pt.X << " " << Pt.Y << " " << -Pt.X << " " << -Pt.Y;
throw clipperException(s.str().c_str());
}
}
else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange)
{
useFullRange = true;
RangeTest(Pt, useFullRange);
}
}
//------------------------------------------------------------------------------
TEdge* FindNextLocMin(TEdge* E)
{
for (;;)
{
while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next;
if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break;
while (IsHorizontal(*E->Prev)) E = E->Prev;
TEdge* E2 = E;
while (IsHorizontal(*E)) E = E->Next;
if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz.
if (E2->Prev->Bot.X < E->Bot.X) E = E2;
break;
}
return E;
}
//------------------------------------------------------------------------------
TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
{
TEdge *Result = E;
TEdge *Horz = 0;
if (E->OutIdx == Skip)
{
//if edges still remain in the current bound beyond the skip edge then
//create another LocMin and call ProcessBound once more
if (NextIsForward)
{
while (E->Top.Y == E->Next->Bot.Y) E = E->Next;
//don't include top horizontals when parsing a bound a second time,
//they will be contained in the opposite bound ...
while (E != Result && IsHorizontal(*E)) E = E->Prev;
}
else
{
while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev;
while (E != Result && IsHorizontal(*E)) E = E->Next;
}
if (E == Result)
{
if (NextIsForward) Result = E->Next;
else Result = E->Prev;
}
else
{
//there are more edges in the bound beyond result starting with E
if (NextIsForward)
E = Result->Next;
else
E = Result->Prev;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
E->WindDelta = 0;
Result = ProcessBound(E, NextIsForward);
m_MinimaList.push_back(locMin);
}
return Result;
}
TEdge *EStart;
if (IsHorizontal(*E))
{
//We need to be careful with open paths because this may not be a
//true local minima (ie E may be following a skip edge).
//Also, consecutive horz. edges may start heading left before going right.
if (NextIsForward)
EStart = E->Prev;
else
EStart = E->Next;
if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge
{
if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X)
ReverseHorizontal(*E);
}
else if (EStart->Bot.X != E->Bot.X)
ReverseHorizontal(*E);
}
EStart = E;
if (NextIsForward)
{
while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip)
Result = Result->Next;
if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip)
{
//nb: at the top of a bound, horizontals are added to the bound
//only when the preceding edge attaches to the horizontal's left vertex
//unless a Skip edge is encountered when that becomes the top divide
Horz = Result;
while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
}
while (E != Result)
{
E->NextInLML = E->Next;
if (IsHorizontal(*E) && E != EStart &&
E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
E = E->Next;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X)
ReverseHorizontal(*E);
Result = Result->Next; //move to the edge just beyond current bound
} else
{
while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip)
Result = Result->Prev;
if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
{
Horz = Result;
while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
if (Horz->Next->Top.X == Result->Prev->Top.X ||
Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
}
while (E != Result)
{
E->NextInLML = E->Prev;
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
E = E->Prev;
}
if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X)
ReverseHorizontal(*E);
Result = Result->Prev; //move to the edge just beyond current bound
}
return Result;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed)
{
#ifdef use_lines
if (!Closed && PolyTyp == ptClip)
throw clipperException("AddPath: Open paths must be subject.");
#else
if (!Closed)
throw clipperException("AddPath: Open paths have been disabled.");
#endif
int highI = (int)pg.size() -1;
if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI;
while (highI > 0 && (pg[highI] == pg[highI -1])) --highI;
if ((Closed && highI < 2) || (!Closed && highI < 1)) return false;
//create a new edge array ...
TEdge *edges = new TEdge [highI +1];
bool IsFlat = true;
//1. Basic (first) edge initialization ...
try
{
edges[1].Curr = pg[1];
RangeTest(pg[0], m_UseFullRange);
RangeTest(pg[highI], m_UseFullRange);
InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]);
InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]);
for (int i = highI - 1; i >= 1; --i)
{
RangeTest(pg[i], m_UseFullRange);
InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]);
}
}
catch(std::exception const&)
{
delete [] edges;
throw; //range test fails
}
TEdge *eStart = &edges[0];
//2. Remove duplicate vertices, and (when closed) collinear edges ...
TEdge *E = eStart, *eLoopStop = eStart;
for (;;)
{
//nb: allows matching start and end points when not Closed ...
if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart))
{
if (E == E->Next) break;
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
eLoopStop = E;
continue;
}
if (E->Prev == E->Next)
break; //only two vertices
else if (Closed &&
SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) &&
(!m_PreserveCollinear ||
!Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr)))
{
//Collinear edges are allowed for open paths but in closed paths
//the default is to merge adjacent collinear edges into a single edge.
//However, if the PreserveCollinear property is enabled, only overlapping
//collinear edges (ie spikes) will be removed from closed paths.
if (E == eStart) eStart = E->Next;
E = RemoveEdge(E);
E = E->Prev;
eLoopStop = E;
continue;
}
E = E->Next;
if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break;
}
if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next)))
{
delete [] edges;
return false;
}
if (!Closed)
{
m_HasOpenPaths = true;
eStart->Prev->OutIdx = Skip;
}
//3. Do second stage of edge initialization ...
E = eStart;
do
{
InitEdge2(*E, PolyTyp);
E = E->Next;
if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false;
}
while (E != eStart);
//4. Finally, add edge bounds to LocalMinima list ...
//Totally flat paths must be handled differently when adding them
//to LocalMinima list to avoid endless loops etc ...
if (IsFlat)
{
if (Closed)
{
delete [] edges;
return false;
}
E->Prev->OutIdx = Skip;
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
locMin.LeftBound = 0;
locMin.RightBound = E;
locMin.RightBound->Side = esRight;
locMin.RightBound->WindDelta = 0;
for (;;)
{
if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E);
if (E->Next->OutIdx == Skip) break;
E->NextInLML = E->Next;
E = E->Next;
}
m_MinimaList.push_back(locMin);
m_edges.push_back(edges);
return true;
}
m_edges.push_back(edges);
bool leftBoundIsForward;
TEdge* EMin = 0;
//workaround to avoid an endless loop in the while loop below when
//open paths have matching start and end points ...
if (E->Prev->Bot == E->Prev->Top) E = E->Next;
for (;;)
{
E = FindNextLocMin(E);
if (E == EMin) break;
else if (!EMin) EMin = E;
//E and E.Prev now share a local minima (left aligned if horizontal).
//Compare their slopes to find which starts which bound ...
MinimaList::value_type locMin;
locMin.Y = E->Bot.Y;
if (E->Dx < E->Prev->Dx)
{
locMin.LeftBound = E->Prev;
locMin.RightBound = E;
leftBoundIsForward = false; //Q.nextInLML = Q.prev
} else
{
locMin.LeftBound = E;
locMin.RightBound = E->Prev;
leftBoundIsForward = true; //Q.nextInLML = Q.next
}
locMin.LeftBound->Side = esLeft;
locMin.RightBound->Side = esRight;
if (!Closed) locMin.LeftBound->WindDelta = 0;
else if (locMin.LeftBound->Next == locMin.RightBound)
locMin.LeftBound->WindDelta = -1;
else locMin.LeftBound->WindDelta = 1;
locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta;
E = ProcessBound(locMin.LeftBound, leftBoundIsForward);
if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward);
TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward);
if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward);
if (locMin.LeftBound->OutIdx == Skip)
locMin.LeftBound = 0;
else if (locMin.RightBound->OutIdx == Skip)
locMin.RightBound = 0;
m_MinimaList.push_back(locMin);
if (!leftBoundIsForward) E = E2;
}
return true;
}
//------------------------------------------------------------------------------
bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed)
{
bool result = false;
for (Paths::size_type i = 0; i < ppg.size(); ++i)
if (AddPath(ppg[i], PolyTyp, Closed)) result = true;
return result;
}
//------------------------------------------------------------------------------
void ClipperBase::Clear()
{
DisposeLocalMinimaList();
for (EdgeList::size_type i = 0; i < m_edges.size(); ++i)
{
//for each edge array in turn, find the first used edge and
//check for and remove any hiddenPts in each edge in the array.
TEdge* edges = m_edges[i];
delete [] edges;
}
m_edges.clear();
m_UseFullRange = false;
m_HasOpenPaths = false;
}
//------------------------------------------------------------------------------
void ClipperBase::Reset()
{
m_CurrentLM = m_MinimaList.begin();
if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process
std::stable_sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter());
//reset all edges ...
for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
{
TEdge* e = lm->LeftBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esLeft;
e->OutIdx = Unassigned;
}
e = lm->RightBound;
if (e)
{
e->Curr = e->Bot;
e->Side = esRight;
e->OutIdx = Unassigned;
}
}
}
//------------------------------------------------------------------------------
void ClipperBase::DisposeLocalMinimaList()
{
m_MinimaList.clear();
m_CurrentLM = m_MinimaList.begin();
}
//------------------------------------------------------------------------------
void ClipperBase::PopLocalMinima()
{
if (m_CurrentLM == m_MinimaList.end()) return;
++m_CurrentLM;
}
//------------------------------------------------------------------------------
IntRect ClipperBase::GetBounds()
{
IntRect result;
MinimaList::iterator lm = m_MinimaList.begin();
if (lm == m_MinimaList.end())
{
result.left = result.top = result.right = result.bottom = 0;
return result;
}
result.left = lm->LeftBound->Bot.X;
result.top = lm->LeftBound->Bot.Y;
result.right = lm->LeftBound->Bot.X;
result.bottom = lm->LeftBound->Bot.Y;
while (lm != m_MinimaList.end())
{
result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y);
TEdge* e = lm->LeftBound;
for (;;) {
TEdge* bottomE = e;
while (e->NextInLML)
{
if (e->Bot.X < result.left) result.left = e->Bot.X;
if (e->Bot.X > result.right) result.right = e->Bot.X;
e = e->NextInLML;
}
result.left = std::min(result.left, e->Bot.X);
result.right = std::max(result.right, e->Bot.X);
result.left = std::min(result.left, e->Top.X);
result.right = std::max(result.right, e->Top.X);
result.top = std::min(result.top, e->Top.Y);
if (bottomE == lm->LeftBound) e = lm->RightBound;
else break;
}
++lm;
}
return result;
}
//------------------------------------------------------------------------------
// TClipper methods ...
//------------------------------------------------------------------------------
Clipper::Clipper(int initOptions) : ClipperBase() //constructor
{
m_ActiveEdges = 0;
m_SortedEdges = 0;
m_ExecuteLocked = false;
m_UseFullRange = false;
m_ReverseOutput = ((initOptions & ioReverseSolution) != 0);
m_StrictSimple = ((initOptions & ioStrictlySimple) != 0);
m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0);
m_HasOpenPaths = false;
#ifdef use_xyz
m_ZFill = 0;
#endif
}
//------------------------------------------------------------------------------
Clipper::~Clipper() //destructor
{
Clear();
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::ZFillFunction(ZFillCallback zFillFunc)
{
m_ZFill = zFillFunc;
}
//------------------------------------------------------------------------------
#endif
void Clipper::Reset()
{
ClipperBase::Reset();
m_Scanbeam = ScanbeamList();
m_Maxima = MaximaList();
m_ActiveEdges = 0;
m_SortedEdges = 0;
for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm)
InsertScanbeam(lm->Y);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType)
{
return Execute(clipType, solution, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType)
{
return Execute(clipType, polytree, fillType, fillType);
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, Paths &solution,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
if (m_HasOpenPaths)
throw clipperException("Error: PolyTree struct is needed for open path clipping.");
m_ExecuteLocked = true;
solution.resize(0);
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = false;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult(solution);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
bool Clipper::Execute(ClipType clipType, PolyTree& polytree,
PolyFillType subjFillType, PolyFillType clipFillType)
{
if( m_ExecuteLocked ) return false;
m_ExecuteLocked = true;
m_SubjFillType = subjFillType;
m_ClipFillType = clipFillType;
m_ClipType = clipType;
m_UsingPolyTree = true;
bool succeeded = ExecuteInternal();
if (succeeded) BuildResult2(polytree);
DisposeAllOutRecs();
m_ExecuteLocked = false;
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::FixHoleLinkage(OutRec &outrec)
{
//skip OutRecs that (a) contain outermost polygons or
//(b) already have the correct owner/child linkage ...
if (!outrec.FirstLeft ||
(outrec.IsHole != outrec.FirstLeft->IsHole &&
outrec.FirstLeft->Pts)) return;
OutRec* orfl = outrec.FirstLeft;
while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts))
orfl = orfl->FirstLeft;
outrec.FirstLeft = orfl;
}
//------------------------------------------------------------------------------
bool Clipper::ExecuteInternal()
{
bool succeeded = true;
try {
Reset();
if (m_CurrentLM == m_MinimaList.end()) return true;
cInt botY = PopScanbeam();
do {
InsertLocalMinimaIntoAEL(botY);
ProcessHorizontals();
ClearGhostJoins();
if (m_Scanbeam.empty()) break;
cInt topY = PopScanbeam();
succeeded = ProcessIntersections(topY);
if (!succeeded) break;
ProcessEdgesAtTopOfScanbeam(topY);
botY = topY;
} while (!m_Scanbeam.empty() || m_CurrentLM != m_MinimaList.end());
}
catch(std::exception const&)
{
succeeded = false;
}
if (succeeded)
{
//fix orientations ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts || outRec->IsOpen) continue;
if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0))
ReversePolyPtLinks(outRec->Pts);
}
if (!m_Joins.empty()) JoinCommonEdges();
//unfortunately FixupOutPolygon() must be done after JoinCommonEdges()
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec *outRec = m_PolyOuts[i];
if (!outRec->Pts) continue;
if (outRec->IsOpen)
FixupOutPolyline(*outRec);
else
FixupOutPolygon(*outRec);
}
if (m_StrictSimple) DoSimplePolygons();
}
ClearJoins();
ClearGhostJoins();
return succeeded;
}
//------------------------------------------------------------------------------
void Clipper::InsertScanbeam(const cInt Y)
{
m_Scanbeam.push(Y);
}
//------------------------------------------------------------------------------
cInt Clipper::PopScanbeam()
{
const cInt Y = m_Scanbeam.top();
m_Scanbeam.pop();
while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates.
return Y;
}
//------------------------------------------------------------------------------
void Clipper::DisposeAllOutRecs(){
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
DisposeOutRec(i);
m_PolyOuts.clear();
}
//------------------------------------------------------------------------------
void Clipper::DisposeOutRec(PolyOutList::size_type index)
{
OutRec *outRec = m_PolyOuts[index];
if (outRec->Pts) DisposeOutPts(outRec->Pts);
delete outRec;
m_PolyOuts[index] = 0;
}
//------------------------------------------------------------------------------
void Clipper::SetWindingCount(TEdge &edge)
{
TEdge *e = edge.PrevInAEL;
//find the edge of the same polytype that immediately preceeds 'edge' in AEL
while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL;
if (!e)
{
edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
edge.WindCnt2 = 0;
e = m_ActiveEdges; //ie get ready to calc WindCnt2
}
else if (edge.WindDelta == 0 && m_ClipType != ctUnion)
{
edge.WindCnt = 1;
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else if (IsEvenOddFillType(edge))
{
//EvenOdd filling ...
if (edge.WindDelta == 0)
{
//are we inside a subj polygon ...
bool Inside = true;
TEdge *e2 = e->PrevInAEL;
while (e2)
{
if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0)
Inside = !Inside;
e2 = e2->PrevInAEL;
}
edge.WindCnt = (Inside ? 0 : 1);
}
else
{
edge.WindCnt = edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
else
{
//nonZero, Positive or Negative filling ...
if (e->WindCnt * e->WindDelta < 0)
{
//prev edge is 'decreasing' WindCount (WC) toward zero
//so we're outside the previous polygon ...
if (Abs(e->WindCnt) > 1)
{
//outside prev poly but still inside another.
//when reversing direction of prev poly use the same WC
if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise continue to 'decrease' WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
else
//now outside all polys of same polytype so set own WC ...
edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta);
} else
{
//prev edge is 'increasing' WindCount (WC) away from zero
//so we're inside the previous polygon ...
if (edge.WindDelta == 0)
edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1);
//if wind direction is reversing prev then use same WC
else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt;
//otherwise add to WC ...
else edge.WindCnt = e->WindCnt + edge.WindDelta;
}
edge.WindCnt2 = e->WindCnt2;
e = e->NextInAEL; //ie get ready to calc WindCnt2
}
//update WindCnt2 ...
if (IsEvenOddAltFillType(edge))
{
//EvenOdd filling ...
while (e != &edge)
{
if (e->WindDelta != 0)
edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0);
e = e->NextInAEL;
}
} else
{
//nonZero, Positive or Negative filling ...
while ( e != &edge )
{
edge.WindCnt2 += e->WindDelta;
e = e->NextInAEL;
}
}
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_SubjFillType == pftEvenOdd; else
return m_ClipFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const
{
if (edge.PolyTyp == ptSubject)
return m_ClipFillType == pftEvenOdd; else
return m_SubjFillType == pftEvenOdd;
}
//------------------------------------------------------------------------------
bool Clipper::IsContributing(const TEdge& edge) const
{
PolyFillType pft, pft2;
if (edge.PolyTyp == ptSubject)
{
pft = m_SubjFillType;
pft2 = m_ClipFillType;
} else
{
pft = m_ClipFillType;
pft2 = m_SubjFillType;
}
switch(pft)
{
case pftEvenOdd:
//return false if a subj line has been flagged as inside a subj polygon
if (edge.WindDelta == 0 && edge.WindCnt != 1) return false;
break;
case pftNonZero:
if (Abs(edge.WindCnt) != 1) return false;
break;
case pftPositive:
if (edge.WindCnt != 1) return false;
break;
default: //pftNegative
if (edge.WindCnt != -1) return false;
}
switch(m_ClipType)
{
case ctIntersection:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctUnion:
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
break;
case ctDifference:
if (edge.PolyTyp == ptSubject)
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 != 0);
case pftPositive:
return (edge.WindCnt2 > 0);
default:
return (edge.WindCnt2 < 0);
}
break;
case ctXor:
if (edge.WindDelta == 0) //XOr always contributing unless open
switch(pft2)
{
case pftEvenOdd:
case pftNonZero:
return (edge.WindCnt2 == 0);
case pftPositive:
return (edge.WindCnt2 <= 0);
default:
return (edge.WindCnt2 >= 0);
}
else
return true;
break;
default:
return true;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
OutPt* result;
TEdge *e, *prevE;
if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx ))
{
result = AddOutPt(e1, Pt);
e2->OutIdx = e1->OutIdx;
e1->Side = esLeft;
e2->Side = esRight;
e = e1;
if (e->PrevInAEL == e2)
prevE = e2->PrevInAEL;
else
prevE = e->PrevInAEL;
} else
{
result = AddOutPt(e2, Pt);
e1->OutIdx = e2->OutIdx;
e1->Side = esRight;
e2->Side = esLeft;
e = e2;
if (e->PrevInAEL == e1)
prevE = e1->PrevInAEL;
else
prevE = e->PrevInAEL;
}
if (prevE && prevE->OutIdx >= 0 &&
(TopX(*prevE, Pt.Y) == TopX(*e, Pt.Y)) &&
SlopesEqual(*e, *prevE, m_UseFullRange) &&
(e->WindDelta != 0) && (prevE->WindDelta != 0))
{
OutPt* outPt = AddOutPt(prevE, Pt);
AddJoin(result, outPt, e->Top);
}
return result;
}
//------------------------------------------------------------------------------
void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt)
{
AddOutPt( e1, Pt );
if (e2->WindDelta == 0) AddOutPt(e2, Pt);
if( e1->OutIdx == e2->OutIdx )
{
e1->OutIdx = Unassigned;
e2->OutIdx = Unassigned;
}
else if (e1->OutIdx < e2->OutIdx)
AppendPolygon(e1, e2);
else
AppendPolygon(e2, e1);
}
//------------------------------------------------------------------------------
void Clipper::AddEdgeToSEL(TEdge *edge)
{
//SEL pointers in PEdge are reused to build a list of horizontal edges.
//However, we don't need to worry about order with horizontal edge processing.
if( !m_SortedEdges )
{
m_SortedEdges = edge;
edge->PrevInSEL = 0;
edge->NextInSEL = 0;
}
else
{
edge->NextInSEL = m_SortedEdges;
edge->PrevInSEL = 0;
m_SortedEdges->PrevInSEL = edge;
m_SortedEdges = edge;
}
}
//------------------------------------------------------------------------------
void Clipper::CopyAELToSEL()
{
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while ( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op1;
j->OutPt2 = op2;
j->OffPt = OffPt;
m_Joins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::ClearJoins()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
delete m_Joins[i];
m_Joins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::ClearGhostJoins()
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++)
delete m_GhostJoins[i];
m_GhostJoins.resize(0);
}
//------------------------------------------------------------------------------
void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt)
{
Join* j = new Join;
j->OutPt1 = op;
j->OutPt2 = 0;
j->OffPt = OffPt;
m_GhostJoins.push_back(j);
}
//------------------------------------------------------------------------------
void Clipper::InsertLocalMinimaIntoAEL(const cInt botY)
{
while (m_CurrentLM != m_MinimaList.end() && (m_CurrentLM->Y == botY))
{
TEdge* lb = m_CurrentLM->LeftBound;
TEdge* rb = m_CurrentLM->RightBound;
PopLocalMinima();
OutPt *Op1 = 0;
if (!lb)
{
//nb: don't insert LB into either AEL or SEL
InsertEdgeIntoAEL(rb, 0);
SetWindingCount(*rb);
if (IsContributing(*rb))
Op1 = AddOutPt(rb, rb->Bot);
}
else if (!rb)
{
InsertEdgeIntoAEL(lb, 0);
SetWindingCount(*lb);
if (IsContributing(*lb))
Op1 = AddOutPt(lb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
else
{
InsertEdgeIntoAEL(lb, 0);
InsertEdgeIntoAEL(rb, lb);
SetWindingCount( *lb );
rb->WindCnt = lb->WindCnt;
rb->WindCnt2 = lb->WindCnt2;
if (IsContributing(*lb))
Op1 = AddLocalMinPoly(lb, rb, lb->Bot);
InsertScanbeam(lb->Top.Y);
}
if (rb)
{
if(IsHorizontal(*rb)) AddEdgeToSEL(rb);
else InsertScanbeam( rb->Top.Y );
}
if (!lb || !rb) continue;
//if any output polygons share an edge, they'll need joining later ...
if (Op1 && IsHorizontal(*rb) &&
!m_GhostJoins.empty() && (rb->WindDelta != 0))
{
for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i)
{
Join* jr = m_GhostJoins[i];
//if the horizontal Rb and a 'ghost' horizontal overlap, then convert
//the 'ghost' join to a real join ready for later ...
if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X))
AddJoin(jr->OutPt1, Op1, jr->OffPt);
}
}
if (lb->OutIdx >= 0 && lb->PrevInAEL &&
lb->PrevInAEL->Curr.X == lb->Bot.X &&
lb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(*lb->PrevInAEL, *lb, m_UseFullRange) &&
(lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot);
AddJoin(Op1, Op2, lb->Top);
}
if(lb->NextInAEL != rb)
{
if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 &&
SlopesEqual(*rb->PrevInAEL, *rb, m_UseFullRange) &&
(rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0))
{
OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot);
AddJoin(Op1, Op2, rb->Top);
}
TEdge* e = lb->NextInAEL;
if (e)
{
while( e != rb )
{
//nb: For calculating winding counts etc, IntersectEdges() assumes
//that param1 will be to the Right of param2 ABOVE the intersection ...
IntersectEdges(rb , e , lb->Curr); //order important here
e = e->NextInAEL;
}
}
}
}
}
//------------------------------------------------------------------------------
void Clipper::DeleteFromAEL(TEdge *e)
{
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if( !AelPrev && !AelNext && (e != m_ActiveEdges) ) return; //already deleted
if( AelPrev ) AelPrev->NextInAEL = AelNext;
else m_ActiveEdges = AelNext;
if( AelNext ) AelNext->PrevInAEL = AelPrev;
e->NextInAEL = 0;
e->PrevInAEL = 0;
}
//------------------------------------------------------------------------------
void Clipper::DeleteFromSEL(TEdge *e)
{
TEdge* SelPrev = e->PrevInSEL;
TEdge* SelNext = e->NextInSEL;
if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted
if( SelPrev ) SelPrev->NextInSEL = SelNext;
else m_SortedEdges = SelNext;
if( SelNext ) SelNext->PrevInSEL = SelPrev;
e->NextInSEL = 0;
e->PrevInSEL = 0;
}
//------------------------------------------------------------------------------
#ifdef use_xyz
void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2)
{
if (pt.Z != 0 || !m_ZFill) return;
else if (pt == e1.Bot) pt.Z = e1.Bot.Z;
else if (pt == e1.Top) pt.Z = e1.Top.Z;
else if (pt == e2.Bot) pt.Z = e2.Bot.Z;
else if (pt == e2.Top) pt.Z = e2.Top.Z;
else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt);
}
//------------------------------------------------------------------------------
#endif
void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt)
{
bool e1Contributing = ( e1->OutIdx >= 0 );
bool e2Contributing = ( e2->OutIdx >= 0 );
#ifdef use_xyz
SetZ(Pt, *e1, *e2);
#endif
#ifdef use_lines
//if either edge is on an OPEN path ...
if (e1->WindDelta == 0 || e2->WindDelta == 0)
{
//ignore subject-subject open path intersections UNLESS they
//are both open paths, AND they are both 'contributing maximas' ...
if (e1->WindDelta == 0 && e2->WindDelta == 0) return;
//if intersecting a subj line with a subj poly ...
else if (e1->PolyTyp == e2->PolyTyp &&
e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion)
{
if (e1->WindDelta == 0)
{
if (e2Contributing)
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
}
else
{
if (e1Contributing)
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
}
else if (e1->PolyTyp != e2->PolyTyp)
{
//toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ...
if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 &&
(m_ClipType != ctUnion || e2->WindCnt2 == 0))
{
AddOutPt(e1, Pt);
if (e1Contributing) e1->OutIdx = Unassigned;
}
else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) &&
(m_ClipType != ctUnion || e1->WindCnt2 == 0))
{
AddOutPt(e2, Pt);
if (e2Contributing) e2->OutIdx = Unassigned;
}
}
return;
}
#endif
//update winding counts...
//assumes that e1 will be to the Right of e2 ABOVE the intersection
if ( e1->PolyTyp == e2->PolyTyp )
{
if ( IsEvenOddFillType( *e1) )
{
int oldE1WindCnt = e1->WindCnt;
e1->WindCnt = e2->WindCnt;
e2->WindCnt = oldE1WindCnt;
} else
{
if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt;
else e1->WindCnt += e2->WindDelta;
if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt;
else e2->WindCnt -= e1->WindDelta;
}
} else
{
if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta;
else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0;
if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta;
else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0;
}
PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2;
if (e1->PolyTyp == ptSubject)
{
e1FillType = m_SubjFillType;
e1FillType2 = m_ClipFillType;
} else
{
e1FillType = m_ClipFillType;
e1FillType2 = m_SubjFillType;
}
if (e2->PolyTyp == ptSubject)
{
e2FillType = m_SubjFillType;
e2FillType2 = m_ClipFillType;
} else
{
e2FillType = m_ClipFillType;
e2FillType2 = m_SubjFillType;
}
cInt e1Wc, e2Wc;
switch (e1FillType)
{
case pftPositive: e1Wc = e1->WindCnt; break;
case pftNegative: e1Wc = -e1->WindCnt; break;
default: e1Wc = Abs(e1->WindCnt);
}
switch(e2FillType)
{
case pftPositive: e2Wc = e2->WindCnt; break;
case pftNegative: e2Wc = -e2->WindCnt; break;
default: e2Wc = Abs(e2->WindCnt);
}
if ( e1Contributing && e2Contributing )
{
if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) ||
(e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) )
{
AddLocalMaxPoly(e1, e2, Pt);
}
else
{
AddOutPt(e1, Pt);
AddOutPt(e2, Pt);
SwapSides( *e1 , *e2 );
SwapPolyIndexes( *e1 , *e2 );
}
}
else if ( e1Contributing )
{
if (e2Wc == 0 || e2Wc == 1)
{
AddOutPt(e1, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( e2Contributing )
{
if (e1Wc == 0 || e1Wc == 1)
{
AddOutPt(e2, Pt);
SwapSides(*e1, *e2);
SwapPolyIndexes(*e1, *e2);
}
}
else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1))
{
//neither edge is currently contributing ...
cInt e1Wc2, e2Wc2;
switch (e1FillType2)
{
case pftPositive: e1Wc2 = e1->WindCnt2; break;
case pftNegative : e1Wc2 = -e1->WindCnt2; break;
default: e1Wc2 = Abs(e1->WindCnt2);
}
switch (e2FillType2)
{
case pftPositive: e2Wc2 = e2->WindCnt2; break;
case pftNegative: e2Wc2 = -e2->WindCnt2; break;
default: e2Wc2 = Abs(e2->WindCnt2);
}
if (e1->PolyTyp != e2->PolyTyp)
{
AddLocalMinPoly(e1, e2, Pt);
}
else if (e1Wc == 1 && e2Wc == 1)
switch( m_ClipType ) {
case ctIntersection:
if (e1Wc2 > 0 && e2Wc2 > 0)
AddLocalMinPoly(e1, e2, Pt);
break;
case ctUnion:
if ( e1Wc2 <= 0 && e2Wc2 <= 0 )
AddLocalMinPoly(e1, e2, Pt);
break;
case ctDifference:
if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) ||
((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0)))
AddLocalMinPoly(e1, e2, Pt);
break;
case ctXor:
AddLocalMinPoly(e1, e2, Pt);
}
else
SwapSides( *e1, *e2 );
}
}
//------------------------------------------------------------------------------
void Clipper::SetHoleState(TEdge *e, OutRec *outrec)
{
bool IsHole = false;
TEdge *e2 = e->PrevInAEL;
while (e2)
{
if (e2->OutIdx >= 0 && e2->WindDelta != 0)
{
IsHole = !IsHole;
if (! outrec->FirstLeft)
outrec->FirstLeft = m_PolyOuts[e2->OutIdx];
}
e2 = e2->PrevInAEL;
}
if (IsHole) outrec->IsHole = true;
}
//------------------------------------------------------------------------------
OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2)
{
//work out which polygon fragment has the correct hole state ...
if (!outRec1->BottomPt)
outRec1->BottomPt = GetBottomPt(outRec1->Pts);
if (!outRec2->BottomPt)
outRec2->BottomPt = GetBottomPt(outRec2->Pts);
OutPt *OutPt1 = outRec1->BottomPt;
OutPt *OutPt2 = outRec2->BottomPt;
if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1;
else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2;
else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1;
else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2;
else if (OutPt1->Next == OutPt1) return outRec2;
else if (OutPt2->Next == OutPt2) return outRec1;
else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1;
else return outRec2;
}
//------------------------------------------------------------------------------
bool Param1RightOfParam2(OutRec* outRec1, OutRec* outRec2)
{
do
{
outRec1 = outRec1->FirstLeft;
if (outRec1 == outRec2) return true;
} while (outRec1);
return false;
}
//------------------------------------------------------------------------------
OutRec* Clipper::GetOutRec(int Idx)
{
OutRec* outrec = m_PolyOuts[Idx];
while (outrec != m_PolyOuts[outrec->Idx])
outrec = m_PolyOuts[outrec->Idx];
return outrec;
}
//------------------------------------------------------------------------------
void Clipper::AppendPolygon(TEdge *e1, TEdge *e2)
{
//get the start and ends of both output polygons ...
OutRec *outRec1 = m_PolyOuts[e1->OutIdx];
OutRec *outRec2 = m_PolyOuts[e2->OutIdx];
OutRec *holeStateRec;
if (Param1RightOfParam2(outRec1, outRec2))
holeStateRec = outRec2;
else if (Param1RightOfParam2(outRec2, outRec1))
holeStateRec = outRec1;
else
holeStateRec = GetLowermostRec(outRec1, outRec2);
//get the start and ends of both output polygons and
//join e2 poly onto e1 poly and delete pointers to e2 ...
OutPt* p1_lft = outRec1->Pts;
OutPt* p1_rt = p1_lft->Prev;
OutPt* p2_lft = outRec2->Pts;
OutPt* p2_rt = p2_lft->Prev;
EdgeSide Side;
//join e2 poly onto e1 poly and delete pointers to e2 ...
if( e1->Side == esLeft )
{
if( e2->Side == esLeft )
{
//z y x a b c
ReversePolyPtLinks(p2_lft);
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
outRec1->Pts = p2_rt;
} else
{
//x y z a b c
p2_rt->Next = p1_lft;
p1_lft->Prev = p2_rt;
p2_lft->Prev = p1_rt;
p1_rt->Next = p2_lft;
outRec1->Pts = p2_lft;
}
Side = esLeft;
} else
{
if( e2->Side == esRight )
{
//a b c z y x
ReversePolyPtLinks(p2_lft);
p1_rt->Next = p2_rt;
p2_rt->Prev = p1_rt;
p2_lft->Next = p1_lft;
p1_lft->Prev = p2_lft;
} else
{
//a b c x y z
p1_rt->Next = p2_lft;
p2_lft->Prev = p1_rt;
p1_lft->Prev = p2_rt;
p2_rt->Next = p1_lft;
}
Side = esRight;
}
outRec1->BottomPt = 0;
if (holeStateRec == outRec2)
{
if (outRec2->FirstLeft != outRec1)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec1->IsHole = outRec2->IsHole;
}
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->FirstLeft = outRec1;
int OKIdx = e1->OutIdx;
int ObsoleteIdx = e2->OutIdx;
e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly
e2->OutIdx = Unassigned;
TEdge* e = m_ActiveEdges;
while( e )
{
if( e->OutIdx == ObsoleteIdx )
{
e->OutIdx = OKIdx;
e->Side = Side;
break;
}
e = e->NextInAEL;
}
outRec2->Idx = outRec1->Idx;
}
//------------------------------------------------------------------------------
OutRec* Clipper::CreateOutRec()
{
OutRec* result = new OutRec;
result->IsHole = false;
result->IsOpen = false;
result->FirstLeft = 0;
result->Pts = 0;
result->BottomPt = 0;
result->PolyNd = 0;
m_PolyOuts.push_back(result);
result->Idx = (int)m_PolyOuts.size()-1;
return result;
}
//------------------------------------------------------------------------------
OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt)
{
if( e->OutIdx < 0 )
{
OutRec *outRec = CreateOutRec();
outRec->IsOpen = (e->WindDelta == 0);
OutPt* newOp = new OutPt;
outRec->Pts = newOp;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = newOp;
newOp->Prev = newOp;
if (!outRec->IsOpen)
SetHoleState(e, outRec);
e->OutIdx = outRec->Idx;
return newOp;
} else
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
//OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most'
OutPt* op = outRec->Pts;
bool ToFront = (e->Side == esLeft);
if (ToFront && (pt == op->Pt)) return op;
else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev;
OutPt* newOp = new OutPt;
newOp->Idx = outRec->Idx;
newOp->Pt = pt;
newOp->Next = op;
newOp->Prev = op->Prev;
newOp->Prev->Next = newOp;
op->Prev = newOp;
if (ToFront) outRec->Pts = newOp;
return newOp;
}
}
//------------------------------------------------------------------------------
OutPt* Clipper::GetLastOutPt(TEdge *e)
{
OutRec *outRec = m_PolyOuts[e->OutIdx];
if (e->Side == esLeft)
return outRec->Pts;
else
return outRec->Pts->Prev;
}
//------------------------------------------------------------------------------
void Clipper::ProcessHorizontals()
{
TEdge* horzEdge = m_SortedEdges;
while(horzEdge)
{
DeleteFromSEL(horzEdge);
ProcessHorizontal(horzEdge);
horzEdge = m_SortedEdges;
}
}
//------------------------------------------------------------------------------
inline bool IsMinima(TEdge *e)
{
return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e);
}
//------------------------------------------------------------------------------
inline bool IsMaxima(TEdge *e, const cInt Y)
{
return e && e->Top.Y == Y && !e->NextInLML;
}
//------------------------------------------------------------------------------
inline bool IsIntermediate(TEdge *e, const cInt Y)
{
return e->Top.Y == Y && e->NextInLML;
}
//------------------------------------------------------------------------------
TEdge *GetMaximaPair(TEdge *e)
{
TEdge* result = 0;
if ((e->Next->Top == e->Top) && !e->Next->NextInLML)
result = e->Next;
else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML)
result = e->Prev;
if (result && (result->OutIdx == Skip ||
//result is false if both NextInAEL & PrevInAEL are nil & not horizontal ...
(result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result))))
return 0;
return result;
}
//------------------------------------------------------------------------------
void Clipper::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2)
{
//check that one or other edge hasn't already been removed from AEL ...
if (Edge1->NextInAEL == Edge1->PrevInAEL ||
Edge2->NextInAEL == Edge2->PrevInAEL) return;
if( Edge1->NextInAEL == Edge2 )
{
TEdge* Next = Edge2->NextInAEL;
if( Next ) Next->PrevInAEL = Edge1;
TEdge* Prev = Edge1->PrevInAEL;
if( Prev ) Prev->NextInAEL = Edge2;
Edge2->PrevInAEL = Prev;
Edge2->NextInAEL = Edge1;
Edge1->PrevInAEL = Edge2;
Edge1->NextInAEL = Next;
}
else if( Edge2->NextInAEL == Edge1 )
{
TEdge* Next = Edge1->NextInAEL;
if( Next ) Next->PrevInAEL = Edge2;
TEdge* Prev = Edge2->PrevInAEL;
if( Prev ) Prev->NextInAEL = Edge1;
Edge1->PrevInAEL = Prev;
Edge1->NextInAEL = Edge2;
Edge2->PrevInAEL = Edge1;
Edge2->NextInAEL = Next;
}
else
{
TEdge* Next = Edge1->NextInAEL;
TEdge* Prev = Edge1->PrevInAEL;
Edge1->NextInAEL = Edge2->NextInAEL;
if( Edge1->NextInAEL ) Edge1->NextInAEL->PrevInAEL = Edge1;
Edge1->PrevInAEL = Edge2->PrevInAEL;
if( Edge1->PrevInAEL ) Edge1->PrevInAEL->NextInAEL = Edge1;
Edge2->NextInAEL = Next;
if( Edge2->NextInAEL ) Edge2->NextInAEL->PrevInAEL = Edge2;
Edge2->PrevInAEL = Prev;
if( Edge2->PrevInAEL ) Edge2->PrevInAEL->NextInAEL = Edge2;
}
if( !Edge1->PrevInAEL ) m_ActiveEdges = Edge1;
else if( !Edge2->PrevInAEL ) m_ActiveEdges = Edge2;
}
//------------------------------------------------------------------------------
void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2)
{
if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return;
if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return;
if( Edge1->NextInSEL == Edge2 )
{
TEdge* Next = Edge2->NextInSEL;
if( Next ) Next->PrevInSEL = Edge1;
TEdge* Prev = Edge1->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge2;
Edge2->PrevInSEL = Prev;
Edge2->NextInSEL = Edge1;
Edge1->PrevInSEL = Edge2;
Edge1->NextInSEL = Next;
}
else if( Edge2->NextInSEL == Edge1 )
{
TEdge* Next = Edge1->NextInSEL;
if( Next ) Next->PrevInSEL = Edge2;
TEdge* Prev = Edge2->PrevInSEL;
if( Prev ) Prev->NextInSEL = Edge1;
Edge1->PrevInSEL = Prev;
Edge1->NextInSEL = Edge2;
Edge2->PrevInSEL = Edge1;
Edge2->NextInSEL = Next;
}
else
{
TEdge* Next = Edge1->NextInSEL;
TEdge* Prev = Edge1->PrevInSEL;
Edge1->NextInSEL = Edge2->NextInSEL;
if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1;
Edge1->PrevInSEL = Edge2->PrevInSEL;
if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1;
Edge2->NextInSEL = Next;
if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2;
Edge2->PrevInSEL = Prev;
if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2;
}
if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1;
else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2;
}
//------------------------------------------------------------------------------
TEdge* GetNextInAEL(TEdge *e, Direction dir)
{
return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL;
}
//------------------------------------------------------------------------------
void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right)
{
if (HorzEdge.Bot.X < HorzEdge.Top.X)
{
Left = HorzEdge.Bot.X;
Right = HorzEdge.Top.X;
Dir = dLeftToRight;
} else
{
Left = HorzEdge.Top.X;
Right = HorzEdge.Bot.X;
Dir = dRightToLeft;
}
}
//------------------------------------------------------------------------
/*******************************************************************************
* Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or *
* Bottom of a scanbeam) are processed as if layered. The order in which HEs *
* are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] *
* (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), *
* and with other non-horizontal edges [*]. Once these intersections are *
* processed, intermediate HEs then 'promote' the Edge above (NextInLML) into *
* the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. *
*******************************************************************************/
void Clipper::ProcessHorizontal(TEdge *horzEdge)
{
Direction dir;
cInt horzLeft, horzRight;
bool IsOpen = (horzEdge->OutIdx >= 0 && m_PolyOuts[horzEdge->OutIdx]->IsOpen);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
TEdge* eLastHorz = horzEdge, *eMaxPair = 0;
while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML))
eLastHorz = eLastHorz->NextInLML;
if (!eLastHorz->NextInLML)
eMaxPair = GetMaximaPair(eLastHorz);
MaximaList::const_iterator maxIt;
MaximaList::const_reverse_iterator maxRit;
if (!m_Maxima.empty())
{
//get the first maxima in range (X) ...
if (dir == dLeftToRight)
{
maxIt = m_Maxima.begin();
while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++;
if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
maxIt = m_Maxima.end();
}
else
{
maxRit = m_Maxima.rbegin();
while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++;
if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
maxRit = m_Maxima.rend();
}
}
OutPt* op1 = 0;
for (;;) //loop through consec. horizontal edges
{
bool IsLastHorz = (horzEdge == eLastHorz);
TEdge* e = GetNextInAEL(horzEdge, dir);
while(e)
{
//this code block inserts extra coords into horizontal edges (in output
//polygons) whereever maxima touch these horizontal edges. This helps
//'simplifying' polygons (ie if the Simplify property is set).
if (!m_Maxima.empty())
{
if (dir == dLeftToRight)
{
while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
maxIt++;
}
}
else
{
while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X)
{
if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
maxRit++;
}
}
};
if ((dir == dLeftToRight && e->Curr.X > horzRight) ||
(dir == dRightToLeft && e->Curr.X < horzLeft)) break;
//Also break if we've got to the end of an intermediate horizontal edge ...
//nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal.
if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML &&
e->Dx < horzEdge->NextInLML->Dx) break;
if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times
{
op1 = AddOutPt(horzEdge, e->Curr);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Bot);
}
//OK, so far we're still in range of the horizontal Edge but make sure
//we're at the last of consec. horizontals when matching with eMaxPair
if(e == eMaxPair && IsLastHorz)
{
if (horzEdge->OutIdx >= 0)
AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top);
DeleteFromAEL(horzEdge);
DeleteFromAEL(eMaxPair);
return;
}
if(dir == dLeftToRight)
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges(horzEdge, e, Pt);
}
else
{
IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y);
IntersectEdges( e, horzEdge, Pt);
}
TEdge* eNext = GetNextInAEL(e, dir);
SwapPositionsInAEL( horzEdge, e );
e = eNext;
} //end while(e)
//Break out of loop if HorzEdge.NextInLML is not also horizontal ...
if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break;
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot);
GetHorzDirection(*horzEdge, dir, horzLeft, horzRight);
} //end for (;;)
if (horzEdge->OutIdx >= 0 && !op1)
{
op1 = GetLastOutPt(horzEdge);
TEdge* eNextHorz = m_SortedEdges;
while (eNextHorz)
{
if (eNextHorz->OutIdx >= 0 &&
HorzSegmentsOverlap(horzEdge->Bot.X,
horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X))
{
OutPt* op2 = GetLastOutPt(eNextHorz);
AddJoin(op2, op1, eNextHorz->Top);
}
eNextHorz = eNextHorz->NextInSEL;
}
AddGhostJoin(op1, horzEdge->Top);
}
if (horzEdge->NextInLML)
{
if(horzEdge->OutIdx >= 0)
{
op1 = AddOutPt( horzEdge, horzEdge->Top);
UpdateEdgeIntoAEL(horzEdge);
if (horzEdge->WindDelta == 0) return;
//nb: HorzEdge is no longer horizontal here
TEdge* ePrev = horzEdge->PrevInAEL;
TEdge* eNext = horzEdge->NextInAEL;
if (ePrev && ePrev->Curr.X == horzEdge->Bot.X &&
ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 &&
(ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(*horzEdge, *ePrev, m_UseFullRange)))
{
OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
else if (eNext && eNext->Curr.X == horzEdge->Bot.X &&
eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(*horzEdge, *eNext, m_UseFullRange))
{
OutPt* op2 = AddOutPt(eNext, horzEdge->Bot);
AddJoin(op1, op2, horzEdge->Top);
}
}
else
UpdateEdgeIntoAEL(horzEdge);
}
else
{
if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top);
DeleteFromAEL(horzEdge);
}
}
//------------------------------------------------------------------------------
void Clipper::UpdateEdgeIntoAEL(TEdge *&e)
{
if( !e->NextInLML )
throw clipperException("UpdateEdgeIntoAEL: invalid call");
e->NextInLML->OutIdx = e->OutIdx;
TEdge* AelPrev = e->PrevInAEL;
TEdge* AelNext = e->NextInAEL;
if (AelPrev) AelPrev->NextInAEL = e->NextInLML;
else m_ActiveEdges = e->NextInLML;
if (AelNext) AelNext->PrevInAEL = e->NextInLML;
e->NextInLML->Side = e->Side;
e->NextInLML->WindDelta = e->WindDelta;
e->NextInLML->WindCnt = e->WindCnt;
e->NextInLML->WindCnt2 = e->WindCnt2;
e = e->NextInLML;
e->Curr = e->Bot;
e->PrevInAEL = AelPrev;
e->NextInAEL = AelNext;
if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y);
}
//------------------------------------------------------------------------------
bool Clipper::ProcessIntersections(const cInt topY)
{
if( !m_ActiveEdges ) return true;
try {
BuildIntersectList(topY);
size_t IlSize = m_IntersectList.size();
if (IlSize == 0) return true;
if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList();
else return false;
}
catch(std::exception const& ex)
{
m_SortedEdges = 0;
DisposeIntersectNodes();
throw clipperException((std::string("ProcessIntersections error ") + ex.what()).c_str());
}
m_SortedEdges = 0;
return true;
}
//------------------------------------------------------------------------------
void Clipper::DisposeIntersectNodes()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i )
delete m_IntersectList[i];
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
void Clipper::BuildIntersectList(const cInt topY)
{
if ( !m_ActiveEdges ) return;
//prepare for sorting ...
TEdge* e = m_ActiveEdges;
m_SortedEdges = e;
while( e )
{
e->PrevInSEL = e->PrevInAEL;
e->NextInSEL = e->NextInAEL;
e->Curr.X = TopX( *e, topY );
e = e->NextInAEL;
}
//bubblesort ...
bool isModified;
do
{
isModified = false;
e = m_SortedEdges;
while( e->NextInSEL )
{
TEdge *eNext = e->NextInSEL;
IntPoint Pt;
if(e->Curr.X > eNext->Curr.X)
{
IntersectPoint(*e, *eNext, Pt);
IntersectNode * newNode = new IntersectNode;
newNode->Edge1 = e;
newNode->Edge2 = eNext;
newNode->Pt = Pt;
m_IntersectList.push_back(newNode);
SwapPositionsInSEL(e, eNext);
isModified = true;
}
else
e = eNext;
}
if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0;
else break;
}
while ( isModified );
m_SortedEdges = 0; //important
}
//------------------------------------------------------------------------------
void Clipper::ProcessIntersectList()
{
for (size_t i = 0; i < m_IntersectList.size(); ++i)
{
IntersectNode* iNode = m_IntersectList[i];
{
IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt);
SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 );
}
delete iNode;
}
m_IntersectList.clear();
}
//------------------------------------------------------------------------------
bool IntersectListSort(IntersectNode* node1, IntersectNode* node2)
{
return node2->Pt.Y < node1->Pt.Y;
}
//------------------------------------------------------------------------------
inline bool EdgesAdjacent(const IntersectNode &inode)
{
return (inode.Edge1->NextInSEL == inode.Edge2) ||
(inode.Edge1->PrevInSEL == inode.Edge2);
}
//------------------------------------------------------------------------------
bool Clipper::FixupIntersectionOrder()
{
//pre-condition: intersections are sorted Bottom-most first.
//Now it's crucial that intersections are made only between adjacent edges,
//so to ensure this the order of intersections may need adjusting ...
CopyAELToSEL();
std::stable_sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort);
size_t cnt = m_IntersectList.size();
for (size_t i = 0; i < cnt; ++i)
{
if (!EdgesAdjacent(*m_IntersectList[i]))
{
size_t j = i + 1;
while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++;
if (j == cnt) return false;
std::swap(m_IntersectList[i], m_IntersectList[j]);
}
SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2);
}
return true;
}
//------------------------------------------------------------------------------
void Clipper::DoMaxima(TEdge *e)
{
TEdge* eMaxPair = GetMaximaPair(e);
if (!eMaxPair)
{
if (e->OutIdx >= 0)
AddOutPt(e, e->Top);
DeleteFromAEL(e);
return;
}
TEdge* eNext = e->NextInAEL;
while(eNext && eNext != eMaxPair)
{
IntersectEdges(e, eNext, e->Top);
SwapPositionsInAEL(e, eNext);
eNext = e->NextInAEL;
}
if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned)
{
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
{
if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top);
DeleteFromAEL(e);
DeleteFromAEL(eMaxPair);
}
#ifdef use_lines
else if (e->WindDelta == 0)
{
if (e->OutIdx >= 0)
{
AddOutPt(e, e->Top);
e->OutIdx = Unassigned;
}
DeleteFromAEL(e);
if (eMaxPair->OutIdx >= 0)
{
AddOutPt(eMaxPair, e->Top);
eMaxPair->OutIdx = Unassigned;
}
DeleteFromAEL(eMaxPair);
}
#endif
else throw clipperException("DoMaxima error");
}
//------------------------------------------------------------------------------
void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY)
{
TEdge* e = m_ActiveEdges;
while( e )
{
//1. process maxima, treating them as if they're 'bent' horizontal edges,
// but exclude maxima with horizontal edges. nb: e can't be a horizontal.
bool IsMaximaEdge = IsMaxima(e, topY);
if(IsMaximaEdge)
{
TEdge* eMaxPair = GetMaximaPair(e);
IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair));
}
if(IsMaximaEdge)
{
if (m_StrictSimple) m_Maxima.push_back(e->Top.X);
TEdge* ePrev = e->PrevInAEL;
DoMaxima(e);
if( !ePrev ) e = m_ActiveEdges;
else e = ePrev->NextInAEL;
}
else
{
//2. promote horizontal edges, otherwise update Curr.X and Curr.Y ...
if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML))
{
UpdateEdgeIntoAEL(e);
if (e->OutIdx >= 0)
AddOutPt(e, e->Bot);
AddEdgeToSEL(e);
}
else
{
e->Curr.X = TopX( *e, topY );
e->Curr.Y = topY;
}
//When StrictlySimple and 'e' is being touched by another edge, then
//make sure both edges have a vertex here ...
if (m_StrictSimple)
{
TEdge* ePrev = e->PrevInAEL;
if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) &&
(ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0))
{
IntPoint pt = e->Curr;
#ifdef use_xyz
SetZ(pt, *ePrev, *e);
#endif
OutPt* op = AddOutPt(ePrev, pt);
OutPt* op2 = AddOutPt(e, pt);
AddJoin(op, op2, pt); //StrictlySimple (type-3) join
}
}
e = e->NextInAEL;
}
}
//3. Process horizontals at the Top of the scanbeam ...
m_Maxima.sort();
ProcessHorizontals();
m_Maxima.clear();
//4. Promote intermediate vertices ...
e = m_ActiveEdges;
while(e)
{
if(IsIntermediate(e, topY))
{
OutPt* op = 0;
if( e->OutIdx >= 0 )
op = AddOutPt(e, e->Top);
UpdateEdgeIntoAEL(e);
//if output polygons share an edge, they'll need joining later ...
TEdge* ePrev = e->PrevInAEL;
TEdge* eNext = e->NextInAEL;
if (ePrev && ePrev->Curr.X == e->Bot.X &&
ePrev->Curr.Y == e->Bot.Y && op &&
ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y &&
SlopesEqual(*e, *ePrev, m_UseFullRange) &&
(e->WindDelta != 0) && (ePrev->WindDelta != 0))
{
OutPt* op2 = AddOutPt(ePrev, e->Bot);
AddJoin(op, op2, e->Top);
}
else if (eNext && eNext->Curr.X == e->Bot.X &&
eNext->Curr.Y == e->Bot.Y && op &&
eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y &&
SlopesEqual(*e, *eNext, m_UseFullRange) &&
(e->WindDelta != 0) && (eNext->WindDelta != 0))
{
OutPt* op2 = AddOutPt(eNext, e->Bot);
AddJoin(op, op2, e->Top);
}
}
e = e->NextInAEL;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolyline(OutRec &outrec)
{
OutPt *pp = outrec.Pts;
OutPt *lastPP = pp->Prev;
while (pp != lastPP)
{
pp = pp->Next;
if (pp->Pt == pp->Prev->Pt)
{
if (pp == lastPP) lastPP = pp->Prev;
OutPt *tmpPP = pp->Prev;
tmpPP->Next = pp->Next;
pp->Next->Prev = tmpPP;
delete pp;
pp = tmpPP;
}
}
if (pp == pp->Prev)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
}
//------------------------------------------------------------------------------
void Clipper::FixupOutPolygon(OutRec &outrec)
{
//FixupOutPolygon() - removes duplicate points and simplifies consecutive
//parallel edges by removing the middle vertex.
OutPt *lastOK = 0;
outrec.BottomPt = 0;
OutPt *pp = outrec.Pts;
bool preserveCol = m_PreserveCollinear || m_StrictSimple;
for (;;)
{
if (pp->Prev == pp || pp->Prev == pp->Next)
{
DisposeOutPts(pp);
outrec.Pts = 0;
return;
}
//test for duplicate points and collinear edges ...
if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) ||
(SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) &&
(!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt))))
{
lastOK = 0;
OutPt *tmp = pp;
pp->Prev->Next = pp->Next;
pp->Next->Prev = pp->Prev;
pp = pp->Prev;
delete tmp;
}
else if (pp == lastOK) break;
else
{
if (!lastOK) lastOK = pp;
pp = pp->Next;
}
}
outrec.Pts = pp;
}
//------------------------------------------------------------------------------
int PointCount(OutPt *Pts)
{
if (!Pts) return 0;
int result = 0;
OutPt* p = Pts;
do
{
result++;
p = p->Next;
}
while (p != Pts);
return result;
}
//------------------------------------------------------------------------------
void Clipper::BuildResult(Paths &polys)
{
polys.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
if (!m_PolyOuts[i]->Pts) continue;
Path pg;
OutPt* p = m_PolyOuts[i]->Pts->Prev;
int cnt = PointCount(p);
if (cnt < 2) continue;
pg.reserve(cnt);
for (int j = 0; j < cnt; ++j)
{
pg.push_back(p->Pt);
p = p->Prev;
}
polys.push_back(pg);
}
}
//------------------------------------------------------------------------------
void Clipper::BuildResult2(PolyTree& polytree)
{
polytree.Clear();
polytree.AllNodes.reserve(m_PolyOuts.size());
//add each output polygon/contour to polytree ...
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
int cnt = PointCount(outRec->Pts);
if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue;
FixHoleLinkage(*outRec);
PolyNode* pn = new PolyNode();
//nb: polytree takes ownership of all the PolyNodes
polytree.AllNodes.push_back(pn);
outRec->PolyNd = pn;
pn->Parent = 0;
pn->Index = 0;
pn->Contour.reserve(cnt);
OutPt *op = outRec->Pts->Prev;
for (int j = 0; j < cnt; j++)
{
pn->Contour.push_back(op->Pt);
op = op->Prev;
}
}
//fixup PolyNode links etc ...
polytree.Childs.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->PolyNd) continue;
if (outRec->IsOpen)
{
outRec->PolyNd->m_IsOpen = true;
polytree.AddChild(*outRec->PolyNd);
}
else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd)
outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd);
else
polytree.AddChild(*outRec->PolyNd);
}
}
//------------------------------------------------------------------------------
void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2)
{
//just swap the contents (because fIntersectNodes is a single-linked-list)
IntersectNode inode = int1; //gets a copy of Int1
int1.Edge1 = int2.Edge1;
int1.Edge2 = int2.Edge2;
int1.Pt = int2.Pt;
int2.Edge1 = inode.Edge1;
int2.Edge2 = inode.Edge2;
int2.Pt = inode.Pt;
}
//------------------------------------------------------------------------------
inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2)
{
if (e2.Curr.X == e1.Curr.X)
{
if (e2.Top.Y > e1.Top.Y)
return e2.Top.X < TopX(e1, e2.Top.Y);
else return e1.Top.X > TopX(e2, e1.Top.Y);
}
else return e2.Curr.X < e1.Curr.X;
}
//------------------------------------------------------------------------------
bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2,
cInt& Left, cInt& Right)
{
if (a1 < a2)
{
if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);}
else {Left = std::max(a1,b2); Right = std::min(a2,b1);}
}
else
{
if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);}
else {Left = std::max(a2,b2); Right = std::min(a1,b1);}
}
return Left < Right;
}
//------------------------------------------------------------------------------
inline void UpdateOutPtIdxs(OutRec& outrec)
{
OutPt* op = outrec.Pts;
do
{
op->Idx = outrec.Idx;
op = op->Prev;
}
while(op != outrec.Pts);
}
//------------------------------------------------------------------------------
void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge)
{
if(!m_ActiveEdges)
{
edge->PrevInAEL = 0;
edge->NextInAEL = 0;
m_ActiveEdges = edge;
}
else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge))
{
edge->PrevInAEL = 0;
edge->NextInAEL = m_ActiveEdges;
m_ActiveEdges->PrevInAEL = edge;
m_ActiveEdges = edge;
}
else
{
if(!startEdge) startEdge = m_ActiveEdges;
while(startEdge->NextInAEL &&
!E2InsertsBeforeE1(*startEdge->NextInAEL , *edge))
startEdge = startEdge->NextInAEL;
edge->NextInAEL = startEdge->NextInAEL;
if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge;
edge->PrevInAEL = startEdge;
startEdge->NextInAEL = edge;
}
}
//----------------------------------------------------------------------
OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
{
OutPt* result = new OutPt;
result->Pt = outPt->Pt;
result->Idx = outPt->Idx;
if (InsertAfter)
{
result->Next = outPt->Next;
result->Prev = outPt;
outPt->Next->Prev = result;
outPt->Next = result;
}
else
{
result->Prev = outPt->Prev;
result->Next = outPt;
outPt->Prev->Next = result;
outPt->Prev = result;
}
return result;
}
//------------------------------------------------------------------------------
bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
const IntPoint Pt, bool DiscardLeft)
{
Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight);
Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight);
if (Dir1 == Dir2) return false;
//When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we
//want Op1b to be on the Right. (And likewise with Op2 and Op2b.)
//So, to facilitate this while inserting Op1b and Op2b ...
//when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b,
//otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.)
if (Dir1 == dLeftToRight)
{
while (op1->Next->Pt.X <= Pt.X &&
op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, !DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, !DiscardLeft);
}
}
else
{
while (op1->Next->Pt.X >= Pt.X &&
op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y)
op1 = op1->Next;
if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next;
op1b = DupOutPt(op1, DiscardLeft);
if (op1b->Pt != Pt)
{
op1 = op1b;
op1->Pt = Pt;
op1b = DupOutPt(op1, DiscardLeft);
}
}
if (Dir2 == dLeftToRight)
{
while (op2->Next->Pt.X <= Pt.X &&
op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, !DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, !DiscardLeft);
};
} else
{
while (op2->Next->Pt.X >= Pt.X &&
op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y)
op2 = op2->Next;
if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next;
op2b = DupOutPt(op2, DiscardLeft);
if (op2b->Pt != Pt)
{
op2 = op2b;
op2->Pt = Pt;
op2b = DupOutPt(op2, DiscardLeft);
};
};
if ((Dir1 == dLeftToRight) == DiscardLeft)
{
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
}
else
{
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
}
return true;
}
//------------------------------------------------------------------------------
bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2)
{
OutPt *op1 = j->OutPt1, *op1b;
OutPt *op2 = j->OutPt2, *op2b;
//There are 3 kinds of joins for output polygons ...
//1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere
//along (horizontal) collinear edges (& Join.OffPt is on the same horizontal).
//2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same
//location at the Bottom of the overlapping segment (& Join.OffPt is above).
//3. StrictSimple joins where edges touch but are not collinear and where
//Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point.
bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y);
if (isHorizontal && (j->OffPt == j->OutPt1->Pt) &&
(j->OffPt == j->OutPt2->Pt))
{
//Strictly Simple join ...
if (outRec1 != outRec2) return false;
op1b = j->OutPt1->Next;
while (op1b != op1 && (op1b->Pt == j->OffPt))
op1b = op1b->Next;
bool reverse1 = (op1b->Pt.Y > j->OffPt.Y);
op2b = j->OutPt2->Next;
while (op2b != op2 && (op2b->Pt == j->OffPt))
op2b = op2b->Next;
bool reverse2 = (op2b->Pt.Y > j->OffPt.Y);
if (reverse1 == reverse2) return false;
if (reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
else if (isHorizontal)
{
//treat horizontal joins differently to non-horizontal joins since with
//them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt
//may be anywhere along the horizontal edge.
op1b = op1;
while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2)
op1 = op1->Prev;
while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2)
op1b = op1b->Next;
if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon'
op2b = op2;
while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b)
op2 = op2->Prev;
while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1)
op2b = op2b->Next;
if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon'
cInt Left, Right;
//Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges
if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right))
return false;
//DiscardLeftSide: when overlapping edges are joined, a spike will created
//which needs to be cleaned up. However, we don't want Op1 or Op2 caught up
//on the discard Side as either may still be needed for other joins ...
IntPoint Pt;
bool DiscardLeftSide;
if (op1->Pt.X >= Left && op1->Pt.X <= Right)
{
Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X);
}
else if (op2->Pt.X >= Left&& op2->Pt.X <= Right)
{
Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X);
}
else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right)
{
Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X;
}
else
{
Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X);
}
j->OutPt1 = op1; j->OutPt2 = op2;
return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide);
} else
{
//nb: For non-horizontal joins ...
// 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y
// 2. Jr.OutPt1.Pt > Jr.OffPt.Y
//make sure the polygons are correctly oriented ...
op1b = op1->Next;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next;
bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange));
if (Reverse1)
{
op1b = op1->Prev;
while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev;
if ((op1b->Pt.Y > op1->Pt.Y) ||
!SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false;
};
op2b = op2->Next;
while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next;
bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange));
if (Reverse2)
{
op2b = op2->Prev;
while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev;
if ((op2b->Pt.Y > op2->Pt.Y) ||
!SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false;
}
if ((op1b == op1) || (op2b == op2) || (op1b == op2b) ||
((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false;
if (Reverse1)
{
op1b = DupOutPt(op1, false);
op2b = DupOutPt(op2, true);
op1->Prev = op2;
op2->Next = op1;
op1b->Next = op2b;
op2b->Prev = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
} else
{
op1b = DupOutPt(op1, true);
op2b = DupOutPt(op2, false);
op1->Next = op2;
op2->Prev = op1;
op1b->Prev = op2b;
op2b->Next = op1b;
j->OutPt1 = op1;
j->OutPt2 = op1b;
return true;
}
}
}
//----------------------------------------------------------------------
static OutRec* ParseFirstLeft(OutRec* FirstLeft)
{
while (FirstLeft && !FirstLeft->Pts)
FirstLeft = FirstLeft->FirstLeft;
return FirstLeft;
}
//------------------------------------------------------------------------------
void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec)
{
//tests if NewOutRec contains the polygon before reassigning FirstLeft
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
if (!outRec->Pts || !outRec->FirstLeft) continue;
OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft);
if (firstLeft == OldOutRec)
{
if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts))
outRec->FirstLeft = NewOutRec;
}
}
}
//----------------------------------------------------------------------
void Clipper::FixupFirstLefts2(OutRec* OldOutRec, OutRec* NewOutRec)
{
//reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{
OutRec* outRec = m_PolyOuts[i];
if (outRec->FirstLeft == OldOutRec) outRec->FirstLeft = NewOutRec;
}
}
//----------------------------------------------------------------------
void Clipper::JoinCommonEdges()
{
for (JoinList::size_type i = 0; i < m_Joins.size(); i++)
{
Join* join = m_Joins[i];
OutRec *outRec1 = GetOutRec(join->OutPt1->Idx);
OutRec *outRec2 = GetOutRec(join->OutPt2->Idx);
if (!outRec1->Pts || !outRec2->Pts) continue;
if (outRec1->IsOpen || outRec2->IsOpen) continue;
//get the polygon fragment with the correct hole state (FirstLeft)
//before calling JoinPoints() ...
OutRec *holeStateRec;
if (outRec1 == outRec2) holeStateRec = outRec1;
else if (Param1RightOfParam2(outRec1, outRec2)) holeStateRec = outRec2;
else if (Param1RightOfParam2(outRec2, outRec1)) holeStateRec = outRec1;
else holeStateRec = GetLowermostRec(outRec1, outRec2);
if (!JoinPoints(join, outRec1, outRec2)) continue;
if (outRec1 == outRec2)
{
//instead of joining two polygons, we've just created a new one by
//splitting one polygon into two.
outRec1->Pts = join->OutPt1;
outRec1->BottomPt = 0;
outRec2 = CreateOutRec();
outRec2->Pts = join->OutPt2;
//update all OutRec2.Pts Idx's ...
UpdateOutPtIdxs(*outRec2);
//We now need to check every OutRec.FirstLeft pointer. If it points
//to OutRec1 it may need to point to OutRec2 instead ...
if (m_UsingPolyTree)
for (PolyOutList::size_type j = 0; j < m_PolyOuts.size() - 1; j++)
{
OutRec* oRec = m_PolyOuts[j];
if (!oRec->Pts || ParseFirstLeft(oRec->FirstLeft) != outRec1 ||
oRec->IsHole == outRec1->IsHole) continue;
if (Poly2ContainsPoly1(oRec->Pts, join->OutPt2))
oRec->FirstLeft = outRec2;
}
if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts))
{
//outRec2 is contained by outRec1 ...
outRec2->IsHole = !outRec1->IsHole;
outRec2->FirstLeft = outRec1;
//fixup FirstLeft pointers that may need reassigning to OutRec1
if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0))
ReversePolyPtLinks(outRec2->Pts);
} else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts))
{
//outRec1 is contained by outRec2 ...
outRec2->IsHole = outRec1->IsHole;
outRec1->IsHole = !outRec2->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
outRec1->FirstLeft = outRec2;
//fixup FirstLeft pointers that may need reassigning to OutRec1
if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2);
if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0))
ReversePolyPtLinks(outRec1->Pts);
}
else
{
//the 2 polygons are completely separate ...
outRec2->IsHole = outRec1->IsHole;
outRec2->FirstLeft = outRec1->FirstLeft;
//fixup FirstLeft pointers that may need reassigning to OutRec2
if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2);
}
} else
{
//joined 2 polygons together ...
outRec2->Pts = 0;
outRec2->BottomPt = 0;
outRec2->Idx = outRec1->Idx;
outRec1->IsHole = holeStateRec->IsHole;
if (holeStateRec == outRec2)
outRec1->FirstLeft = outRec2->FirstLeft;
outRec2->FirstLeft = outRec1;
//fixup FirstLeft pointers that may need reassigning to OutRec1
if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1);
}
}
}
//------------------------------------------------------------------------------
// ClipperOffset support functions ...
//------------------------------------------------------------------------------
DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2)
{
if(pt2.X == pt1.X && pt2.Y == pt1.Y)
return DoublePoint(0, 0);
double Dx = (double)(pt2.X - pt1.X);
double dy = (double)(pt2.Y - pt1.Y);
double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy );
Dx *= f;
dy *= f;
return DoublePoint(dy, -Dx);
}
//------------------------------------------------------------------------------
// ClipperOffset class
//------------------------------------------------------------------------------
ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
{
this->MiterLimit = miterLimit;
this->ArcTolerance = arcTolerance;
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
ClipperOffset::~ClipperOffset()
{
Clear();
}
//------------------------------------------------------------------------------
void ClipperOffset::Clear()
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
delete m_polyNodes.Childs[i];
m_polyNodes.Childs.clear();
m_lowest.X = -1;
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType)
{
int highI = (int)path.size() - 1;
if (highI < 0) return;
PolyNode* newNode = new PolyNode();
newNode->m_jointype = joinType;
newNode->m_endtype = endType;
//strip duplicate points from path and also get index to the lowest point ...
if (endType == etClosedLine || endType == etClosedPolygon)
while (highI > 0 && path[0] == path[highI]) highI--;
newNode->Contour.reserve(highI + 1);
newNode->Contour.push_back(path[0]);
int j = 0, k = 0;
for (int i = 1; i <= highI; i++)
if (newNode->Contour[j] != path[i])
{
j++;
newNode->Contour.push_back(path[i]);
if (path[i].Y > newNode->Contour[k].Y ||
(path[i].Y == newNode->Contour[k].Y &&
path[i].X < newNode->Contour[k].X)) k = j;
}
if (endType == etClosedPolygon && j < 2)
{
delete newNode;
return;
}
m_polyNodes.AddChild(*newNode);
//if this path's lowest pt is lower than all the others then update m_lowest
if (endType != etClosedPolygon) return;
if (m_lowest.X < 0)
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
else
{
IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y];
if (newNode->Contour[k].Y > ip.Y ||
(newNode->Contour[k].Y == ip.Y &&
newNode->Contour[k].X < ip.X))
m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k);
}
}
//------------------------------------------------------------------------------
void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType)
{
for (Paths::size_type i = 0; i < paths.size(); ++i)
AddPath(paths[i], joinType, endType);
}
//------------------------------------------------------------------------------
void ClipperOffset::FixOrientations()
{
//fixup orientations of all closed paths if the orientation of the
//closed path with the lowermost vertex is wrong ...
if (m_lowest.X >= 0 &&
!Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour))
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon ||
(node.m_endtype == etClosedLine && Orientation(node.Contour)))
ReversePath(node.Contour);
}
} else
{
for (int i = 0; i < m_polyNodes.ChildCount(); ++i)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedLine && !Orientation(node.Contour))
ReversePath(node.Contour);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(Paths& solution, double delta)
{
solution.clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
if (!solution.empty()) solution.erase(solution.begin());
}
}
//------------------------------------------------------------------------------
void ClipperOffset::Execute(PolyTree& solution, double delta)
{
solution.Clear();
FixOrientations();
DoOffset(delta);
//now clean up 'corners' ...
Clipper clpr;
clpr.AddPaths(m_destPolys, ptSubject, true);
if (delta > 0)
{
clpr.Execute(ctUnion, solution, pftPositive, pftPositive);
}
else
{
IntRect r = clpr.GetBounds();
Path outer(4);
outer[0] = IntPoint(r.left - 10, r.bottom + 10);
outer[1] = IntPoint(r.right + 10, r.bottom + 10);
outer[2] = IntPoint(r.right + 10, r.top - 10);
outer[3] = IntPoint(r.left - 10, r.top - 10);
clpr.AddPath(outer, ptSubject, true);
clpr.ReverseSolution(true);
clpr.Execute(ctUnion, solution, pftNegative, pftNegative);
//remove the outer PolyNode rectangle ...
if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0)
{
PolyNode* outerNode = solution.Childs[0];
solution.Childs.reserve(outerNode->ChildCount());
solution.Childs[0] = outerNode->Childs[0];
solution.Childs[0]->Parent = outerNode->Parent;
for (int i = 1; i < outerNode->ChildCount(); ++i)
solution.AddChild(*outerNode->Childs[i]);
}
else
solution.Clear();
}
}
//------------------------------------------------------------------------------
void ClipperOffset::DoOffset(double delta)
{
m_destPolys.clear();
m_delta = delta;
//if Zero offset, just copy any CLOSED polygons to m_p and return ...
if (NEAR_ZERO(delta))
{
m_destPolys.reserve(m_polyNodes.ChildCount());
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
if (node.m_endtype == etClosedPolygon)
m_destPolys.push_back(node.Contour);
}
return;
}
//see offset_triginometry3.svg in the documentation folder ...
if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit);
else m_miterLim = 0.5;
double y;
if (ArcTolerance <= 0.0) y = def_arc_tolerance;
else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance)
y = std::fabs(delta) * def_arc_tolerance;
else y = ArcTolerance;
//see offset_triginometry2.svg in the documentation folder ...
double steps = pi / std::acos(1 - y / std::fabs(delta));
if (steps > std::fabs(delta) * pi)
steps = std::fabs(delta) * pi; //ie excessive precision check
m_sin = std::sin(two_pi / steps);
m_cos = std::cos(two_pi / steps);
m_StepsPerRad = steps / two_pi;
if (delta < 0.0) m_sin = -m_sin;
m_destPolys.reserve(m_polyNodes.ChildCount() * 2);
for (int i = 0; i < m_polyNodes.ChildCount(); i++)
{
PolyNode& node = *m_polyNodes.Childs[i];
m_srcPoly = node.Contour;
int len = (int)m_srcPoly.size();
if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon)))
continue;
m_destPoly.clear();
if (len == 1)
{
if (node.m_jointype == jtRound)
{
double X = 1.0, Y = 0.0;
for (cInt j = 1; j <= steps; j++)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
double X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
}
else
{
double X = -1.0, Y = -1.0;
for (int j = 0; j < 4; ++j)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[0].X + X * delta),
Round(m_srcPoly[0].Y + Y * delta)));
if (X < 0) X = 1;
else if (Y < 0) Y = 1;
else X = -1;
}
}
m_destPolys.push_back(m_destPoly);
continue;
}
//build m_normals ...
m_normals.clear();
m_normals.reserve(len);
for (int j = 0; j < len - 1; ++j)
m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1]));
if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon)
m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0]));
else
m_normals.push_back(DoublePoint(m_normals[len - 2]));
if (node.m_endtype == etClosedPolygon)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else if (node.m_endtype == etClosedLine)
{
int k = len - 1;
for (int j = 0; j < len; ++j)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
m_destPoly.clear();
//re-build m_normals ...
DoublePoint n = m_normals[len -1];
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-n.X, -n.Y);
k = 0;
for (int j = len - 1; j >= 0; j--)
OffsetPoint(j, k, node.m_jointype);
m_destPolys.push_back(m_destPoly);
}
else
{
int k = 0;
for (int j = 1; j < len - 1; ++j)
OffsetPoint(j, k, node.m_jointype);
IntPoint pt1;
if (node.m_endtype == etOpenButt)
{
int j = len - 1;
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X *
delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
int j = len - 1;
k = len - 2;
m_sinA = 0;
m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y);
if (node.m_endtype == etOpenSquare)
DoSquare(j, k);
else
DoRound(j, k);
}
//re-build m_normals ...
for (int j = len - 1; j > 0; j--)
m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y);
m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y);
k = len - 1;
for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype);
if (node.m_endtype == etOpenButt)
{
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta),
(cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta));
m_destPoly.push_back(pt1);
}
else
{
k = 1;
m_sinA = 0;
if (node.m_endtype == etOpenSquare)
DoSquare(0, 1);
else
DoRound(0, 1);
}
m_destPolys.push_back(m_destPoly);
}
}
}
//------------------------------------------------------------------------------
void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype)
{
//cross product ...
m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y);
if (std::fabs(m_sinA * m_delta) < 1.0)
{
//dot product ...
double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y );
if (cosA > 0) // angle => 0 degrees
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
return;
}
//else angle => 180 degrees
}
else if (m_sinA > 1.0) m_sinA = 1.0;
else if (m_sinA < -1.0) m_sinA = -1.0;
if (m_sinA * m_delta < 0)
{
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta)));
m_destPoly.push_back(m_srcPoly[j]);
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
else
switch (jointype)
{
case jtMiter:
{
double r = 1 + (m_normals[j].X * m_normals[k].X +
m_normals[j].Y * m_normals[k].Y);
if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k);
break;
}
case jtSquare: DoSquare(j, k); break;
case jtRound: DoRound(j, k); break;
}
k = j;
}
//------------------------------------------------------------------------------
void ClipperOffset::DoSquare(int j, int k)
{
double dx = std::tan(std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4);
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx))));
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)),
Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx))));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoMiter(int j, int k, double r)
{
double q = m_delta / r;
m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q),
Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q)));
}
//------------------------------------------------------------------------------
void ClipperOffset::DoRound(int j, int k)
{
double a = std::atan2(m_sinA,
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
double X = m_normals[k].X, Y = m_normals[k].Y, X2;
for (int i = 0; i < steps; ++i)
{
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + X * m_delta),
Round(m_srcPoly[j].Y + Y * m_delta)));
X2 = X;
X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos;
}
m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + m_normals[j].X * m_delta),
Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta)));
}
//------------------------------------------------------------------------------
// Miscellaneous public functions
//------------------------------------------------------------------------------
void Clipper::DoSimplePolygons()
{
PolyOutList::size_type i = 0;
while (i < m_PolyOuts.size())
{
OutRec* outrec = m_PolyOuts[i++];
OutPt* op = outrec->Pts;
if (!op || outrec->IsOpen) continue;
do //for each Pt in Polygon until duplicate found do ...
{
OutPt* op2 = op->Next;
while (op2 != outrec->Pts)
{
if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op)
{
//split the polygon into two ...
OutPt* op3 = op->Prev;
OutPt* op4 = op2->Prev;
op->Prev = op4;
op4->Next = op;
op2->Prev = op3;
op3->Next = op2;
outrec->Pts = op;
OutRec* outrec2 = CreateOutRec();
outrec2->Pts = op2;
UpdateOutPtIdxs(*outrec2);
if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts))
{
//OutRec2 is contained by OutRec1 ...
outrec2->IsHole = !outrec->IsHole;
outrec2->FirstLeft = outrec;
if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec);
}
else
if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts))
{
//OutRec1 is contained by OutRec2 ...
outrec2->IsHole = outrec->IsHole;
outrec->IsHole = !outrec2->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
outrec->FirstLeft = outrec2;
if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2);
}
else
{
//the 2 polygons are separate ...
outrec2->IsHole = outrec->IsHole;
outrec2->FirstLeft = outrec->FirstLeft;
if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2);
}
op2 = op; //ie get ready for the Next iteration
}
op2 = op2->Next;
}
op = op->Next;
}
while (op != outrec->Pts);
}
}
//------------------------------------------------------------------------------
void ReversePath(Path& p)
{
std::reverse(p.begin(), p.end());
}
//------------------------------------------------------------------------------
void ReversePaths(Paths& p)
{
for (Paths::size_type i = 0; i < p.size(); ++i)
ReversePath(p[i]);
}
//------------------------------------------------------------------------------
void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPath(in_poly, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType)
{
Clipper c;
c.StrictlySimple(true);
c.AddPaths(in_polys, ptSubject, true);
c.Execute(ctUnion, out_polys, fillType, fillType);
}
//------------------------------------------------------------------------------
void SimplifyPolygons(Paths &polys, PolyFillType fillType)
{
SimplifyPolygons(polys, polys, fillType);
}
//------------------------------------------------------------------------------
inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2)
{
double Dx = ((double)pt1.X - pt2.X);
double dy = ((double)pt1.Y - pt2.Y);
return (Dx*Dx + dy*dy);
}
//------------------------------------------------------------------------------
double DistanceFromLineSqrd(
const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2)
{
//The equation of a line in general form (Ax + By + C = 0)
//given 2 points (x¹,y¹) & (x²,y²) is ...
//(y¹ - y²)x + (x² - x¹)y + (y² - y¹)x¹ - (x² - x¹)y¹ = 0
//A = (y¹ - y²); B = (x² - x¹); C = (y² - y¹)x¹ - (x² - x¹)y¹
//perpendicular distance of point (x³,y³) = (Ax³ + By³ + C)/Sqrt(A² + B²)
//see http://en.wikipedia.org/wiki/Perpendicular_distance
double A = double(ln1.Y - ln2.Y);
double B = double(ln2.X - ln1.X);
double C = A * ln1.X + B * ln1.Y;
C = A * pt.X + B * pt.Y - C;
return (C * C) / (A * A + B * B);
}
//---------------------------------------------------------------------------
bool SlopesNearCollinear(const IntPoint& pt1,
const IntPoint& pt2, const IntPoint& pt3, double distSqrd)
{
//this function is more accurate when the point that's geometrically
//between the other 2 points is the one that's tested for distance.
//ie makes it more likely to pick up 'spikes' ...
if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y))
{
if ((pt1.X > pt2.X) == (pt1.X < pt3.X))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.X > pt1.X) == (pt2.X < pt3.X))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
else
{
if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y))
return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd;
else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y))
return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd;
else
return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd;
}
}
//------------------------------------------------------------------------------
bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd)
{
double Dx = (double)pt1.X - pt2.X;
double dy = (double)pt1.Y - pt2.Y;
return ((Dx * Dx) + (dy * dy) <= distSqrd);
}
//------------------------------------------------------------------------------
OutPt* ExcludeOp(OutPt* op)
{
OutPt* result = op->Prev;
result->Next = op->Next;
op->Next->Prev = result;
result->Idx = 0;
return result;
}
//------------------------------------------------------------------------------
void CleanPolygon(const Path& in_poly, Path& out_poly, double distance)
{
//distance = proximity in units/pixels below which vertices
//will be stripped. Default ~= sqrt(2).
size_t size = in_poly.size();
if (size == 0)
{
out_poly.clear();
return;
}
OutPt* outPts = new OutPt[size];
for (size_t i = 0; i < size; ++i)
{
outPts[i].Pt = in_poly[i];
outPts[i].Next = &outPts[(i + 1) % size];
outPts[i].Next->Prev = &outPts[i];
outPts[i].Idx = 0;
}
double distSqrd = distance * distance;
OutPt* op = &outPts[0];
while (op->Idx == 0 && op->Next != op->Prev)
{
if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd))
{
ExcludeOp(op->Next);
op = ExcludeOp(op);
size -= 2;
}
else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd))
{
op = ExcludeOp(op);
size--;
}
else
{
op->Idx = 1;
op = op->Next;
}
}
if (size < 3) size = 0;
out_poly.resize(size);
for (size_t i = 0; i < size; ++i)
{
out_poly[i] = op->Pt;
op = op->Next;
}
delete [] outPts;
}
//------------------------------------------------------------------------------
void CleanPolygon(Path& poly, double distance)
{
CleanPolygon(poly, poly, distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance)
{
for (Paths::size_type i = 0; i < in_polys.size(); ++i)
CleanPolygon(in_polys[i], out_polys[i], distance);
}
//------------------------------------------------------------------------------
void CleanPolygons(Paths& polys, double distance)
{
CleanPolygons(polys, polys, distance);
}
//------------------------------------------------------------------------------
void Minkowski(const Path& poly, const Path& path,
Paths& solution, bool isSum, bool isClosed)
{
int delta = (isClosed ? 1 : 0);
size_t polyCnt = poly.size();
size_t pathCnt = path.size();
Paths pp;
pp.reserve(pathCnt);
if (isSum)
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y));
pp.push_back(p);
}
else
for (size_t i = 0; i < pathCnt; ++i)
{
Path p;
p.reserve(polyCnt);
for (size_t j = 0; j < poly.size(); ++j)
p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y));
pp.push_back(p);
}
solution.clear();
solution.reserve((pathCnt + delta) * (polyCnt + 1));
for (size_t i = 0; i < pathCnt - 1 + delta; ++i)
for (size_t j = 0; j < polyCnt; ++j)
{
Path quad;
quad.reserve(4);
quad.push_back(pp[i % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]);
quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]);
quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]);
if (!Orientation(quad)) ReversePath(quad);
solution.push_back(quad);
}
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed)
{
Minkowski(pattern, path, solution, true, pathIsClosed);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void TranslatePath(const Path& input, Path& output, const IntPoint delta)
{
//precondition: input != output
output.resize(input.size());
for (size_t i = 0; i < input.size(); ++i)
output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y);
}
//------------------------------------------------------------------------------
void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed)
{
Clipper c;
for (size_t i = 0; i < paths.size(); ++i)
{
Paths tmp;
Minkowski(pattern, paths[i], tmp, true, pathIsClosed);
c.AddPaths(tmp, ptSubject, true);
if (pathIsClosed)
{
Path tmp2;
TranslatePath(paths[i], tmp2, pattern[0]);
c.AddPath(tmp2, ptClip, true);
}
}
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution)
{
Minkowski(poly1, poly2, solution, false, true);
Clipper c;
c.AddPaths(solution, ptSubject, true);
c.Execute(ctUnion, solution, pftNonZero, pftNonZero);
}
//------------------------------------------------------------------------------
enum NodeType {ntAny, ntOpen, ntClosed};
void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths)
{
bool match = true;
if (nodetype == ntClosed) match = !polynode.IsOpen();
else if (nodetype == ntOpen) return;
if (!polynode.Contour.empty() && match)
paths.push_back(polynode.Contour);
for (int i = 0; i < polynode.ChildCount(); ++i)
AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths);
}
//------------------------------------------------------------------------------
void PolyTreeToPaths(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntAny, paths);
}
//------------------------------------------------------------------------------
void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
AddPolyNodeToPaths(polytree, ntClosed, paths);
}
//------------------------------------------------------------------------------
void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths)
{
paths.resize(0);
paths.reserve(polytree.Total());
//Open paths are top level only, so ...
for (int i = 0; i < polytree.ChildCount(); ++i)
if (polytree.Childs[i]->IsOpen())
paths.push_back(polytree.Childs[i]->Contour);
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const IntPoint &p)
{
s << "(" << p.X << "," << p.Y << ")";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Path &p)
{
if (p.empty()) return s;
Path::size_type last = p.size() -1;
for (Path::size_type i = 0; i < last; i++)
s << "(" << p[i].X << "," << p[i].Y << "), ";
s << "(" << p[last].X << "," << p[last].Y << ")\n";
return s;
}
//------------------------------------------------------------------------------
std::ostream& operator <<(std::ostream &s, const Paths &p)
{
for (Paths::size_type i = 0; i < p.size(); i++)
s << p[i];
s << "\n";
return s;
}
//------------------------------------------------------------------------------
} //ClipperLib namespace
| [
"dane@mapbox.com"
] | dane@mapbox.com |
96184da94dccc61fe1a89f75266a26435c0160f2 | a84b013cd995870071589cefe0ab060ff3105f35 | /webdriver/branches/chrome/chrome/src/cpp/include/chrome/browser/views/sad_tab_view.h | be33df13b29623a07ce46b2ca036d85cc26e3fff | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | vdt/selenium | 137bcad58b7184690b8785859d77da0cd9f745a0 | 30e5e122b068aadf31bcd010d00a58afd8075217 | refs/heads/master | 2020-12-27T21:35:06.461381 | 2009-08-18T15:56:32 | 2009-08-18T15:56:32 | 13,650,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,817 | h | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_VIEWS_SAD_TAB_H_
#define CHROME_BROWSER_VIEWS_SAD_TAB_H_
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/views/view.h"
class SkBitmap;
///////////////////////////////////////////////////////////////////////////////
//
// SadTabView
//
// A views::View subclass used to render the presentation of the crashed
// "sad tab" in the browser window when a renderer is destroyed unnaturally.
//
// Note that since this view is not (currently) part of a Container or
// RootView hierarchy, it cannot respond to events or contain controls that
// do, right now it is used simply to render. Adding an extra Container to
// WebContents seemed like a lot of complexity. Ideally, perhaps WebContents'
// view portion would itself become a Container in the future, then event
// processing will work.
//
///////////////////////////////////////////////////////////////////////////////
class SadTabView : public views::View {
public:
SadTabView();
virtual ~SadTabView() {}
// Overridden from views::View:
virtual void Paint(ChromeCanvas* canvas);
virtual void Layout();
private:
static void InitClass();
// Assorted resources for display.
static SkBitmap* sad_tab_bitmap_;
static ChromeFont title_font_;
static ChromeFont message_font_;
static std::wstring title_;
static std::wstring message_;
static int title_width_;
// Regions within the display for different components, populated by
// Layout().
gfx::Rect icon_bounds_;
gfx::Rect title_bounds_;
gfx::Rect message_bounds_;
DISALLOW_EVIL_CONSTRUCTORS(SadTabView);
};
#endif // CHROME_BROWSER_VIEWS_SAD_TAB_H__
| [
"noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9"
] | noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9 |
9d41d73b0c69a2ffcf7abf2029afc3f1d80ce733 | 775acebaa6559bb12365c930330a62365afb0d98 | /source/public/interfaces/tables/ITableCommands.h | c15c63a058e29ac26fa35dde453d189fb1348841 | [] | no_license | Al-ain-Developers/indesing_plugin | 3d22c32d3d547fa3a4b1fc469498de57643e9ee3 | 36a09796b390e28afea25456b5d61597b20de850 | refs/heads/main | 2023-08-14T13:34:47.867890 | 2021-10-05T07:57:35 | 2021-10-05T07:57:35 | 339,970,603 | 1 | 1 | null | 2021-10-05T07:57:36 | 2021-02-18T07:33:40 | C++ | UTF-8 | C++ | false | false | 26,191 | h | //========================================================================================
//
// $File: //depot/devtech/16.0.x/plugin/source/public/interfaces/tables/ITableCommands.h $
//
// Owner: Mat Marcus
//
// $Author: pmbuilder $
//
// $DateTime: 2020/11/06 13:08:29 $
//
// $Revision: #2 $
//
// $Change: 1088580 $
//
// Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//========================================================================================
#pragma once
#ifndef __ITableCommands__
#define __ITableCommands__
#include "TablesID.h"
#include "TableTypes.h"
#include "ICellStrokeAttrData.h"
#include "ITableModel.h"
class AttributeBossList;
class TableMementoPiece; // $$$ should not be in the API
class WideString;
class ICommand;
/** Provides command based interface to the table model. Changes made to the table model
should be made through this interface rather than through ITableAttrModifier or
ITableModel to support undo capability.
*/
class ITableCommands : public IPMUnknown
{
public:
enum { kDefaultIID = IID_ITABLECOMMANDS };
/**@name Structure */
//@{-----------------------------------------------------------------------------
/** Method to insert new, unfilled rows in a table.
Height should be specified in points. If the given rowHeight is 0.0 then
the new row height is determined from
the row relative to which the insertion is being made. A non zero value of height will
result in all inserted rows having that minimum height.
The structure and attributes of the row that is the reference for the insertion
will be propagated to the newly created rows; for instance, if the relative position is 'eAfter' and the
row above the insertion location has a minimum row
height of 2 picas and the row height is specified as 0,
then the newly created rows will inherit the minimum row
size of 2 picas from the rows above the insertion point even if this is not the default for other cells in the table.
Similarly, if the relative position is 'eBefore', then the attributes and structure of the row below the insertion point
will be propagated to the newly created rows.
Encapsulates the execution of command that is instance of class kInsertRowsCmdBoss.
This command in turn acts on the table model to insert rows.
@param rows specifies the location as the start of the range, and how many rows to add, as the count
@param pos eBefore or eAfter to specify whether to insert before or after the current insertion point
@param height height of the row specified in points; a non-zero value means inserted rows will have that minimum height,
whereas a zero value will result in a calculated value based as described above
@param continuation
@return kSuccess if the command could be executed successully, kFailure otherwise
@precondition the row range specified has a start within the bounds of the table rows
@precondition the count of rows to be added in the row-range given is > 0
@precondition the minimimum height specified is >= 0.0
*/
virtual ErrorCode InsertRows(const RowRange& rows, const Tables::ERelativePosition pos, const PMReal& height, const Tables::EContinuation continuation = Tables::eStructureAllAttrs) = 0;
/** Method to move row(s) in a table
@param sourceTable specifies the table within which rows are to be moved
@param fromArea specifies the grid area which is to be moved
@param toRow specifies the row where the selected rows are to be moved
@param pos specifies the position of moved rows with respect to destination row, i.e. toRow
@param duplicateFlag specifies whether the moved rows are to be duplicated or not
@return kSuccess if the command could be executed successully, kFailure otherwise
*/
virtual ErrorCode MoveRows(ITableModel* sourceTable, GridArea fromArea, int32 toRow, Tables::ERelativePosition pos, bool16 duplicateFlag) = 0;
/** Method to move column(s) in a table
@param sourceTable specifies the table within which columns are to be moved
@param fromArea specifies the grid area which is to be moved
@param toColumn specifies the column where the selected columns are to be moved
@param pos specifies the relative position with respect to toColumn
@param duplicateFlag specifies whether the moved columns are to be duplicated or not
@return kSuccess if the command could be executed successully, kFailure otherwise
*/
virtual ErrorCode MoveColumns(ITableModel* sourceTable, GridArea fromArea, int32 toColumn, Tables::ERelativePosition pos, bool16 duplicateFlag) = 0;
/** Method to insert new, unfilled columns in a table.
Width for the newly-created columns should be specified in points.
If colWidth is 0.0 then the new width is determined from
the column relative to which the insertion is being made. A non zero value of
width will result in all inserted columns having that width.
See the comments on InsertRows for detail on how attributes are propagated from the reference column
to the newly created columns, mutatis mutandis.
Encapsulates the execution of command that is instance of class kInsertColumnsCmdBoss;
this acts on the table model to insert columns.
@param cols the start of the ColRange specifies the insertion location, and the count of the ColRange
columns gives the number of columns to add
@param pos eBefore or eAfter to specify whether to insert before or after the current insertion point
@param width
@param continuation
@return kSuccess if the command could be executed successully, kFailure otherwise
*/
virtual ErrorCode InsertColumns(const ColRange& cols, const Tables::ERelativePosition pos, const PMReal& width, const Tables::EContinuation continuation = Tables::eStructureAllAttrs) = 0;
/** Method to remove a specified row range from the table model.
@param rows specifies a range of rows to be removed from the table model
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the start of the range should be within the range of rows in the table
@precondition the count of rows to be deleted should be greater than 0
@precondition table.GetTotalRows().Contains(rows)
(GetTotalRows)
*/
virtual ErrorCode DeleteRows (const RowRange& rows) = 0;
/** Method that can remove all rows from table model,
leaving behind the anchor characters.
This method is meant to be called when deleting a table via a text deletion. In this
case it is undesirable for the table to delete the anchor characters.
@param rows specifies a range of rows to be removed from the table model which should cover
the whole table
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the start of the range should be within the range of rows in the table
@precondition table.GetTotalRows() == rows
(GetTotalRows)
*/
virtual ErrorCode DeleteRowsButNotAnchors(const RowRange& rows) = 0;
/** Method to remove a specified range of columns from the table.
@param cols specifies the range of columns to remove from the table
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the start of the range should be within the range of columns in the table
@precondition the count of columns to be deleted should be greater than 0
@precondition table.GetTotalCols().Contains(cols)
(GetTotalCols)
*/
virtual ErrorCode DeleteColumns(const ColRange& cols) = 0;
/** Method to merge the area specified into a single cell covering a GridSpan that is the
union of all the cells within this area.
@param cells specifies a grid area that contains the cells to merge
*/
virtual ErrorCode MergeCells (const GridArea& cells) = 0;
/** Method to unmerge the cells at the specified location, breaking apart the cell into grid
elements. These elements will have the trivial or unit GridSpan(1,1).
@param anchor specifies the location of the cell that is to be unmerged
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the grid address should be valid within the table
@precondition the address should refer to an anchor (top-left) of a cell
*/
virtual ErrorCode UnmergeCell (const GridAddress& anchor) = 0;
/** This method is obsolete. Please use SplitCells.
Method to split a cell at specified location in given direction.
@param anchor
@param splitDirection one of eVerticalSplit, eHorizontalSplit
@return kSuccess if the command executed successfully, kFailure otherwise
*/
// virtual ErrorCode SplitCell(const GridAddress& anchor, const ITableModel::ESplitDirection splitDirection) = 0;
/** Method to split cells with anchors in the specified area in given direction.
@param cells area of cells to split, does not need to contain complete cells
@param splitDirection one of eVerticalSplit, eHorizontalSplit
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode SplitCells (const GridArea& cells, const ITableModel::ESplitDirection splitDirection) = 0;
/* Method to change table direction from LeftToRight to RightToLeft
@param directionRTL direction to change to
@return kSuccess command executed successfully
*/
virtual ErrorCode ChangeTableDirection(Tables::EDirection directionRTL) = 0;
//@}-----------------------------------------------------------------------------
/**@name Attributes */
//@{-----------------------------------------------------------------------------
/** Method to apply change in height to rows.
The result of this method is to set the row-height and
the minimum row height for the target rows to newHeight.
If some cells in target rows have content that extends below this in depth, then
these cells can become overset.
This encapsulates executing the command kResizeRowsCmdBoss.
This command delegates to the table model's attribute modifier (ITableAttrModifier) to
change the model attributes.
@param rows specifies the range of rows to operate upon
@param newHeight specifies the new minimum and current row-height to set for the target range of rows
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ResizeRows (const RowRange& rows, const PMReal& newHeight) = 0;
/** Method to apply change in width to columns. This will set the column width for
the target column range; this does not affect the minimum column width for the target columns.
@param cols specifies the target range of columsn for this operation
@param newWidth specifies the
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ResizeCols (const ColRange& cols, const PMReal& newWidth) = 0;
/** Method to apply attribute-overrides to the given row range.
This encapsulates the execution of a command of class kApplyRowOverridesCmdBoss.
This command in turn delegates to the table model's attribute modifier (ITableAttrModifier)
to change the specified overrides.
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ApplyRowOverrides(const RowRange& rows, const AttributeBossList* attrs) = 0;
/** Method to apply attribute-overrides to the given column range.
This encapsulates the execution of a command of class kApplyColOverridesCmdBoss.
This command in turn delegates to the table model's attribute modifier (ITableAttrModifier)
to change the specified overrides.
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ApplyColOverrides(const ColRange& cols, const AttributeBossList* attrs) = 0;
/** Method to apply stroke-overrides to cells within given area.
These attributes are represented by boss classes that are distinctively identified by
aggregating an ITableAttrReport interface and have a ClassID such as kRowAttr<whatever>Boss.
Encapsulates execution of command of class kModifyCellStrokesCmdBoss. This in turn delegates
to the table model's attribute modifier (ITableAttrModifier) to clear the strokes specified.
For instance, to apply a stroke-weight to the top of all cells in given area, an ICellStrokeData::Data struct
would be initialised as follows:
<pre>
ICellStrokeAttrData::Data data;
data.attrs.Set(ICellStrokeAttrData::eWeight);
data.attrs.Add(ICellStrokeAttrData::eTint);
data.sides = Tables::eTopSide;
data.weight = newWeight; // a PMReal specifying new weight in points
data.tintPercent = newTintPercent; // a PMReal specifying tint in percent
</pre>
@param area the cells within the given GridArea to operate upon
@param data this is used to specify the sides and/or other attribute(s) for which the stroke-properties should be set.
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the area should be valid within the table model, i.e. have at least one cell within it
*/
virtual ErrorCode ApplyCellStrokes(const GridArea& area, const ICellStrokeAttrData::Data& data) = 0;
/** Method to remove stroke-overrides from specified sides of cells in given area.
Encapsulates execution of command of class kModifyCellStrokesCmdBoss. This in turn delegates
to the table model's attribute modifier (ITableAttrModifier) to clear the strokes specified.
For instance, to clear all the stroke-weight attributes set on all sides of the cells in the
area, initialise a ICellStrokeAttrData::Data struct with the following:
<pre>
ICellStrokeAttrData::Data data;
data.sides = Tables::eAllSides; // or other constant from ESelectionSides
data.attrs.Set(ICellStrokeAttrData::eWeight);
</pre>
@param area cells within this area will have the cell stroke overrides removed
@param data this is used to specify the sides and/or other attribute(s) for which the stroke-properties should be cleared.
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the area should be valid within the table model, i.e. have at least one cell within it
*/
virtual ErrorCode ClearCellStrokes(const GridArea& area, const ICellStrokeAttrData::Data& data) = 0;
/** @see ClearCellStrokes
The difference between this command and the one above is that this one checks the GridArea we are applying to and makes
sure it still exists in the table. You can run into this problem through the preview dialogs. If the apply table dimensions
command is fired before the Clear Cell Attributes command then you end up clearing attributes on a new table structure
which if using the above command would crash
*/
virtual ErrorCode ClearCellStrokesUISafe(const GridArea& area, const ICellStrokeAttrData::Data& data) = 0;
/** Method to swap over stroke-fill of the cells in given area. That is, the fill colour, tint and overprint
will be swapped one-to-one with the stroke colour, tint and overprint.
This encapsulates execution of a command of class kSwapCellStrokeFillCmdBoss.
@param cells the cells within the given GridArea to operate upon
@return kSuccess if the command executed successfully, kFailure otherwise
@precondition the area should be valid within the table model, i.e. have at least one cell within it
*/
virtual ErrorCode SwapCellStrokeFill(const GridArea& cells) = 0;
/** Method to apply overrides to cells within given area.
These attributes are represented by boss classes that are distinctively identified by
aggregating an ITableAttrReport interface and have a ClassID such as kCellAttr<whatever>Boss.
@param cells the cells within the given GridArea to operate upon
@param attrs list of boss objects specifying by their ClassID the attribute to override and new values
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ApplyCellOverrides(const GridArea& cells, const AttributeBossList* attrs) = 0;
/** Removes cell-attribute overrides within specified area.
These attributes are represented by boss classes that are distinctively identified by
aggregating an ITableAttrReport interface and have a ClassID such as kCellAttr<whatever>Boss.
@param cells the cells within the given GridArea to operate upon
@param attrs list of boss objects specifying by their ClassID the override to remove
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ClearCellOverrides(const GridArea& cells, const AttributeBossList* attrs) = 0;
/** Applies table-level overrides to model.
These attributes are represented by boss classes that are distinctively identified by
aggregating an ITableAttrReport interface and have a ClassID such as kTableAttr<whatever>Boss.
@param cells the cells within the given GridArea to operate upon
@param attrs list of boss objects specifying by their ClassID the attribute to override and new values
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ApplyTableOverrides(const AttributeBossList* attrs) = 0;
/** Method to associate new table style with table model. Note that InDesign 2.0 does not support
named table styles, so this is a method for future use.
@param styleRef reference to the new table-style to associate with this table model
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode SetTableStyle(const UIDRef& styleRef) = 0;
/** Removes cell-border overrides
@param edge the side which border we are dealing with
@param attrs list of boss objects specifying by their ClassID the override to remove
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ClearBorderOverrides(Tables::ECellEdge edge, const AttributeBossList* attrs) = 0;
/** Removes cell-attribute overrides within specified area.
These attributes are represented by boss classes that are distinctively identified by
aggregating an ITableAttrReport interface and have a ClassID such as kCellAttr<whatever>Boss.
The difference between this command and the one above is that this one checks the GridArea we are applying to and makes
sure it still exists in the table. You can run into this problem through the preview dialogs. If the apply table dimensions
command is fired before the Clear Cell Attributes command then you end up clearing attributes on a new table structure
which if using the above command would crash
@param cells the cells within the given GridArea to operate upon
@param attrs list of boss objects specifying by their ClassID the override to remove
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ClearCellOverridesUISafe(const GridArea& cells, const AttributeBossList* attrs) = 0;
//@}-----------------------------------------------------------------------------
// Attributes -- returns a command to be processed
/**@name Queries */
//@{-----------------------------------------------------------------------------
/** Method to acquire command that can be processed to apply changes to stroke-properties within given area
@param area delimits cells that are target of this operation
@param data
@return interface ptr that has had reference-count incremented
*/
virtual ICommand* QueryApplyCellStrokesCmd(const GridArea& area, const ICellStrokeAttrData::Data& data) = 0;
/** Method to acquire command that can be processed to clear stroke-properties within given area
@param area delimits cells that are target of this operation
@param data
@return interface ptr that has had reference-count incremented
*/
virtual ICommand* QueryClearCellStrokesCmd(const GridArea& area, const ICellStrokeAttrData::Data& data) = 0;
/** Method to acquire command that can be processed to clear stroke-properties within given area
The difference between this command and the one above is that this one checks the GridArea we are applying to and makes
sure it still exists in the table. You can run into this problem through the preview dialogs. If the apply table dimensions
command is fired before the Clear Cell Attributes command then you end up clearing attributes on a new table structure
which if using the above command would crash
@param area delimits cells that are target of this operation
@param data
@return interface ptr that has had reference-count incremented
*/
virtual ICommand* QueryClearCellStrokesUISafeCmd(const GridArea& area, const ICellStrokeAttrData::Data& data) = 0;
/** Method to acquire command that can be processed to apply overrides to cell attributes within given area
@param cells delimits cells that are target of this operation
@param attrs
@return interface ptr that has had reference-count incremented
*/
virtual ICommand* QueryApplyCellOverridesCmd(const GridArea& cells, const AttributeBossList* attrs) = 0;
//@}-----------------------------------------------------------------------------
/**@name Content */
//@{-----------------------------------------------------------------------------
/** Method to set the text contents of cell with given anchor (top-left) location.
@param cellText specifies text contents for cell
@param anchor location of top-left of cell that is target for this operation
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode SetCellText(const WideString& cellText, const GridAddress& anchor) = 0;
/** Method to remove the content from cells within given region
@param cells delimits region within which cell contents are to be cleared
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode ClearContent(const GridArea& cells) = 0;
//@}-----------------------------------------------------------------------------
/**@name Internal use */
//@{-----------------------------------------------------------------------------
/** Internal use only.
@param strandRef
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode RegisterStrand(const UIDRef& strandRef) = 0;
/** Internal use only. See the documentation on ICellContentMgr for more information.
@param contentMgrType
@param contenMgr
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode RegisterContentMgr(CellType contentMgrType, const UIDRef& contenMgr) = 0;
//@}-----------------------------------------------------------------------------
/**@name Create Segments */
//@{-----------------------------------------------------------------------------
/** Method to create a row segment at the distance from the top PMReal specified and
spanning the cells in the range GridArea.
@param distanceFromEdge
@param segment
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode CreateRowSegment(const PMReal& distanceFromEdge, const ColRange& segmentRange) = 0;
/** Method to create a row segment at the distance from the left PMReal specified and
spanning the cells in the range GridArea.
@param distanceFromEdge
@param segment
@return kSuccess if the command executed successfully, kFailure otherwise
*/
virtual ErrorCode CreateColSegment(const PMReal& distanceFromEdge, const RowRange& segmentRange) = 0;
//@}-----------------------------------------------------------------------------
/** @name Convert to header and footer */
//@{-----------------------------------------------------------------------------
/**
@param rows Rows to convert to headers. See ITableModel::ConvertToHeaderRows for more info.
*/
virtual ErrorCode ConvertToHeaderRows(const RowRange& rows) = 0;
/**
@param rows Rows to convert to footer. See ITableModel::ConvertToFooterRows for more info.
*/
virtual ErrorCode ConvertToFooterRows(const RowRange& rows) = 0;
/**
@param rows Rows to convert to body. See ITableModel::ConvertToBodyRows for more info.
*/
virtual ErrorCode ConvertToBodyRows(const RowRange& rows) = 0;
//@}-----------------------------------------------------------------------------
/** @name Convert table to text */
//@{-----------------------------------------------------------------------------
/**
@param colSeparator delimiter for parsing columns
@param rowSeparator delimiter for parsing rows
*/
virtual ErrorCode ConvertTableToText(const PMString colSeparator="\t", const PMString rowSeparator="\r") = 0;
/** Method to acquire command that can be processed to delete an entire table
@param table model ref
@return interface ptr that has had reference-count incremented
*/
virtual ICommand* QueryDeleteTableCmd(const UIDRef& tableRef) = 0;
/** Method to convert the type of cells
@param cells GridArea of cells to be converted
@param destType cell type to be converted into
@param tryToPreserveData if true, the data is preserved into the cell after conversion, if possible.
*/
virtual ErrorCode ConvertCellsType(const GridArea& cells, CellType destType, bool16 tryToPreserveData = kFalse) = 0;
/** Method to paste a page item into the graphic cell.
@param anchor GridAddress of destination cell
@param pageItemUID UIDRef of object to be pasted into the cell
@param preventCopy The object would not be copied, just removed from the source and pasted here. This is not cut-paste.
It should be used, only if object is already in the scrap database.
*/
virtual ErrorCode PastePageItem(const GridAddress &anchor, UIDRef pageItemUID, bool16 preventCopy = kFalse) = 0;
};
#endif // __ITableCommands__
| [
"75730278+Tarekhesham10@users.noreply.github.com"
] | 75730278+Tarekhesham10@users.noreply.github.com |
ec42159e6a0406ea15d52416de8a5c6da63c2524 | 7643c2d99c30127a49d506cd9526ccdf24e8c131 | /src/gdw_dialog.cpp | b3ce6d9376997b9aa46ebcda29dbbf6bda9c6fd4 | [] | no_license | neilspo/gendat-explorer | 8c67dc3bdb311eb9f9cc55d8bebd6dad382eaea8 | b06c35ec208a6b0eef8377da33ad9d5fc88acc10 | refs/heads/master | 2023-05-11T01:24:53.601856 | 2023-04-26T17:06:16 | 2023-04-26T17:06:16 | 49,293,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,057 | cpp | ///
/// \class gdw_db_connect gdw_dialog.h
///
/// \brief Popup window that obtains database login information from the user
///
/// This class handles ...
///
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <string>
#include <stdexcept>
#include "gdw_dialog.h"
#include "gdw_field_group.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Constructor
///
/// The constructor creates the popup window and waits for user input.
///
////////////////////////////////////////////////////////////////////////////////////////////////////
gdw_db_connect::gdw_db_connect(database* db) : wxDialog(NULL, wxID_ANY, "Database Connect")
{
wxLogMessage("gdw_db_connect Constructor Start");
// Keep a pointer to the database object.
my_db = db;
// Put everything in a panel.
wxPanel *panel = new wxPanel(this, wxID_ANY);
// Use a vertical box sizer to layout the parts of the dialog.
wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL);
// Add the user input fields.
gdw_field_group field_group(panel, vbox, wxID_ANY, 100, -1);
wx_hostname = field_group.add_field ("Host Name", "localhost");
wx_username = field_group.add_field ("User Name", "test_RO");
wx_password = field_group.add_field ("Password", "");
// Add "Cancel" and "Apply" buttons.
wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL);
hbox->Add(new wxButton(panel, wxID_CANCEL));
hbox->Add(new wxButton(panel, wxID_APPLY));
vbox->Add(hbox, 0, wxALIGN_RIGHT | wxTOP | wxRIGHT | wxBOTTOM, 10);
// Bind the event handler, which will only execute after the "Apply" button is pressed.
Bind(wxEVT_BUTTON, &gdw_db_connect::event_handler, this, wxID_APPLY);
// Now display everything.
panel->SetSizer(vbox);
Centre();
}
gdw_db_connect::~gdw_db_connect()
{
wxLogMessage("gdw_db_connect Destructor Start");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Event handler
///
/// This member function handles all of the wxWidgets events that are generated by TopFrame.
///
////////////////////////////////////////////////////////////////////////////////////////////////////
void gdw_db_connect::event_handler (wxCommandEvent& event)
{
wxLogMessage("db_connect::event_handler: Start");
std::string host (wx_hostname->GetValue());
std::string user (wx_username->GetValue());
std::string passwd (wx_password->GetValue());
std::string db_name("zzz");
// Try to connect to the database. If it worked, then kill the dialog window.
// Otherwise, report the error and leave the dialog window open.
try
{
my_db->connect(host, user, passwd, db_name);
EndModal(1);
}
catch (std::runtime_error& exception)
{
wxString error_msg = exception.what();
wxMessageDialog* msg_dia = new wxMessageDialog(NULL, error_msg, "Runtime Error");
msg_dia->ShowModal();
}
}
| [
"neil.sponagle@gmail.com"
] | neil.sponagle@gmail.com |
44f6122f507be687fc42c903bd12270ae0ecd833 | c7c4ac450c0150fa443ea879aab7e867c61ada73 | /src/qt/rpcconsole.h | 6c2337555767a0a5362469934631f851e61d1bee | [
"MIT"
] | permissive | randboy/BAYEMCOIN | 1a408701bcaf152f0f26ba988861c58b4956bbbc | d0f19e1e38a5bebeb9a7a230e1f0054134720250 | refs/heads/master | 2022-12-03T14:59:07.156104 | 2020-08-24T02:07:53 | 2020-08-24T02:07:53 | 289,723,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,126 | h | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Ravencoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BAYEMCOIN_QT_RPCCONSOLE_H
#define BAYEMCOIN_QT_RPCCONSOLE_H
#include "guiutil.h"
#include "peertablemodel.h"
#include "net.h"
#include <QWidget>
#include <QCompleter>
#include <QThread>
class ClientModel;
class PlatformStyle;
class RPCTimerInterface;
namespace Ui {
class RPCConsole;
}
QT_BEGIN_NAMESPACE
class QMenu;
class QItemSelection;
QT_END_NAMESPACE
/** Local Bayemcoin RPC console. */
class RPCConsole: public QWidget
{
Q_OBJECT
public:
explicit RPCConsole(const PlatformStyle *platformStyle, QWidget *parent);
~RPCConsole();
static bool RPCParseCommandLine(std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr);
static bool RPCExecuteCommandLine(std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr) {
return RPCParseCommandLine(strResult, strCommand, true, pstrFilteredOut);
}
void setClientModel(ClientModel *model);
enum MessageClass {
MC_ERROR,
MC_DEBUG,
CMD_REQUEST,
CMD_REPLY,
CMD_ERROR
};
enum TabTypes {
TAB_INFO = 0,
TAB_CONSOLE = 1,
TAB_GRAPH = 2,
TAB_PEERS = 3
};
protected:
virtual bool eventFilter(QObject* obj, QEvent *event);
void keyPressEvent(QKeyEvent *);
private Q_SLOTS:
void on_lineEdit_returnPressed();
void on_tabWidget_currentChanged(int index);
/** open the debug.log from the current datadir */
void on_openDebugLogfileButton_clicked();
/** change the time range of the network traffic graph */
void on_sldGraphRange_valueChanged(int value);
/** update traffic statistics */
void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut);
void resizeEvent(QResizeEvent *event);
void showEvent(QShowEvent *event);
void hideEvent(QHideEvent *event);
/** Show custom context menu on Peers tab */
void showPeersTableContextMenu(const QPoint& point);
/** Show custom context menu on Bans tab */
void showBanTableContextMenu(const QPoint& point);
/** Hides ban table if no bans are present */
void showOrHideBanTableIfRequired();
/** clear the selected node */
void clearSelectedNode();
public Q_SLOTS:
void clear(bool clearHistory = true);
void fontBigger();
void fontSmaller();
void setFontSize(int newSize);
/** Append the message to the message widget */
void message(int category, const QString &message, bool html = false);
/** Set number of connections shown in the UI */
void setNumConnections(int count);
/** Set network state shown in the UI */
void setNetworkActive(bool networkActive);
/** Set number of blocks and last block date shown in the UI */
void setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers);
/** Set size (number of transactions and memory usage) of the mempool in the UI */
void setMempoolSize(long numberOfTxs, size_t dynUsage);
/** Go forward or back in history */
void browseHistory(int offset);
/** Scroll console view to end */
void scrollToEnd();
/** Handle selection of peer in peers list */
void peerSelected(const QItemSelection &selected, const QItemSelection &deselected);
/** Handle selection caching before update */
void peerLayoutAboutToChange();
/** Handle updated peer information */
void peerLayoutChanged();
/** Disconnect a selected node on the Peers tab */
void disconnectSelectedNode();
/** Ban a selected node on the Peers tab */
void banSelectedNode(int bantime);
/** Unban a selected node on the Bans tab */
void unbanSelectedNode();
/** set which tab has the focus (is visible) */
void setTabFocus(enum TabTypes tabType);
Q_SIGNALS:
// For RPC command executor
void stopExecutor();
void cmdRequest(const QString &command);
private:
void startExecutor();
void setTrafficGraphRange(int mins);
/** show detailed information on ui about selected node */
void updateNodeDetail(const CNodeCombinedStats *stats);
enum ColumnWidths
{
ADDRESS_COLUMN_WIDTH = 200,
SUBVERSION_COLUMN_WIDTH = 150,
PING_COLUMN_WIDTH = 80,
BANSUBNET_COLUMN_WIDTH = 200,
BANTIME_COLUMN_WIDTH = 250
};
Ui::RPCConsole *ui;
ClientModel *clientModel;
QStringList history;
int historyPtr;
QString cmdBeforeBrowsing;
QList<NodeId> cachedNodeids;
const PlatformStyle *platformStyle;
RPCTimerInterface *rpcTimerInterface;
QMenu *peersTableContextMenu;
QMenu *banTableContextMenu;
int consoleFontSize;
QCompleter *autoCompleter;
QThread thread;
/** Update UI with latest network info from model. */
void updateNetworkState();
};
#endif // BAYEMCOIN_QT_RPCCONSOLE_H
| [
"root@vps-5c20fa9d.vps.ovh.net.novalocal"
] | root@vps-5c20fa9d.vps.ovh.net.novalocal |
ba9f6553285937a5d2bb73cad76f4893e4a5df20 | 2aa79da9c8bda8e4b41ed75957fc16f2d8708df1 | /ovum/test/gtest.h | 1a0864a5d075dbe213d9991dcd46fafa427b6208 | [
"MIT"
] | permissive | zeta1999/egg | b941e8621dfd677ea60af46adac7d1af01adea0c | 99c6e03dfbc19864b3de364f7d4b3de6d9db5dbc | refs/heads/master | 2022-11-29T04:58:40.245440 | 2020-08-17T08:04:43 | 2020-08-17T08:04:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,651 | h | // GoogleTest needs a reduction in MSVC's warning levels
#if defined(_MSC_VER)
#pragma warning(push, 3)
#pragma warning(disable: 4365 4623 4625 4626 5026 5027)
#endif
#include "gtest/gtest.h"
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
namespace egg::test {
// This is the default entry-point for Google Test runners
int main(int argc, char** argv);
// Readability wrappers
inline bool contains(const std::string& haystack, const std::string& needle) {
return haystack.find(needle) != std::string::npos;
}
inline bool startsWith(const std::string& haystack, const std::string& needle) {
return (haystack.size() >= needle.size()) && std::equal(needle.begin(), needle.end(), haystack.begin());
}
inline bool endsWith(const std::string& haystack, const std::string& needle) {
return (haystack.size() >= needle.size()) && std::equal(needle.rbegin(), needle.rend(), haystack.rbegin());
}
// Used by ASSERT_CONTAINS, ASSERT_STARTSWITH, ASSERT_ENDSWITH, et al
::testing::AssertionResult assertContains(const char* haystack_expr, const char* needle_expr, const std::string& haystack, const std::string& needle);
::testing::AssertionResult assertNotContains(const char* haystack_expr, const char* needle_expr, const std::string& haystack, const std::string& needle);
::testing::AssertionResult assertStartsWith(const char* haystack_expr, const char* needle_expr, const std::string& haystack, const std::string& needle);
::testing::AssertionResult assertEndsWith(const char* haystack_expr, const char* needle_expr, const std::string& haystack, const std::string& needle);
// Used by EGG_INSTANTIATE_TEST_CASE_P
template<typename T>
int registerTestCase(const char* name, const char* file, int line) {
// See https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#how-to-write-value-parameterized-tests
auto& registry = ::testing::UnitTest::GetInstance()->parameterized_test_registry();
auto* holder = registry.GetTestCasePatternHolder<T>(name, ::testing::internal::CodeLocation(file, line));
return holder->AddTestCaseInstantiation("", &T::generator, &T::name, file, line);
}
}
// The following is almost the same as
// INSTANTIATE_TEST_CASE_P(Examples, TestExamples, ::testing::ValuesIn(TestExamples::find()), TestExamples::name);
// but produces prettier lists in MSVC Test Explorer
#define EGG_INSTANTIATE_TEST_CASE_P(test_case_name) \
static int test_case_name##Registration GTEST_ATTRIBUTE_UNUSED_ = egg::test::registerTestCase<test_case_name>(#test_case_name, __FILE__, __LINE__);
// Add some useful extra macros
#define ASSERT_CONTAINS(haystack, needle) ASSERT_PRED_FORMAT2(egg::test::assertContains, haystack, needle)
#define ASSERT_NOTCONTAINS(haystack, needle) ASSERT_PRED_FORMAT2(egg::test::assertNotContains, haystack, needle)
#define ASSERT_STARTSWITH(haystack, needle) ASSERT_PRED_FORMAT2(egg::test::assertStartsWith, haystack, needle)
#define ASSERT_ENDSWITH(haystack, needle) ASSERT_PRED_FORMAT2(egg::test::assertEndsWith, haystack, needle)
// See https://stackoverflow.com/a/43569017
#define ASSERT_THROW_E(statement, expected_exception, caught) \
try \
{ \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);\
FAIL() << "Expected: " #statement " throws an exception of type " #expected_exception ".\n Actual: it throws nothing."; \
} \
catch (const expected_exception& e) \
{ \
GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(caught); \
} \
catch (...) \
{ \
FAIL() << "Expected: " #statement " throws an exception of type " #expected_exception ".\n Actual: it throws a different type."; \
}
| [
"ian@chilliant.com"
] | ian@chilliant.com |
8df8e6c6e0817049250833a24e708402eb25adbf | 9f1531b82e1e5842582b9deee98ccf5178485232 | /include/Joint.hpp | 74ed8cdcb6c98a3284e448b84f299cd1cbb3dfcd | [
"MIT"
] | permissive | j8xixo12/Multibody-Dynamics-Solver | 8d6659ce254c81f11fb72cdd602c1adb80c17468 | 6102a97b00e3ce59db7fb95acc25be5bd8711984 | refs/heads/master | 2020-07-06T22:55:39.671931 | 2019-08-19T12:03:28 | 2019-08-19T12:03:28 | 203,164,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 830 | hpp | #ifndef JOINT_HPP
#define JOINT_HPP
#include <armadillo>
#include "Math.hpp"
#include "Body.hpp"
class Joint
{
public:
Joint(unsigned int TypeIn, arma::vec piIn, arma::vec pjIn, arma::vec qiIn,
arma::vec qjIn, Body *i_In, Body *j_In);
~Joint() {};
void Build_C();
void Build_Cq();
void Build_GAMMA();
void update();
arma::mat get_Cq();
arma::vec get_GAMMA();
private:
unsigned int Type;
arma::vec pi;
arma::vec pj;
arma::vec qi;
arma::vec qj;
arma::mat Cq;
arma::vec GAMMA;
arma::vec CONSTRAINT;
arma::mat TBI_i;
arma::mat TBI_j;
arma::vec Pi;
arma::vec Pj;
arma::vec Qi;
arma::vec Qj;
arma::vec wi;
arma::vec wj;
arma::vec Si;
arma::vec Sj;
Body *body_i_ptr;
Body *body_j_ptr;
};
#endif //JOINT_HPP | [
"as2266317@hotmail.com"
] | as2266317@hotmail.com |
a753ce49cb5993350d26349e644dfe5b7826128d | f819d6e972a5cf26ad0d13b2be482a353d3cfeb9 | /Doc/Sinkhold_DocPJ/Sinkhold_Doc/Service_ScanEnemyCharacter.h | 4b580742bac6e861c24690cb3049562de6e36e09 | [] | no_license | Sandwich33/Sinkhole4_9 | b317dc2ca75879597197c4db1c2983ac7c677e48 | 72d0cb90ea6b8ba39966fd23e9b31b1ef8d65be1 | refs/heads/master | 2021-01-21T15:26:23.278122 | 2016-08-11T09:17:25 | 2016-08-11T09:17:25 | 53,466,519 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 748 | h | #pragma once
/**
@brief 팀원 AI 서비스
@details 매 틱마다 공격 대상을 찾는다. 발견하면 대상을 블랙보드의 targetToAttack에 set한다.
*/
class Service_ScanEnemyCharacter :
public BTService
{
public:
BlackboardKeySelector targetToAttack;
BlackboardKeySelector attackRange;
/**
@brief 서비스 틱 이벤트
@details 캐릭터 주변 일정 범위 안의 적 캐릭터를 찾는다.
@details 찾은 캐릭터들 중 가장 가까운 액터를 블랙보드의 targetToAttack에 저장한다.
@param OwnerActor AI 컨트롤러.
*/
EventGraph ReceiveTick(Actor OwnerActor);
private:
AllAIController All_AI_Ref;
Pawn AI_Char_Ref;
EObjectTypeQuery EObject_Arr;
Vector AI_Location;
Float F_AttackRange;
};
| [
"deathnote10@naver.com"
] | deathnote10@naver.com |
c66b804f9c4596471e52b5ff01e611b1fc059cd9 | f572446a43c89a28cc7e115ec71cbb3970bf8db8 | /PredicatesAndExpressions/TsLTPredicate.H | c63ffc85298f6c2c36c1c81ff411471c0e9d6bce | [] | no_license | as010101/Autemp | b0b47b711b48a5cdaf79c44dace28841d41608b4 | 2a3ae6b536ab8a13afebba3e9be02eeae27e4713 | refs/heads/master | 2022-06-10T05:55:55.545374 | 2020-05-06T08:11:32 | 2020-05-06T08:11:32 | 260,402,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | h | #ifndef TIMESTAMP_LESS_THAN_PREDICATE_H
#define TIMESTAMP_LESS_THAN_PREDICATE_H
#include "Predicate.H"
class TsLTPredicate : public Predicate
{
public:
TsLTPredicate (Expression *left_side, Expression *right_side);
TsLTPredicate(Expression *exp);
virtual ~TsLTPredicate();
void setExpression(Expression *exp);
virtual bool evaluate(char *tuple);
virtual bool evaluate(char *tuple1, char *tuple2);
private:
Expression *_ls;
Expression *_rs;
};
#endif
| [
"root@localhost.localdomain"
] | root@localhost.localdomain |
6e7842ad127216fc7168d82bcaa63c6271f8201f | 58a4cdf76fb7b0e9594f7a4fb51c4c8ba8e06514 | /fboss/agent/hw/bcm/BcmTrunkTable.h | cca29bc7ba4cd5a10025ef86f3624fc1cd1bd64e | [
"BSD-3-Clause"
] | permissive | dendisuhubdy/fboss | 981bcb99e68f2d3c63947044235b5cd4283f84d0 | 89deb9468f647f2a56da55c7ed8f36e7e1151b4e | refs/heads/master | 2020-06-01T01:38:15.038773 | 2019-06-06T00:54:43 | 2019-06-06T00:58:21 | 190,580,507 | 0 | 0 | NOASSERTION | 2019-12-09T07:13:54 | 2019-06-06T12:50:08 | C++ | UTF-8 | C++ | false | false | 1,970 | h | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <memory>
extern "C" {
#include <opennsl/types.h>
}
#include <boost/container/flat_map.hpp>
#include <folly/dynamic.h>
#include "fboss/agent/hw/bcm/MinimumLinkCountMap.h"
#include "fboss/agent/types.h"
namespace facebook {
namespace fboss {
class AggregatePort;
class BcmSwitch;
class BcmTrunk;
class BcmTrunkTable {
public:
explicit BcmTrunkTable(const BcmSwitch* hw);
virtual ~BcmTrunkTable();
// Prior to the invocation of the following 3 functions, the global HW update
// lock (BcmSwitch::lock_) should have been acquired.
void addTrunk(const std::shared_ptr<AggregatePort>& aggPort);
void programTrunk(
const std::shared_ptr<AggregatePort>& oldAggPort,
const std::shared_ptr<AggregatePort>& newAggPort);
void deleteTrunk(const std::shared_ptr<AggregatePort>& aggPort);
opennsl_trunk_t getBcmTrunkId(AggregatePortID id) const;
AggregatePortID getAggregatePortId(opennsl_trunk_t trunk) const;
size_t numTrunkPorts() const { return trunks_.size(); }
// TODO(samank): Fill in method
// Serialize to folly::dynamic
folly::dynamic toFollyDynamic() const;
opennsl_trunk_t linkDownHwNotLocked(opennsl_port_t port);
void updateStats();
// Setup trunking machinery
void setupTrunking();
private:
// Forbidden copy constructor and assignment operator
BcmTrunkTable(const BcmTrunkTable&) = delete;
BcmTrunkTable& operator=(const BcmTrunkTable&) = delete;
boost::container::flat_map<AggregatePortID, std::unique_ptr<BcmTrunk>>
trunks_;
const BcmSwitch* const hw_{nullptr};
TrunkToMinimumLinkCountMap trunkToMinLinkCount_;
};
}
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
46f5c677a6394b24d3f8cce702bf16b23e99b9bf | fd0878e211a042e91603d0941f6624cb7af9eab1 | /DLL Circular Queue/main.cpp | 4b53da222f2b15e30c5739bdf2e3c40c62052680 | [] | no_license | luntan365/cpp | ef8293e8abf3d9b4e7c78beb77124767e01d1a79 | 77d5c4c2007c07cf5a7633c60cf1521a9530f21c | refs/heads/master | 2021-06-12T21:27:00.189293 | 2020-03-31T15:10:00 | 2020-03-31T15:10:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 75 | cpp | #include "queue.h"
int main()
{
Queue queue;
queue.run();
return 0;
}
| [
"adityakr082@gmail.com"
] | adityakr082@gmail.com |
e0be766eb803d899dd818802d53630fef2ef0b0e | 300c25f8dd06c3f27d5148a41547163b6bddab3f | /src/CharacterAnim.cpp | ba5be33670121344a1271822eda277a045fdad70 | [] | no_license | Exoria/JeudePorcs | bd59c81d7bfcb9e05f049e0d86412ad4d1fd1945 | b277feb0228e5e4e3e9a094181ba13d24c2d3b15 | refs/heads/master | 2021-01-23T04:10:22.011911 | 2013-12-15T17:31:39 | 2013-12-15T17:31:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | cpp | #include <stdio.h>
#include "CharacterAnim.hpp"
ALLEGRO_BITMAP *CharacterAnim::image = NULL;
int CharacterAnim::useCount = 0;
CharacterAnim::CharacterAnim(int ch, int an, float fr) : character(ch), anim(an), framerate(fr), firstFrame(0) {
if (useCount == 0 && image == NULL) {
image = al_load_bitmap("resources/persos.png");
al_convert_mask_to_alpha(image, al_get_pixel(image,0,0));
}
++useCount;
}
CharacterAnim::~CharacterAnim() {
--useCount;
if (useCount == 0 && image != NULL) {
al_destroy_bitmap(image);
image = NULL;
}
}
void CharacterAnim::Draw(float x, float y) {
int bw = al_get_bitmap_width(image);
int bh = al_get_bitmap_height(image);
int w = bw / (3*4);
int h = bh / (4*2);
if (character > 3) {
character -= 3;
anim += 4;
}
int frame = firstFrame;
if (framerate > 0.0f) {
frame += (al_get_time() * framerate);
frame %= 4;
if (frame == 3)
frame = 1;
}
al_draw_scaled_bitmap( image, (character*3+frame)*w, anim*h, w, h, x, y, w, h, 0 );
}
void CharacterAnim::SetFrame(int frame) {
firstFrame = frame;
}
| [
"camille.bartalan@gmail.com"
] | camille.bartalan@gmail.com |
22d210c1de3de3c653ecba38c632ac11d32d7a76 | 3e3fe4344120006c3fd3664865eba160ae66a013 | /Game/Preferences.cpp | 21a88e493250faf9b3ab1264fd49a40bae64fbee | [] | no_license | Kumazuma/3D_Project | f627f20c5c89d3e8f2adbb10d1ab8cb6a655f1ac | 4e38afd3de5a8a6cfb589adf5e73bb7d5772af33 | refs/heads/master | 2023-03-16T14:06:46.254172 | 2021-03-02T09:46:24 | 2021-03-02T09:46:24 | 314,772,394 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,196 | cpp | #include "Preferences.hpp"
#include <mutex>
namespace Kumazuma::Client
{
std::unique_ptr<Preferences> Preferences::s_instance{};
SpinLock Preferences::s_locker{};
Preferences::Preferences():
showCollisionBox{ false }
{
}
Preferences::Preferences(Preferences&& rhs) noexcept :
showCollisionBox{std::move(rhs.showCollisionBox)}
{
}
auto Preferences::operator=(Preferences&& rhs) noexcept-> Preferences&
{
Preferences tmp{ std::move(rhs) };
this->~Preferences();
new(this)Preferences{ std::move(tmp) };
// TODO: 여기에 return 문을 삽입합니다.
return *this;
}
auto Preferences::Current() -> Preferences const&
{
std::lock_guard<SpinLock> guard{ s_locker };
if (s_instance == nullptr)
{
s_instance.reset(new Preferences{});
}
return *s_instance;
}
auto Preferences::Update(Preferences const& rhs) -> void
{
Update(Preferences{ rhs });
}
auto Preferences::Update(Preferences&& rhs) -> void
{
std::lock_guard<SpinLock> guard{ s_locker };
*s_instance = std::move(rhs);
}
}
| [
"qweads12@gmail.com"
] | qweads12@gmail.com |
6661756c6bc76266ce7270b5f564fc3299003ed1 | 005cb1c69358d301f72c6a6890ffeb430573c1a1 | /Pods/Headers/Private/GeoFeatures/boost/mpl/list/aux_/front.hpp | 94201bc565cd404a20f6b0099975270f69003aea | [
"Apache-2.0"
] | permissive | TheClimateCorporation/DemoCLUs | 05588dcca687cc5854755fad72f07759f81fe673 | f343da9b41807694055151a721b497cf6267f829 | refs/heads/master | 2021-01-10T15:10:06.021498 | 2016-04-19T20:31:34 | 2016-04-19T20:31:34 | 51,960,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74 | hpp | ../../../../../../../GeoFeatures/GeoFeatures/boost/mpl/list/aux_/front.hpp | [
"tommy.rogers@climate.com"
] | tommy.rogers@climate.com |
d0099e0554fa1f864d16403a3b40862928e7b49f | c4f5aaff56a28fad5b582943b088538c247de491 | /src/ui/linux/TogglDesktop/errorviewcontroller.cpp | 4b23858c19392f9440fc9f9350129ba839af9bcf | [
"BSD-2-Clause"
] | permissive | refiito/toggldesktop | e900a9d220ee9b10b34a0c350f436d493f87bf96 | 1581b78013516110f59f5f60f0f23a77fe4dfd2d | refs/heads/master | 2021-01-15T23:59:47.901096 | 2015-01-22T11:07:55 | 2015-01-22T11:07:55 | 29,674,710 | 0 | 0 | null | 2015-01-22T11:06:30 | 2015-01-22T11:06:30 | null | UTF-8 | C++ | false | false | 1,842 | cpp | // Copyright 2014 Toggl Desktop developers.
#include "./errorviewcontroller.h"
#include "./ui_errorviewcontroller.h"
#include "./toggl.h"
ErrorViewController::ErrorViewController(QWidget *parent)
: QWidget(parent)
, ui(new Ui::ErrorViewController)
, networkError(false)
, loginError(false)
, uid(0) {
ui->setupUi(this);
setVisible(false);
connect(TogglApi::instance, SIGNAL(displayError(QString,bool)), // NOLINT
this, SLOT(displayError(QString,bool))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayOnlineState(bool,QString)), // NOLINT
this, SLOT(displayOnlineState(bool,QString))); // NOLINT
connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), // NOLINT
this, SLOT(displayLogin(bool,uint64_t))); // NOLINT
}
ErrorViewController::~ErrorViewController() {
delete ui;
}
void ErrorViewController::on_pushButton_clicked() {
setVisible(false);
}
void ErrorViewController::displayError(
const QString errmsg,
const bool user_error) {
networkError = false;
loginError = !uid;
ui->errorMessage->setText(errmsg);
setVisible(true);
if (!user_error) {
TogglApi::notifyBugsnag("error in shared lib", errmsg,
"ErrorViewController");
}
}
void ErrorViewController::displayOnlineState(
const bool is_online,
const QString reason) {
if (!is_online && !reason.isEmpty()) {
networkError = true;
ui->errorMessage->setText(reason);
setVisible(true);
} else if (is_online && networkError) {
setVisible(false);
}
}
void ErrorViewController::displayLogin(
const bool open,
const uint64_t user_id) {
uid = user_id;
if (user_id && isVisible() && loginError) {
loginError = false;
setVisible(false);
}
}
| [
"tanel.lebedev@gmail.com"
] | tanel.lebedev@gmail.com |
33620a0d1dba9f30e788f86ce1f284c6dcce0ea7 | fc987d063c6d3812cc53f59d2c19fdcbe168bd04 | /FaceFlux/StegerWarmingVector.cpp | da740f60fb2707465d852acdc7e9b955358100b0 | [] | no_license | arashkarshenass/Steady2D | 61021d8fe9ad2610d1e3b3f2128d5193642c098b | f315c6380e77e17cea5e0ae5203c9ee0bdc3f69b | refs/heads/master | 2020-03-25T09:08:40.673142 | 2018-08-05T21:46:37 | 2018-08-05T21:46:37 | 143,649,871 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,171 | cpp | /*=================================================
Steger Class source
=================================================*/
#include "../FaceFlux/StegerWarmingVector.h"
#include "../Inputs.h"
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
void StegerWarmingVector::Initializer(double* wfc,double* wfn,double* ff,double**DL)
{
wFaceCurr=wfc;
wFaceNeigh=wfn;
faceFlux=ff;
dL=DL;
g1=gamma-1;
}
void StegerWarmingVector::CalculateFaceFlux(int cellNum,int faceNum)
{
double rho,un,ut,a,s2;
double lam[4]={0};
double fluxPlus[4]={0};
double fluxMinus[4]={0};
//F+ (flux from current cell in n-t coord)
rho=wFaceCurr[0]; //density
un=wFaceCurr[1]/rho; //u is Un (normal velocity)
ut=wFaceCurr[2]/rho; //v is Ut (tangential velocity)
s2=un*un+ut*ut; //square of speed
a=sqrt(gamma*wFaceCurr[4]/rho); //sound speed
lam[0]=0.5*(un+abs(un));
lam[1]=lam[0];
lam[2]=0.5*((un+a)+abs(un+a));
lam[3]=0.5*((un-a)+abs(un-a));
fluxPlus[0]=rho/2/gamma*(2*g1*lam[1]+lam[2]+lam[3]);
fluxPlus[1]=rho/2/gamma*(2*un*g1*lam[1]+(un+a)*lam[2]+(un-a)*lam[3]);
fluxPlus[2]=rho/2/gamma*(2*ut*g1*lam[0]+ut*(lam[2]+lam[3]));
fluxPlus[3]=rho/2/gamma*(2*ut*ut*g1*lam[0] + (un*un-ut*ut)*g1*lam[1] + (s2/2+a*un+a*a/g1)*lam[2] + (s2/2-a*un+a*a/g1)*lam[3]);
//F- (flux from neighbor cell in n-t coord)
rho=wFaceNeigh[0];
un=wFaceNeigh[1]/rho;
ut=wFaceNeigh[2]/rho;
s2=un*un+ut*ut;
a=sqrt(gamma*wFaceNeigh[4]/rho);
lam[0]=0.5*(un-abs(un));
lam[1]=lam[0];
lam[2]=0.5*((un+a)-abs(un+a));
lam[3]=0.5*((un-a)-abs(un-a));
fluxMinus[0]=rho/2/gamma*(2*g1*lam[1]+lam[2]+lam[3]);
fluxMinus[1]=rho/2/gamma*(2*un*g1*lam[1]+(un+a)*lam[2]+(un-a)*lam[3]);
fluxMinus[2]=rho/2/gamma*(2*ut*g1*lam[0]+ut*(lam[2]+lam[3]));
fluxMinus[3]=rho/2/gamma*(2*ut*ut*g1*lam[0] + (un*un-ut*ut)*g1*lam[1] + (s2/2+a*un+a*a/g1)*lam[2] + (s2/2-a*un+a*a/g1)*lam[3]);
//summing F+ and F-
faceFlux[0]=(fluxPlus[0]+fluxMinus[0])*dL[cellNum][faceNum];
faceFlux[1]=(fluxPlus[1]+fluxMinus[1])*dL[cellNum][faceNum];
faceFlux[2]=(fluxPlus[2]+fluxMinus[2])*dL[cellNum][faceNum];
faceFlux[3]=(fluxPlus[3]+fluxMinus[3])*dL[cellNum][faceNum];
}
| [
"42058201+arashkarshenass@users.noreply.github.com"
] | 42058201+arashkarshenass@users.noreply.github.com |
35a118759e1775bef4fd3d6a5ce517fbb38a0260 | 1fdc4dda46919bf501870364a0430f2124a07e44 | /calculator.h | e883e7f0f35f47a6c89031f8d0a56757988aec1b | [] | no_license | chamodKanishka/GUI-Calculator-App-C- | 57eb61a7b37d0ac64b1e6968edb941afbb0ff003 | afc29e5a603cb5618e8df0246cce5cb3a96e2e43 | refs/heads/master | 2020-09-08T13:33:41.603793 | 2019-11-12T06:41:11 | 2019-11-12T06:41:11 | 221,148,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | h | #ifndef CALCULATOR_H
#define CALCULATOR_H
#include <QMainWindow>
namespace Ui {
class Calculator;
}
class Calculator : public QMainWindow
{
Q_OBJECT
public:
explicit Calculator(QWidget *parent = nullptr);
~Calculator();
private:
Ui::Calculator *ui;
QString currentFile = "";
private slots:
void NumPressed();
void MathButtonPressed();
void EqualButtonPressed();
void ChangeNumberSign();
void ClearPressed();
};
#endif // CALCULATOR_H
| [
"chamodkanishka77@gmail.com"
] | chamodkanishka77@gmail.com |
b81798fa8933b61b394458c25f46f67c2710e2d9 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_repos_function_1450_curl-7.35.0.cpp | 54c191a02c17acaa4090ee9e7ca113aa2aeb0ba0 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | static CURLcode pop3_state_auth_ntlm_type2msg_resp(struct connectdata *conn,
int pop3code,
pop3state instate)
{
CURLcode result = CURLE_OK;
struct SessionHandle *data = conn->data;
char *type2msg = NULL;
char *type3msg = NULL;
size_t len = 0;
(void)instate; /* no use for this yet */
if(pop3code != '+') {
failf(data, "Access denied: %d", pop3code);
result = CURLE_LOGIN_DENIED;
}
else {
/* Get the type-2 message */
pop3_get_message(data->state.buffer, &type2msg);
/* Decode the type-2 message */
result = Curl_sasl_decode_ntlm_type2_message(data, type2msg, &conn->ntlm);
if(result) {
/* Send the cancellation */
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", "*");
if(!result)
state(conn, POP3_AUTH_CANCEL);
}
else {
/* Create the type-3 message */
result = Curl_sasl_create_ntlm_type3_message(data, conn->user,
conn->passwd, &conn->ntlm,
&type3msg, &len);
if(!result && type3msg) {
/* Send the message */
result = Curl_pp_sendf(&conn->proto.pop3c.pp, "%s", type3msg);
if(!result)
state(conn, POP3_AUTH_FINAL);
}
}
}
Curl_safefree(type3msg);
return result;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
99d21ee226b6da594ee824a66489048926bd932d | 741cbbc8c5936615cb47c085d1db1d59c22e1028 | /src/PartialMatchRegexTest.cpp | bf65a2b32aa755016bd7435109d72a1ca6571aeb | [
"BSL-1.0"
] | permissive | iturovskiy/PartialMatchRegex | 7a757b1a63d7f71fbbb61c6affd4380f4b08b2e3 | 30a408bd6a1b6abc0f4909584528bebd101232b0 | refs/heads/master | 2022-03-23T14:23:30.124305 | 2019-12-29T21:09:19 | 2019-12-29T21:09:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,429 | cpp | // Copyright 2019 Igor Turovskiy
// Copyright 2019 Sviatoslav Dmitriev
// 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
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "PartialMatchRegex.h"
TEST_CASE("PartialMatchRegex")
{
const std::string r1("aab*");
const std::string r2("a|b|c");
const std::string r3("J.* B.*");
const std::string r4("\\+?[\\d]+");
const std::string r5("(\\+|-)?[\\d]+");
const std::string r6("((\\+|-)?[\\d]+)(\\.(([\\d]+)?))?");
const std::string r7("((\\+|-)?[\\d]+)(\\.(([\\d]+)?))?((e|E)((\\+|-)?)[\\d]+)?");
const std::string r8("[^a]{0,3}");
const std::string r9("a");
SECTION("Constructor throws")
{
REQUIRE(!PartialMatchRegex::isValidRegex("(aza"));
REQUIRE_THROWS(PartialMatchRegex("(aza"));
REQUIRE(!PartialMatchRegex::isValidRegex("[a-z."));
REQUIRE_THROWS(PartialMatchRegex("[a-z."));
}
SECTION("Constructor no throws")
{
REQUIRE_NOTHROW(PartialMatchRegex(r1));
REQUIRE_NOTHROW(PartialMatchRegex(r2));
REQUIRE_NOTHROW(PartialMatchRegex(r3));
REQUIRE_NOTHROW(PartialMatchRegex(r4));
REQUIRE_NOTHROW(PartialMatchRegex(r5));
REQUIRE_NOTHROW(PartialMatchRegex(r6));
REQUIRE_NOTHROW(PartialMatchRegex(r7));
REQUIRE_NOTHROW(PartialMatchRegex(r8));
REQUIRE_NOTHROW(PartialMatchRegex(r9));
REQUIRE_NOTHROW(PartialMatchRegex(""));
}
SECTION("Constructor move")
{
PartialMatchRegex re1(r1);
REQUIRE_NOTHROW(PartialMatchRegex(std::move(re1)));
PartialMatchRegex re2(r2);
PartialMatchRegex re4 = std::move(re2);
REQUIRE_NOTHROW(PartialMatchRegex(re4));
}
SECTION("Handy matching")
{
PartialMatchRegex re1(r1);
REQUIRE(re1.fullMatch("aabbbb"));
REQUIRE(re1.fullMatch("aab"));
REQUIRE(re1.fullMatch("aa"));
REQUIRE(re1.subMatch("aabbbb"));
REQUIRE(re1.subMatch("aab"));
REQUIRE(re1.subMatch("aa"));
REQUIRE(re1.subMatch("a"));
REQUIRE(!re1.subMatch("ac"));
REQUIRE(!re1.subMatch("c"));
PartialMatchRegex re2(r2);
REQUIRE(re2.subMatch("a"));
REQUIRE(re2.subMatch("b"));
REQUIRE(re2.subMatch("c"));
REQUIRE(re2.subMatch("a"));
REQUIRE(re2.subMatch("b"));
REQUIRE(re2.subMatch("c"));
REQUIRE(re2.fullMatch("a"));
REQUIRE(re2.fullMatch("b"));
REQUIRE(re2.fullMatch("c"));
REQUIRE(re2.fullMatch("a"));
REQUIRE(re2.fullMatch("b"));
REQUIRE(re2.fullMatch("c"));
REQUIRE(!re2.subMatch("d"));
REQUIRE(!re2.fullMatch("d"));
PartialMatchRegex re3(r3);
REQUIRE(re3.fullMatch("J B"));
REQUIRE(re3.fullMatch("John B"));
REQUIRE(re3.fullMatch("Johny Black"));
REQUIRE(re3.subMatch("J"));
REQUIRE(re3.subMatch("Johny"));
REQUIRE(re3.subMatch("John "));
REQUIRE(re3.subMatch("J B"));
REQUIRE(re3.subMatch("John B"));
REQUIRE(re3.subMatch("Johny Black"));
PartialMatchRegex re4("");
REQUIRE(re4.fullMatch(""));
PartialMatchRegex re5(r5);
REQUIRE(re5.fullMatch("+123"));
REQUIRE(re5.fullMatch("123"));
REQUIRE(re5.fullMatch("-123"));
}
}
| [
"treplen8@gmail.com"
] | treplen8@gmail.com |
b16026ab63e29cabb3dd113ff8e2eae8452dc4b9 | 066947a2b0c3e19aaf9449f1579efd39f28e56da | /src/main.hh | 1f886c065206ee98308500f077f525fe3737b336 | [] | no_license | Jerska/tirf | 1fe0373615c0d451dc7977a4c6c307c216f388dd | 875a6559e2fe1ec2e7cc68d0ac0f16a7d0b8e737 | refs/heads/master | 2021-05-28T02:48:02.758735 | 2014-07-11T05:57:31 | 2014-07-11T05:57:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | hh | #ifndef MAIN_HH_
# define MAIN_HH_
# include <map> // std::map
# include <utility> // std::make_pair, std::pair
# include <string> // std::string
# include <iostream>
# include <algorithm> // std::max, std::min
# include <cstdlib>
# include <ctime>
# include <opencv2/opencv.hpp>
//# define VERBOSE
# define FRAME_WIDTH 30
# define FRAME_HEIGHT 20
# define RESIZES 20
# define TRAININGS 15
# define NOT_FOUND_YET 1
# define GOOD_SCALE 2
# define BAD_SCALE 3
typedef std::pair<unsigned int, unsigned int> int_pair_t;
typedef std::map<std::pair<int_pair_t, int_pair_t>, unsigned char> match_map_t;
typedef std::map<std::string, match_map_t> img_map_t;
using namespace cv;
#endif // MAIN_HH_
| [
"jerska@live.fr"
] | jerska@live.fr |
1ac5aba13263e7751ac1c0a68102956d717be8a7 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-cloudsearch/include/aws/cloudsearch/model/DateOptions.h | e834e04beeca2251214178318d575892cebcb182 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 6,542 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/cloudsearch/CloudSearch_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudSearch
{
namespace Model
{
/**
* <p>Options for a date field. Dates and times are specified in UTC (Coordinated
* Universal Time) according to IETF RFC3339: yyyy-mm-ddT00:00:00Z. Present if
* <code>IndexFieldType</code> specifies the field is of type <code>date</code>.
* All options are enabled by default.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/cloudsearch-2013-01-01/DateOptions">AWS
* API Reference</a></p>
*/
class AWS_CLOUDSEARCH_API DateOptions
{
public:
DateOptions();
DateOptions(const Aws::Utils::Xml::XmlNode& xmlNode);
DateOptions& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline const Aws::String& GetDefaultValue() const{ return m_defaultValue; }
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline void SetDefaultValue(const Aws::String& value) { m_defaultValueHasBeenSet = true; m_defaultValue = value; }
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline void SetDefaultValue(Aws::String&& value) { m_defaultValueHasBeenSet = true; m_defaultValue = value; }
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline void SetDefaultValue(const char* value) { m_defaultValueHasBeenSet = true; m_defaultValue.assign(value); }
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline DateOptions& WithDefaultValue(const Aws::String& value) { SetDefaultValue(value); return *this;}
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline DateOptions& WithDefaultValue(Aws::String&& value) { SetDefaultValue(value); return *this;}
/**
* A value to use for the field if the field isn't specified for a document.
*/
inline DateOptions& WithDefaultValue(const char* value) { SetDefaultValue(value); return *this;}
inline const Aws::String& GetSourceField() const{ return m_sourceField; }
inline void SetSourceField(const Aws::String& value) { m_sourceFieldHasBeenSet = true; m_sourceField = value; }
inline void SetSourceField(Aws::String&& value) { m_sourceFieldHasBeenSet = true; m_sourceField = value; }
inline void SetSourceField(const char* value) { m_sourceFieldHasBeenSet = true; m_sourceField.assign(value); }
inline DateOptions& WithSourceField(const Aws::String& value) { SetSourceField(value); return *this;}
inline DateOptions& WithSourceField(Aws::String&& value) { SetSourceField(value); return *this;}
inline DateOptions& WithSourceField(const char* value) { SetSourceField(value); return *this;}
/**
* <p>Whether facet information can be returned for the field.</p>
*/
inline bool GetFacetEnabled() const{ return m_facetEnabled; }
/**
* <p>Whether facet information can be returned for the field.</p>
*/
inline void SetFacetEnabled(bool value) { m_facetEnabledHasBeenSet = true; m_facetEnabled = value; }
/**
* <p>Whether facet information can be returned for the field.</p>
*/
inline DateOptions& WithFacetEnabled(bool value) { SetFacetEnabled(value); return *this;}
/**
* <p>Whether the contents of the field are searchable.</p>
*/
inline bool GetSearchEnabled() const{ return m_searchEnabled; }
/**
* <p>Whether the contents of the field are searchable.</p>
*/
inline void SetSearchEnabled(bool value) { m_searchEnabledHasBeenSet = true; m_searchEnabled = value; }
/**
* <p>Whether the contents of the field are searchable.</p>
*/
inline DateOptions& WithSearchEnabled(bool value) { SetSearchEnabled(value); return *this;}
/**
* <p>Whether the contents of the field can be returned in the search results.</p>
*/
inline bool GetReturnEnabled() const{ return m_returnEnabled; }
/**
* <p>Whether the contents of the field can be returned in the search results.</p>
*/
inline void SetReturnEnabled(bool value) { m_returnEnabledHasBeenSet = true; m_returnEnabled = value; }
/**
* <p>Whether the contents of the field can be returned in the search results.</p>
*/
inline DateOptions& WithReturnEnabled(bool value) { SetReturnEnabled(value); return *this;}
/**
* <p>Whether the field can be used to sort the search results.</p>
*/
inline bool GetSortEnabled() const{ return m_sortEnabled; }
/**
* <p>Whether the field can be used to sort the search results.</p>
*/
inline void SetSortEnabled(bool value) { m_sortEnabledHasBeenSet = true; m_sortEnabled = value; }
/**
* <p>Whether the field can be used to sort the search results.</p>
*/
inline DateOptions& WithSortEnabled(bool value) { SetSortEnabled(value); return *this;}
private:
Aws::String m_defaultValue;
bool m_defaultValueHasBeenSet;
Aws::String m_sourceField;
bool m_sourceFieldHasBeenSet;
bool m_facetEnabled;
bool m_facetEnabledHasBeenSet;
bool m_searchEnabled;
bool m_searchEnabledHasBeenSet;
bool m_returnEnabled;
bool m_returnEnabledHasBeenSet;
bool m_sortEnabled;
bool m_sortEnabledHasBeenSet;
};
} // namespace Model
} // namespace CloudSearch
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
0197bb6578731e389a7c533a5c3d41206aa20d55 | 82685d006a3c55bb7ee00028d222a5b590189bbf | /Sourcecode/mx/core/elements/OffsetAttributes.h | b25e1c997aaa32f7ea07783bf058f04c2f1388f9 | [
"MIT"
] | permissive | ailialy/MusicXML-Class-Library | 41b1b6b28a67fd7cdfbbc4fb7c5c936aee4d9eca | 5e1f1cc8831449476f3facfff5cf852d66488d6a | refs/heads/master | 2020-06-18T23:46:50.306435 | 2016-08-22T04:33:44 | 2016-08-22T04:33:44 | 74,932,821 | 2 | 0 | null | 2016-11-28T03:14:23 | 2016-11-28T03:14:23 | null | UTF-8 | C++ | false | false | 745 | h | // MusicXML Class Library v0.2
// Copyright (c) 2015 - 2016 by Matthew James Briggs
#pragma once
#include "mx/core/ForwardDeclare.h"
#include "mx/core/AttributesInterface.h"
#include "mx/core/Enums.h"
#include <iosfwd>
#include <memory>
#include <vector>
namespace mx
{
namespace core
{
MX_FORWARD_DECLARE_ATTRIBUTES( OffsetAttributes )
struct OffsetAttributes : public AttributesInterface
{
public:
OffsetAttributes();
virtual bool hasValues() const;
virtual std::ostream& toStream( std::ostream& os ) const;
YesNo sound;
bool hasSound;
bool fromXElement( std::ostream& message, xml::XElement& xelement );
};
}
}
| [
"matthew.james.briggs@gmail.com"
] | matthew.james.briggs@gmail.com |
f600b63dca27189057a24eb6ac3890ebedecf508 | baf2356f891be699bfc33437bee478e0d3f46d9c | /Algorithm/jz/prob17.cpp | 969601bf69181c6adc102f04209ecfbea24dad44 | [] | no_license | D0m021ng/reading | 58ef40bdc40a4f8a049eb461a87cdd2d86c5dd2c | 6678700c2213306985fc04915f27a4014dbabf66 | refs/heads/master | 2022-01-21T11:24:23.067087 | 2022-01-05T10:44:06 | 2022-01-05T10:44:06 | 96,490,524 | 0 | 2 | null | 2022-01-05T10:44:07 | 2017-07-07T02:23:53 | C++ | UTF-8 | C++ | false | false | 867 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode{
int val;
struct TreeNode *left, *right;
TreeNode(int x) :
val(x), left(nullptr), right(nullptr) {}
};
vector<int> PrintFromTopToBottom(TreeNode* root){
vector<int> res;
if(root){
queue<TreeNode* > Q;
Q.push(root);
while(!Q.empty()){
TreeNode* p = Q.front();
Q.pop();
res.push_back(p->val);
if(p->left)
Q.push(p->left);
if(p->right)
Q.push(p->right);
}
}
return res;
}
void createTree(istream &fin, TreeNode **rt){
char x;
fin >> x;
if(x != '#')
if(*rt){
*rt = new TreeNode(x);
}
}
int main(){
int n;
fstream fin("./input/input17");
while(fin >> n){
}
return 0;
}
| [
"zhezhaodong@gmail.com"
] | zhezhaodong@gmail.com |
d852f71ca1b4ccea2741233ff56011fcd62b47aa | ab9ea8b58d3fa1d94546a50f83e1989f2ee04ea5 | /JoeEngine_3rd/Assets.h | e3014da19a87241c4968e6add4a45835af65189d | [
"MIT"
] | permissive | joeyGumer/JoeEngine_3rd | 9954fe4d292385333ffe1d75a3756c8688c49bce | acf41da1d1ce0a490eb896e83017478f1f4641f8 | refs/heads/master | 2020-06-11T22:27:34.823480 | 2016-12-05T12:32:17 | 2016-12-05T12:32:17 | 75,616,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,686 | h |
#ifndef __ASSETS_H__
#define __ASSETS_H__
#include "Window.h"
#include "ModuleResourceManager.h"
#include <vector>
struct Directory;
struct AssetFile
{
FileTypes type;
std::string name; //To display
std::string file_path;
std::string content_path;
std::string original_file;
unsigned int uuid;
int time_mod;
Directory* directory = nullptr;
};
struct Directory
{
std::string name; //To display
std::string path; //Path from Assets to the current directory
std::vector<Directory*> directories;
std::vector<AssetFile*> files;
std::string library_path;
Directory* parent = nullptr;
};
class Assets : public Window
{
public:
Assets();
~Assets();
void Draw();
void Refresh();
string CurrentDirectory()const;
string CurrentLibraryDirectory()const;
void DeleteAssetFile(AssetFile* file);
void DeleteMetaAndLibraryFile(AssetFile* file);
private:
void Init();
void CleanUp();
void FillDirectoriesRecursive(Directory* root_dir);
void DeleteDirectoriesRecursive(Directory* root_dir, bool keep_root = false);
Directory* FindDirectory(const string& dir);
AssetFile* FindAssetFile(const string& file);
bool IsMeshExtension(const std::string& file_name)const;
bool IsSceneExtension(const std::string& file_name)const;
void OpenInExplorer(const std::string* file = NULL)const;
void MeshFileOptions();
void SceneFileOptions();
void DirectoryOptions();
void DeleteAssetDirectory(Directory* directory);
public:
Directory* root = nullptr; //Assets directory
private:
Directory* current_dir = root;
Directory* dir_selected = nullptr;
AssetFile* file_selected = nullptr;
//Icons
uint folder_id;
uint file_id;
uint mesh_id;
uint scene_id;
};
#endif
| [
"pep3553@gmail.com"
] | pep3553@gmail.com |
aa483e703564905e0f870eae0aa53e5b223c5ceb | 8f6722d9ae9736320ee2a4122078606aedf90d11 | /block.h | 3da937aff3212fd9b0c511a08ff2b761c9ea2504 | [] | no_license | PabloLIborra/Arkanoid | 2d3b878cf9add6a80fb3b34f1b6decf36481115b | cd8bef448437b2ff92367d3a5fb9985c8429e4ae | refs/heads/master | 2020-03-19T12:09:37.974650 | 2018-06-07T15:55:29 | 2018-06-07T15:55:29 | 136,499,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | h | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: block.h
* Author: pablo
*
* Created on 14 de febrero de 2017, 22:31
*/
#ifndef BLOCK_H
#define BLOCK_H
class block : public box{
public:
block(int width,int height);
void invisible(){visible=false;}
virtual ~block();
bool getVisible(){return visible;}
private:
bool visible;
};
#endif /* BLOCK_H */
| [
"p.lopez.iborra@gmail.com"
] | p.lopez.iborra@gmail.com |
7cfb78f2009db7890b99eac560f05760fff712f0 | 9051285be833202e32278c0904245956ace3ed21 | /CPLUS/SAMPLES/WPCAR/BRAKE.H | 75b517e279d66a191a960ffde5f896446f8bd186 | [
"BSD-3-Clause"
] | permissive | OS2World/DEV-SAMPLES-IBM_OS2_2-0_Toolkit | 1c1b1598020e8cbbc4236fb96d7b1afc9b8d9acb | eefd859f3f9a73c27387641ffb1e47c3dbd3970f | refs/heads/master | 2021-01-12T16:34:13.743107 | 2016-10-20T01:08:04 | 2016-10-20T01:08:27 | 71,412,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,693 | h | /******************************************************************************
*
* Module Name: BRAKE.H
*
* OS/2 Work Place Shell Sample Program
*
* Copyright (C) 1992 IBM Corporation
*
* DISCLAIMER OF WARRANTIES. The following [enclosed] code is
* sample code created by IBM Corporation. This sample code is not
* part of any standard or IBM product and is provided to you solely
* for the purpose of assisting you in the development of your
* applications. The code is provided "AS IS", without
* warranty of any kind. IBM shall not be liable for any damages
* arising out of your use of the sample code, even if they have been
* advised of the possibility of such damages. *
*
* Description:
*
* This file contains the declaration of class Brake. Brake is a C++ class
* whose client is Carpp which is a SOM class. This is one example of
* the use of C++ constructs in the implementation of a SOM class.
*
* Brake is the abstraction of a real car's brake. The brake can be in
* one of two states. It can either be depressed or not depressed.
* There are public member functions to set the brake, release the
* brake, and determine whether or not the brake is currently depressed.
******************************************************************************/
#include "carpp.xih"
class Brake
{
BOOL depressed;
public:
Brake(VOID);
VOID Set(VOID);
VOID Release(VOID);
BOOL IsSet(VOID);
VOID SetToDefault(VOID);
VOID SaveState(Carpp *clientObject, PSZ CarClassTitle);
VOID RestoreState(Carpp *clientObject, PSZ CarClassTitle);
};
| [
"martiniturbide@gmail.com"
] | martiniturbide@gmail.com |
57ddfa2615f7b36399e8b4178978ccea64c360a2 | bb093502a9636ca962861cdc4b0e19c58e34b8c1 | /parts/seedstudio-us-ranger/src/sketch.ino | 5c733401ca9bcc345176483506c232f9880d58a1 | [] | no_license | Najaf/arduino-experiments | c2b0be3cd13f61b32ea3d2d40f0dd3d96189a438 | 0b64414de133cf8054afff33cbf85785a6e28758 | refs/heads/master | 2021-01-19T17:41:48.119889 | 2012-08-11T20:27:05 | 2012-08-11T20:27:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | ino | const int rangerPin = 9;
long reading = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
pulsePin(rangerPin, 10);
reading = readPin(rangerPin);
Serial.print("Centimeters: ");
Serial.print(microsecondsToCentimeters(reading));
Serial.println();
delay(50);
}
void pulsePin(int pin, int microseconds) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
digitalWrite(pin, HIGH);
delayMicroseconds(microseconds);
digitalWrite(pin, LOW);
}
long readPin(int pin) {
pinMode(pin, INPUT);
return pulseIn(rangerPin, HIGH);
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2 ;
}
| [
"ali.najaf@gmail.com"
] | ali.najaf@gmail.com |
7ac150a6bd26dfa64af3804ed1556cd55d62994d | f739df1f252d7c961ed881be3b8babaf62ff4170 | /softs/SCADAsoft/5.3.3_P2/ACE_Wrappers/TAO/TAO_IDL/be/be_visitor_interface/proxy_impls_ch.cpp | 62ff302d6af626014ce6b8fb6f825f395cba04aa | [] | no_license | billpwchan/SCADA-nsl | 739484691c95181b262041daa90669d108c54234 | 1287edcd38b2685a675f1261884f1035f7f288db | refs/heads/master | 2023-04-30T09:15:49.104944 | 2021-01-10T21:53:10 | 2021-01-10T21:53:10 | 328,486,982 | 0 | 0 | null | 2023-04-22T07:10:56 | 2021-01-10T21:53:19 | C++ | UTF-8 | C++ | false | false | 1,973 | cpp | //
// $Id: proxy_impls_ch.cpp 14 2007-02-01 15:49:12Z mitza $
//
ACE_RCSID (be_visitor_interface,
base_proxy_broker_impl_ch,
"$Id: proxy_impls_ch.cpp 14 2007-02-01 15:49:12Z mitza $")
be_visitor_interface_proxy_impls_ch::be_visitor_interface_proxy_impls_ch (
be_visitor_context *ctx
)
: be_visitor_interface (ctx)
{
// No-Op.
}
be_visitor_interface_proxy_impls_ch::~be_visitor_interface_proxy_impls_ch (
void
)
{
// No-Op.
}
int
be_visitor_interface_proxy_impls_ch::visit_interface (be_interface *node)
{
TAO_OutStream *os = this->ctx_->stream ();
// Generate Guards.
*os << "// The Proxy Implementations are used by each interface to"
<< be_nl
<< "// perform a call. Each different implementation encapsulates"
<< be_nl
<< "// an invocation logic." << be_nl << be_nl;
// Code Generation for the proxy imlpementations base class.
be_visitor_context ctx (*this->ctx_);
ctx.state (TAO_CodeGen::TAO_INTERFACE_BASE_PROXY_IMPL_CH);
be_visitor_interface_base_proxy_impl_ch bpi_visitor (&ctx);
if (node->accept (&bpi_visitor) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"be_visitor_interface_proxy_impls_ch::"
"visit_interface - "
"codegen for Base Proxy Impl. class failed\n"),
-1);
}
ctx = *this->ctx_;
ctx.state (TAO_CodeGen::TAO_INTERFACE_REMOTE_PROXY_IMPL_CH);
be_visitor_interface_remote_proxy_impl_ch rpi_visitor (&ctx);
if (node->accept (&rpi_visitor) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"be_visitor_interface_proxy_impls_ch::"
"visit_interface - "
"codegen for Remote Proxy Broker class failed\n"),
-1);
}
return 0;
}
int be_visitor_interface_proxy_impls_ch::visit_component (
be_component *node
)
{
return this->visit_interface (node);
}
| [
"billpwchan@hotmail.com"
] | billpwchan@hotmail.com |
6debae1c96e8ed39b9f70db818d3e1d4401834d5 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /atcoder/agc001-040/agc011/e.cpp | e5f461f808189bcaa2152e807384f8812e8e892f | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 1,263 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
string S;
char N[505050];
char M[505050];
int ok(int k) {
int i;
if(k<=0) return 0;
memmove(M,N,sizeof(N));
int tot=0;
int carry = 9*k;
FOR(i,505000) {
int v = M[i] + carry;
carry = v/10;
M[i] = v%10;
tot += M[i];
}
return 9*k >= tot;
}
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>S;
reverse(ALL(S));
FOR(i,S.size()) N[i]=S[i]-'0';
FOR(i,505000) N[i]*=9;
FOR(i,505000) {
N[i+1] += N[i]/10;
N[i] %= 10;
}
int ret=(1<<20);
for(i=20;i>=0;i--) if(ok(ret-(1<<i))) ret-=1<<i;
cout<<ret<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n';
FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
5114b30a5efbce33b84f0f5c2b5ab5472f3f5c5a | df9ced600aa576db0a5a9d86e46717d0a9535ff4 | /DHT11/DHT11.ino | d933951598b4347691524aef49f67b1da74f44dd | [] | no_license | linyuxuanlin/My-Arduino-library | 5922e8dfe2ce0d59a651bb35cb4e8b53b499227a | d53c980fda6e2a19b5e740316d9274908c931dd2 | refs/heads/master | 2021-01-20T13:02:58.816197 | 2017-05-09T23:53:04 | 2017-05-09T23:53:04 | 90,439,387 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | ino | #include <dht11.h>
dht11 ggyy; // 注意现在 ggyy 代表 DHT11 传感器
const int pin = 4; //
void setup( ) {
Serial.begin(115200);
}
void loop( ) {
ggyy.read(pin); // 读取 DHT11 传感器
Serial.print(String("") + "Humidity = "+ ggyy.humidity + " %");
Serial.println(String("")+", temperature = "+ ggyy.temperature +" C");
delay(2222); // 规定至少要等 2 秒再次读 dht11
}
| [
"824676271@qq.com"
] | 824676271@qq.com |
7d56b57634f0e24f3220092c3f1395c532eceaa3 | b8376621d63394958a7e9535fc7741ac8b5c3bdc | /lib/lib_XT12/Source/Common/XTPResourceManager.cpp | 17fc434484ecccac72fc0c7fda949be06ceb5a8a | [] | no_license | 15831944/job_mobile | 4f1b9dad21cb7866a35a86d2d86e79b080fb8102 | ebdf33d006025a682e9f2dbb670b23d5e3acb285 | refs/heads/master | 2021-12-02T10:58:20.932641 | 2013-01-09T05:20:33 | 2013-01-09T05:20:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,758 | cpp | // XTPResourceManager.cpp: implementation of the CXTPResourceManager class.
//
// This file is a part of the XTREME TOOLKIT PRO MFC class library.
// (c)1998-2008 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "XTPVC80Helpers.h"
#include "XTPVC50Helpers.h"
#include "XTPResourceManager.h"
#include "XTPMacros.h"
#include "XTPPropExchange.h"
#include "XTPSystemHelpers.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define MAKELANGINFO(l, s, w, e, c, f) {MAKELANGID(l, s), w, e, c, _T(#l), _T(#s), f}
#define ENGLISH_CHARSET ANSI_CHARSET
const WORD cwXTPResManDefLangID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
static XTP_RESOURCEMANAGER_LANGINFO langinfo[] =
{
MAKELANGINFO(LANG_RUSSIAN, SUBLANG_DEFAULT, 1251, _T("windows-1251"), _T("Russian"), RUSSIAN_CHARSET),
MAKELANGINFO(LANG_JAPANESE, SUBLANG_DEFAULT, 932, _T("shift-jis"), _T("Japanese"), SHIFTJIS_CHARSET),
MAKELANGINFO(LANG_ARABIC, SUBLANG_ARABIC_SAUDI_ARABIA, 1256, _T("windows-1256"), _T("Arabic (Saudi Arabia)"), ARABIC_CHARSET),
MAKELANGINFO(LANG_CZECH, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Czech"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_DANISH, SUBLANG_DEFAULT, 1252, _T("windows-1252"), _T("Danish"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_GERMAN, SUBLANG_GERMAN, 1252, _T("windows-1252"), _T("German (Germany)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_GREEK, SUBLANG_DEFAULT, 1253, _T("windows-1253"), _T("Greek"), GREEK_CHARSET),
MAKELANGINFO(LANG_ENGLISH, SUBLANG_ENGLISH_US, CP_ACP, _T("windows-1252"), _T("English (United States)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_SPANISH, SUBLANG_SPANISH_MODERN, 1252, _T("windows-1252"), _T("Spanish (Spain - Modern Sort)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_ESTONIAN, SUBLANG_DEFAULT, 1257, _T("windows-1257"), _T("Estonian"), BALTIC_CHARSET),
MAKELANGINFO(LANG_FINNISH, SUBLANG_DEFAULT, 1252, _T("windows-1252"), _T("Finnish"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_FRENCH, SUBLANG_FRENCH, 1252, _T("windows-1252"), _T("French (France)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_HEBREW, SUBLANG_DEFAULT, 1255, _T("windows-1255"), _T("Hebrew"), HEBREW_CHARSET),
MAKELANGINFO(LANG_CROATIAN, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Croatian"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_HUNGARIAN, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Hungarian"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_ITALIAN, SUBLANG_ITALIAN, 1252, _T("windows-1252"), _T("Italian (Italy)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_KOREAN, SUBLANG_DEFAULT, 949, _T("ks_c_5601"), _T("Korean"), HANGEUL_CHARSET),
MAKELANGINFO(LANG_LITHUANIAN, SUBLANG_LITHUANIAN, 1257, _T("windows-1257"), _T("Lithuanian"), BALTIC_CHARSET),
MAKELANGINFO(LANG_LATVIAN, SUBLANG_DEFAULT, 1257, _T("windows-1257"), _T("Latvian"), BALTIC_CHARSET),
MAKELANGINFO(LANG_DUTCH, SUBLANG_DUTCH, 1252, _T("windows-1252"), _T("Dutch"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_NORWEGIAN, SUBLANG_NORWEGIAN_BOKMAL, 1252, _T("windows-1252"), _T("Norwegian (Bokmal)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_POLISH, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Polish"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_PORTUGUESE, SUBLANG_PORTUGUESE, 1252, _T("windows-1252"), _T("Portuguese (Portugal)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN, 1252, _T("windows-1252"), _T("Portuguese (Brazil)"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_ROMANIAN, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Romanian"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_SLOVAK, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Slovak"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_SLOVENIAN, SUBLANG_DEFAULT, 1250, _T("windows-1250"), _T("Slovenian"), EASTEUROPE_CHARSET),
MAKELANGINFO(LANG_SWEDISH, SUBLANG_DEFAULT, 1252, _T("windows-1252"), _T("Swedish"), ENGLISH_CHARSET),
MAKELANGINFO(LANG_THAI, SUBLANG_DEFAULT, 874, _T("windows-874"), _T("Thai"), THAI_CHARSET),
MAKELANGINFO(LANG_TURKISH, SUBLANG_DEFAULT, 1254, _T("windows-1254"), _T("Turkish"), TURKISH_CHARSET),
MAKELANGINFO(LANG_UKRAINIAN, SUBLANG_DEFAULT, 1251, _T("windows-1251"), _T("Ukrainian "), RUSSIAN_CHARSET),
MAKELANGINFO(LANG_BULGARIAN, SUBLANG_DEFAULT, 1251, _T("windows-1251"), _T("Bulgarian"), RUSSIAN_CHARSET),
MAKELANGINFO(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED, 936, _T("gb2312"), _T("Chinese (PRC)"), GB2312_CHARSET),
MAKELANGINFO(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL, 950, _T("big5"), _T("Chinese (Taiwan)"), CHINESEBIG5_CHARSET)
};
//////////////////////////////////////////////////////////////////////////
// CW2CT
CXTPResourceManager::CXTPW2A::CXTPW2A(LPCWSTR lpwstr)
{
UINT nCodePage = XTPResourceManager()->GetLanguageInfo()->nCodePage;
int nDestLen = WideCharToMultiByte(nCodePage, 0, lpwstr, -1, NULL, 0, NULL, NULL);
m_lpsrt = new CHAR[nDestLen + 1];
WideCharToMultiByte(nCodePage, 0, lpwstr, -1, m_lpsrt, nDestLen, NULL, NULL);
m_lpsrt[nDestLen] = 0;
}
CXTPResourceManager::CXTPW2A::~CXTPW2A()
{
delete[] m_lpsrt;
}
CXTPResourceManager::CXTPW2A::operator LPCSTR() const
{
return m_lpsrt;
}
CXTPResourceManager::CXTPA2W::CXTPA2W(LPCSTR lptstr)
{
UINT nCodePage = XTPResourceManager()->GetLanguageInfo()->nCodePage;
int nDestLen = MultiByteToWideChar(nCodePage, 0, lptstr, -1, NULL, 0);
m_lpwsrt = new WCHAR[nDestLen + 1];
MultiByteToWideChar(nCodePage, 0, lptstr, -1, m_lpwsrt, nDestLen);
m_lpwsrt[nDestLen] = 0;
}
CXTPResourceManager::CXTPA2W::~CXTPA2W()
{
delete[] m_lpwsrt;
}
CXTPResourceManager::CXTPA2W::operator LPCWSTR() const
{
return m_lpwsrt;
}
//////////////////////////////////////////////////////////////////////////
// CXTPResourceManager
CProcessLocal<CXTPResourceManager> CXTPResourceManager::m_managerInstance;
CXTPResourceManager* AFX_CDECL XTPResourceManager()
{
return CXTPResourceManager::m_managerInstance.GetData();
}
BOOL CXTPResourceManager::SetResourceManager(CXTPResourceManager* pResourceManager)
{
if (pResourceManager == NULL)
return FALSE;
if (!pResourceManager->m_bValid)
{
delete pResourceManager;
return FALSE;
}
pResourceManager->UpdateResourcesLangID();
if (m_managerInstance.m_pObject != NULL)
delete m_managerInstance.m_pObject;
m_managerInstance.m_pObject = pResourceManager;
return TRUE;
}
/////////////////////////////////////////////////////////////////////////
// CXTPResourceManager
HINSTANCE CXTPResourceManager::m_hModXTResource = NULL;
CXTPResourceManager::CManageState::CManageState()
{
m_bSet = false;
Redo();
}
CXTPResourceManager::CManageState::~CManageState()
{
Undo();
m_hModOldResource = NULL;
}
void CXTPResourceManager::CManageState::Undo()
{
if (!m_bSet)
return;
AFX_MODULE_STATE* pModuleState = AfxGetModuleState();
pModuleState->m_hCurrentResourceHandle = m_hModOldResource;
m_bSet = false;
}
void CXTPResourceManager::CManageState::Redo()
{
if (XTPResourceManager()->GetResourceHandle() == NULL)
{
m_bSet = false;
return;
}
AFX_MODULE_STATE* pModuleState = AfxGetModuleState();
m_hModOldResource = pModuleState->m_hCurrentResourceHandle;
pModuleState->m_hCurrentResourceHandle = XTPResourceManager()->GetResourceHandle();
m_bSet = true;
}
CXTPResourceManager::CXTPResourceManager()
{
m_bValid = TRUE;
m_hResourceFile = 0;
m_pLanguageInfo = GetLanguageInfo(cwXTPResManDefLangID);
}
CXTPResourceManager::~CXTPResourceManager()
{
Close();
}
void CXTPResourceManager::Close()
{
if (m_hResourceFile != 0)
{
FreeLibrary(m_hResourceFile);
m_hResourceFile = 0;
}
}
HMODULE CXTPResourceManager::GetResourceHandle() const
{
return m_hModXTResource;
}
void CXTPResourceManager::SetResourceHandle(HMODULE hModRes)
{
m_hModXTResource = hModRes;
UpdateResourcesLangID();
}
void CXTPResourceManager::SetResourceFile(const CString& strResourceFile)
{
CString strExtension = strResourceFile.GetLength() > 3 ? strResourceFile.Right(3) : _T("");
strExtension.MakeLower();
if (strExtension == _T("xml"))
{
SetResourceManager(new CXTPResourceManagerXML(strResourceFile));
}
else
{
CXTPResourceManager* pResourceManager = new CXTPResourceManager;
pResourceManager->m_hResourceFile = strResourceFile.IsEmpty() ? 0 : LoadLibrary(strResourceFile);
if (pResourceManager->m_hResourceFile)
{
SetResourceHandle(pResourceManager->m_hResourceFile);
}
else
{
SetResourceHandle(AfxGetInstanceHandle());
}
SetResourceManager(pResourceManager);
}
}
void CXTPResourceManager::UpdateResourcesLangID()
{
HMODULE hResModule = GetResourceHandle();
WORD wLangID = GetResourceLanguage(hResModule);
ASSERT(wLangID);
SetResourceLanguage(wLangID);
}
void CXTPResourceManager::SetResourceLanguage(WORD wLangID)
{
m_pLanguageInfo = GetLanguageInfo(wLangID);
if (!m_pLanguageInfo)
m_pLanguageInfo = GetLanguageInfo(cwXTPResManDefLangID);
}
WORD CXTPResourceManager::GetResourceLanguage(HMODULE hResModule)
{
WORD wLangID = 0;
::EnumResourceTypes(hResModule, &CXTPResourceManager::EnumResTypeProc, (LONG_PTR)&wLangID);
return wLangID;
}
BOOL CXTPResourceManager::EnumResTypeProc(HMODULE hModule, LPTSTR lpszType, LONG_PTR lParam)
{
WORD* pwLangID = (WORD*)lParam;
ASSERT(pwLangID);
if (!pwLangID)
return FALSE;
::EnumResourceNames(hModule, lpszType, &CXTPResourceManager::EnumResNameProc, lParam);
if(*pwLangID == LANG_NEUTRAL)
return TRUE; // continue if neutral
return *pwLangID == cwXTPResManDefLangID; // continue if default
}
BOOL CXTPResourceManager::EnumResNameProc(HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName,
LONG_PTR lParam)
{
WORD* pwLangID = (WORD*)lParam;
ASSERT(pwLangID);
if (!pwLangID)
return FALSE;
::EnumResourceLanguages(hModule, lpszType, lpszName,
&CXTPResourceManager::EnumResLangProc, lParam);
if(*pwLangID == LANG_NEUTRAL)
return TRUE; // continue if neutral
return *pwLangID == cwXTPResManDefLangID; // continue if default
}
BOOL CXTPResourceManager::EnumResLangProc(HMODULE hModule, LPCTSTR lpszType,
LPCTSTR lpszName, WORD wIDLanguage, LONG_PTR lParam)
{
UNREFERENCED_PARAMETER(hModule); UNREFERENCED_PARAMETER(lpszType); UNREFERENCED_PARAMETER(lpszName);
WORD* pwLangID = (WORD*)lParam;
ASSERT(pwLangID);
if (!pwLangID)
return FALSE; // stop emuneration
if(wIDLanguage == LANG_NEUTRAL)
return TRUE; // continue if neutral
*pwLangID = wIDLanguage;
return *pwLangID == cwXTPResManDefLangID; // continue if default
}
BOOL CXTPResourceManager::LoadFailed()
{
#ifdef _LIB
//TRACE(_T("WARNING: Make sure to include XTToolkitPro.rc in your .rc2 file\n"));
#endif
return FALSE;
}
BOOL CXTPResourceManager::LoadString(CString* pString, UINT nIDResource)
{
HMODULE hResourceInstanse = GetResourceHandle();
if (hResourceInstanse && ::FindResource(hResourceInstanse, MAKEINTRESOURCE((nIDResource >> 4)+1), RT_STRING))
{
if (LoadLocaleString(hResourceInstanse, nIDResource, *pString))
return TRUE;
}
if (pString->LoadString(nIDResource))
return TRUE;
return LoadFailed();
}
BOOL CXTPResourceManager::LoadMenu(CMenu* lpMenu, UINT nIDResource)
{
HMODULE hResourceInstanse = GetResourceHandle();
if (hResourceInstanse && ::FindResource(hResourceInstanse, MAKEINTRESOURCE(nIDResource), RT_MENU))
{
CManageState state;
if (lpMenu->LoadMenu(nIDResource))
return TRUE;
}
if (lpMenu->LoadMenu(nIDResource))
return TRUE;
return LoadFailed();
}
BOOL CXTPResourceManager::LoadToolBar(CToolBar* pToolBar, UINT nIDResource)
{
CManageState state;
if (pToolBar->LoadToolBar(nIDResource))
return TRUE;
return LoadFailed();
}
BOOL CXTPResourceManager::LoadBitmap(CBitmap* pBitmap, UINT nIDResource)
{
HMODULE hResourceInstanse = GetResourceHandle();
if (hResourceInstanse && ::FindResource(hResourceInstanse, MAKEINTRESOURCE(nIDResource), RT_BITMAP))
{
CManageState state;
if (pBitmap->LoadBitmap(nIDResource))
return TRUE;
}
if (pBitmap->LoadBitmap(nIDResource))
return TRUE;
return LoadFailed();
}
HCURSOR CXTPResourceManager::LoadCursor(UINT nIDResource)
{
HMODULE hResourceInstanse = GetResourceHandle();
if (hResourceInstanse && ::FindResource(hResourceInstanse, MAKEINTRESOURCE(nIDResource), RT_GROUP_CURSOR))
{
CManageState state;
HCURSOR hCursor = AfxGetApp()->LoadCursor(nIDResource);
if (hCursor)
return hCursor;
}
HCURSOR hCursor = AfxGetApp()->LoadCursor(nIDResource);
if (hCursor)
return hCursor;
LoadFailed();
return NULL;
}
HGLOBAL CXTPResourceManager::LoadDialogTemplate2(LPCTSTR pszTemplate)
{
HINSTANCE hResourceInstanse = GetResourceHandle();
HRSRC hResource = hResourceInstanse ? FindResource(hResourceInstanse, pszTemplate, RT_DIALOG) : NULL;
if (hResource == NULL)
{
hResourceInstanse = AfxFindResourceHandle(pszTemplate, RT_DIALOG);
hResource = hResourceInstanse ? FindResource(hResourceInstanse, pszTemplate, RT_DIALOG) : NULL;
}
if (hResource)
{
HGLOBAL hTemplate = LoadResource(hResourceInstanse, hResource);
return hTemplate;
}
LoadFailed();
return NULL;
}
LPCDLGTEMPLATE CXTPResourceManager::LoadDialogTemplate(UINT nIDResource)
{
LPCTSTR pszTemplate = MAKEINTRESOURCE(nIDResource);
HGLOBAL hTemplate = LoadDialogTemplate2(pszTemplate);
return (LPCDLGTEMPLATE)LockResource(hTemplate);
}
BOOL CXTPResourceManager::LoadHTML(CString* pText, UINT nIDResource)
{
if (pText == NULL)
return FALSE;
HMODULE hResourceInstanse = GetResourceHandle();
HRSRC hResource = ::FindResource(hResourceInstanse, MAKEINTRESOURCE(nIDResource), RT_HTML);
if (hResource == NULL)
{
hResourceInstanse = AfxFindResourceHandle(MAKEINTRESOURCE(nIDResource), RT_HTML);
if (hResourceInstanse == NULL)
return FALSE;
hResource = ::FindResource(hResourceInstanse, MAKEINTRESOURCE(nIDResource), RT_HTML);
}
if (!hResource)
return FALSE;
HGLOBAL hMem = ::LoadResource(hResourceInstanse, hResource);
if (!hMem)
return FALSE;
DWORD dwSize = ::SizeofResource(hResourceInstanse, hResource);
char *pSrc = (char*)::LockResource(hMem);
if (!pSrc)
return FALSE;
const DWORD dwDstSize = (dwSize + 1) * sizeof(TCHAR);
TCHAR *pDst = pText->GetBuffer(dwDstSize);
if (pDst == NULL)
return FALSE;
::ZeroMemory((BYTE*)pDst, dwDstSize);
#ifdef _UNICODE
int nLen = ::MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pSrc, dwSize,
pDst, dwDstSize);
#else
::CopyMemory(pDst, pSrc, dwSize);
int nLen = dwSize;
#endif
pText->ReleaseBuffer();
return nLen > 0;
}
HICON CXTPResourceManager::CreateIconFromResource(HMODULE hModule, LPCTSTR lpszID, CSize iconSize)
{
// Find the icon directory whose identifier is lpszID.
HRSRC hResource = ::FindResource(hModule,
lpszID, RT_GROUP_ICON);
if (hResource == NULL)
return NULL;
// Load and lock the icon directory.
HGLOBAL hMem = ::LoadResource(hModule, hResource);
if (!hMem)
return NULL;
LPVOID lpResource = ::LockResource(hMem);
// Get the identifier of the icon that is most appropriate
// for the video display.
int nID = ::LookupIconIdFromDirectoryEx((PBYTE) lpResource, TRUE,
iconSize.cx, iconSize.cy, LR_DEFAULTCOLOR);
// Find the bits for the nID icon.
hResource = ::FindResource(hModule,
MAKEINTRESOURCE(nID), MAKEINTRESOURCE(RT_ICON));
if (hResource == NULL)
return NULL;
// Load and lock the icon.
hMem = ::LoadResource(hModule, hResource);
if (!hMem)
return NULL;
lpResource = ::LockResource(hMem);
// Create a handle to the icon.
HICON hIcon = ::CreateIconFromResourceEx((PBYTE)lpResource,
::SizeofResource(hModule, hResource), TRUE, 0x00030000,
iconSize.cx, iconSize.cy, LR_DEFAULTCOLOR);
return hIcon;
}
HICON CXTPResourceManager::LoadIcon(LPCTSTR lpszID, CSize iconSize)
{
HICON hIcon = NULL;
HMODULE hResource = GetResourceHandle();
if (hResource && ::FindResource(hResource, lpszID, RT_GROUP_ICON))
{
CManageState state;
hIcon = (HICON)::LoadImage(hResource, lpszID,
IMAGE_ICON, iconSize.cx, iconSize.cy, 0);
if (hIcon != NULL)
return hIcon;
}
hResource = AfxFindResourceHandle(lpszID, RT_GROUP_ICON);
if (hResource)
{
hIcon = (HICON)::LoadImage(hResource, lpszID,
IMAGE_ICON, iconSize.cx, iconSize.cy, 0);
if (hIcon != NULL)
return hIcon;
}
return NULL;
}
HICON CXTPResourceManager::LoadIcon(int nID, CSize iconSize)
{
return LoadIcon(MAKEINTRESOURCE(nID), iconSize);
}
int CXTPResourceManager::ShowMessageBox(UINT nIDPrompt, UINT nType)
{
CString strPrompt;
VERIFY(LoadString(&strPrompt, nIDPrompt));
return ShowMessageBox(strPrompt, nType);
}
int CXTPResourceManager::ShowMessageBox(LPCTSTR lpszText, UINT nType)
{
if (m_pLanguageInfo && (m_pLanguageInfo->nCodePage == 1256 || m_pLanguageInfo->nCodePage == 1255)) // Arabic or Hebrew ?
nType |= MB_RTLREADING;
return AfxMessageBox(lpszText, nType);
}
//////////////////////////////////////////////////////////////////////////
// Locale methods
XTP_RESOURCEMANAGER_LANGINFO* CXTPResourceManager::GetLanguageInfo(UINT nLangId)
{
for (int i = 0; i < _countof(langinfo); i++)
{
if (nLangId == langinfo[i].wLanguage)
return &langinfo[i];
}
return 0;
}
int CXTPResourceManager::GetMenuLocaleString(CMenu* pMenu, UINT nIDItem, CString& rString, UINT nFlags) const
{
if (!pMenu || !pMenu->m_hMenu)
return 0;
ASSERT(m_pLanguageInfo);
if (!m_pLanguageInfo)
{
return pMenu->GetMenuString(nIDItem, rString, nFlags);
}
ASSERT(::IsMenu(pMenu->m_hMenu));
// offer no buffer first
int nStringLen = ::GetMenuString(pMenu->m_hMenu, nIDItem, NULL, 0, nFlags);
// use exact buffer length
if (nStringLen > 0)
{
#ifndef _UNICODE
if (XTPSystemVersion()->IsWin2KOrGreater())
{
LPWSTR lpwstr = new WCHAR[nStringLen + 1];
::GetMenuStringW(pMenu->m_hMenu, nIDItem, lpwstr, nStringLen + 1, nFlags);
int nDestLen = WideCharToMultiByte(m_pLanguageInfo->nCodePage, 0, lpwstr, nStringLen, NULL, 0, NULL, NULL);
LPTSTR pstrString = rString.GetBufferSetLength(nDestLen);
WideCharToMultiByte(m_pLanguageInfo->nCodePage, 0, lpwstr, nStringLen, pstrString, nDestLen, NULL, NULL);
pstrString[nDestLen] = 0;
delete[] lpwstr;
rString.ReleaseBuffer();
}
else
#endif
{
LPTSTR pstrString = rString.GetBufferSetLength(nStringLen);
::GetMenuString(pMenu->m_hMenu, nIDItem, pstrString, nStringLen + 1, nFlags);
rString.ReleaseBuffer(nStringLen);
}
}
else
rString.Empty();
return nStringLen;
}
int CXTPResourceManager::LoadLocaleString(HINSTANCE hInstance, UINT nID, CString& rString) const
{
rString.Empty();
HRSRC hResource = ::FindResource(hInstance, MAKEINTRESOURCE(((nID >> 4) + 1)), RT_STRING);
if (!hResource)
return 0;
HGLOBAL hGlobal = ::LoadResource(hInstance, hResource);
if (!hGlobal)
return 0;
LPWORD pImage = (LPWORD)::LockResource(hGlobal);
if (!pImage)
return 0;
ULONG nResourceSize = ::SizeofResource(hInstance, hResource);
WORD* pImageEnd = (LPWORD)(LPBYTE(pImage) + nResourceSize);
UINT iIndex = nID & 0x000F;
while ((iIndex > 0) && (pImage < pImageEnd))
{
pImage = (LPWORD)(LPBYTE(pImage) + (sizeof(WORD) + (*pImage * sizeof(WCHAR))));
iIndex--;
}
if (pImage >= pImageEnd)
return 0;
int nLength = *pImage;
if (nLength == 0)
return 0;
#ifdef _UNICODE
LPTSTR lpsz = rString.GetBufferSetLength(nLength);
MEMCPY_S(lpsz, (LPWSTR)(pImage + 1), nLength * sizeof(WCHAR));
rString.ReleaseBuffer(nLength);
return nLength;
#else
UINT nCodePage = m_pLanguageInfo ? m_pLanguageInfo->nCodePage : CP_ACP;
int nDestLen = WideCharToMultiByte(nCodePage, 0, (LPWSTR)(pImage + 1), nLength, NULL, 0, NULL, NULL);
LPTSTR lpsz = rString.GetBufferSetLength(nDestLen);
WideCharToMultiByte(nCodePage, 0, (LPWSTR)(pImage + 1), nLength, lpsz, nDestLen, NULL, NULL);
rString.ReleaseBuffer(nDestLen);
return nDestLen;
#endif
}
#ifndef _XTP_EXCLUDE_XML
//////////////////////////////////////////////////////////////////////////
// CXTPResourceManagerXML
CXTPResourceManagerXML::CXTPResourceManagerXML(LPCTSTR strFileName)
{
m_pResourceRoot = new CXTPPropExchangeXMLNode(TRUE, 0, _T("resource"));
m_bValid = FALSE;
if (!m_pResourceRoot->LoadFromFile(strFileName))
return;
if (!m_pResourceRoot->OnBeforeExchange())
return;
m_bValid = TRUE;
}
CXTPResourceManagerXML::CXTPResourceManagerXML(CXTPPropExchangeXMLNode* pResourceRoot)
{
m_bValid = FALSE;
m_pResourceRoot = pResourceRoot;
if (m_pResourceRoot == NULL)
return;
if (!m_pResourceRoot->OnBeforeExchange())
return;
m_bValid = TRUE;
}
CXTPResourceManagerXML::~CXTPResourceManagerXML()
{
Close();
}
void CXTPResourceManagerXML::Close()
{
CXTPResourceManager::Close();
CMDTARGET_RELEASE(m_pResourceRoot);
POSITION pos = m_mapDialogs.GetStartPosition();
while (pos)
{
DLGTEMPLATE* pDlgTemplate;
UINT nIDResource;
m_mapDialogs.GetNextAssoc(pos, nIDResource, pDlgTemplate);
free (pDlgTemplate);
}
m_mapDialogs.RemoveAll();
m_bValid = FALSE;
}
void CXTPResourceManagerXML::UpdateResourcesLangID()
{
long wResourcesLangID = cwXTPResManDefLangID;
PX_Long(m_pResourceRoot, _T("LANGID"), wResourcesLangID);
SetResourceLanguage((WORD)wResourcesLangID);
}
BOOL CXTPResourceManagerXML::LoadString(CString* pString, UINT nIDResource)
{
if (!m_bValid || m_pResourceRoot == NULL)
return CXTPResourceManager::LoadString(pString, nIDResource);
CString strPattern;
strPattern.Format(_T("string[@id = \"%i\"]"), nIDResource);
if (!m_pResourceRoot->IsSectionExists(strPattern))
return CXTPResourceManager::LoadString(pString, nIDResource);
CXTPPropExchangeSection secString(m_pResourceRoot->GetSection(strPattern));
PX_String(&secString, _T("value"), *pString);
return TRUE;
}
struct CXTPResourceManagerXML::MENUITEMTEMPLATEINFO : public MENUITEMTEMPLATE
{
BSTR lpszCaption;
public:
MENUITEMTEMPLATEINFO()
{
mtOption = 0;
lpszCaption = NULL;
}
~MENUITEMTEMPLATEINFO()
{
if (lpszCaption)
{
SysFreeString(lpszCaption);
}
}
UINT GetLength() const
{
return sizeof(mtOption) + sizeof(WCHAR) * ((int)wcslen(lpszCaption) + 1) +
(mtOption & MF_POPUP ? 0 : sizeof(mtID));
}
};
struct CXTPResourceManagerXML::MENUTEMPLATEINFO
{
CArray<MENUITEMTEMPLATEINFO*, MENUITEMTEMPLATEINFO*> aItems;
public:
~MENUTEMPLATEINFO()
{
for (int i = 0; i < (int)aItems.GetSize(); i++)
{
delete aItems[i];
}
}
UINT GetLength() const
{
int nLength = sizeof(MENUITEMTEMPLATEHEADER);
for (int i = 0; i < aItems.GetSize(); i++)
{
nLength += aItems[i]->GetLength();
}
return nLength;
}
};
/////////////////////////////////////////////////////////////////////////////
// Extended dialog templates (new in Win95)
#pragma pack(push, 1)
struct CXTPResourceManagerXML::DLGTEMPLATEEX
{
WORD dlgVer;
WORD signature;
DWORD helpID;
DWORD exStyle;
DWORD style;
WORD cDlgItems;
short x;
short y;
short cx;
short cy;
};
struct CXTPResourceManagerXML::DLGITEMTEMPLATEEX
{
DWORD helpID;
DWORD exStyle;
DWORD style;
short x;
short y;
short cx;
short cy;
DWORD id;
};
#pragma pack(pop)
struct CXTPResourceManagerXML::DLGITEMTEMPLATEINFO : public DLGITEMTEMPLATEEX
{
BSTR lpszCaption;
CString strClassName;
int nCaptionID;
public:
DLGITEMTEMPLATEINFO()
{
lpszCaption = NULL;
nCaptionID = 0;
}
~DLGITEMTEMPLATEINFO()
{
if (lpszCaption)
{
SysFreeString(lpszCaption);
}
}
ULONG AlignDWord(ULONG uLong) const
{
return ((uLong + 3) & ~3);
}
UINT GetLength() const
{
return AlignDWord(sizeof(DLGITEMTEMPLATEEX)
+ ((nCaptionID != 0 ? 1 : (int)wcslen(lpszCaption)) * sizeof(WORD)) + sizeof(WORD)
+ strClassName.GetLength() * sizeof(WORD) + sizeof(WORD)
+ 0
+ sizeof(WORD)
);
}
};
struct CXTPResourceManagerXML::DLGTEMPLATEINFO : public DLGTEMPLATEEX
{
BSTR lpszCaption;
CString strFaceName;
int nPointSize;
CArray<DLGITEMTEMPLATEINFO*, DLGITEMTEMPLATEINFO*> aItems;
public:
DLGTEMPLATEINFO()
{
lpszCaption = NULL;
}
~DLGTEMPLATEINFO()
{
if (lpszCaption)
{
SysFreeString(lpszCaption);
}
for (int i = 0; i < (int)aItems.GetSize(); i++)
{
delete aItems[i];
}
}
ULONG AlignDWord(ULONG uLong) const
{
return ((uLong + 3) & ~3);
}
UINT GetHeaderLength() const
{
return AlignDWord(sizeof(DLGTEMPLATEEX)
+ sizeof(WORD)
+ sizeof(WORD)
+ ((int)wcslen(lpszCaption) * sizeof(WORD) + sizeof(WORD))
+ (style & DS_SETFONT ? strFaceName.GetLength() * sizeof(WORD) + sizeof(WORD)
+ sizeof(WORD) + sizeof(WORD) + sizeof(BYTE) + sizeof(BYTE)
: 0)
);
}
UINT GetLength() const
{
int nLength = GetHeaderLength();
for (int i = 0; i < aItems.GetSize(); i++)
{
nLength += aItems[i]->GetLength();
}
return nLength;
}
};
void CXTPResourceManagerXML::AddMenuItems(CXTPPropExchange* pPX, MENUTEMPLATEINFO* pItems)
{
CXTPPropExchangeEnumeratorPtr enumerator(pPX->GetEnumerator(_T("menuitem")));
POSITION pos = enumerator->GetPosition();
while (pos)
{
CXTPPropExchangeSection sec(enumerator->GetNext(pos));
int id = 0;
MENUITEMTEMPLATEINFO* pItemInfo = new MENUITEMTEMPLATEINFO;
PX_Int(&sec, _T("id"), id, 0);
PX_Bstr(&sec, _T("caption"), pItemInfo->lpszCaption, L"");
pItemInfo->mtID = (WORD)id;
pItems->aItems.Add(pItemInfo);
CXTPPropExchangeEnumeratorPtr enumeratorChilds(sec->GetEnumerator(_T("menuitem")));
if (enumeratorChilds->GetPosition())
{
pItemInfo->mtOption |= MF_POPUP;
AddMenuItems(&sec, pItems);
}
else if (id == 0)
{
pItemInfo->mtOption |= MF_SEPARATOR;
}
if (!pos)
{
pItemInfo->mtOption |= MF_END;
}
}
}
BOOL CXTPResourceManagerXML::CreateMenu(CMenu& menu, CXTPPropExchange* pPX)
{
MENUTEMPLATEINFO menuTemplate;
AddMenuItems(pPX, &menuTemplate);
if (menuTemplate.aItems.GetSize() == 0)
return FALSE;
ASSERT(menuTemplate.aItems[menuTemplate.aItems.GetSize() - 1]->mtOption & MF_END);
int nLength = menuTemplate.GetLength() + sizeof(MENUITEMTEMPLATE);
LPVOID lpDlgTemplate = malloc(nLength);
ZeroMemory(lpDlgTemplate, nLength);
MENUITEMTEMPLATE* mitem = (MENUITEMTEMPLATE*) ((BYTE*)lpDlgTemplate + sizeof(MENUITEMTEMPLATEHEADER));
for (int i = 0; i < menuTemplate.aItems.GetSize(); i++)
{
MENUITEMTEMPLATEINFO& itemInfo = *menuTemplate.aItems[i];
mitem->mtOption = itemInfo.mtOption;
if (itemInfo.mtOption & MF_POPUP)
{
MEMCPY_S((BYTE*)mitem + sizeof(mitem->mtOption), itemInfo.lpszCaption, (wcslen(itemInfo.lpszCaption) + 1) * sizeof(WORD));
}
else
{
mitem->mtID = itemInfo.mtID;
MEMCPY_S(mitem->mtString, itemInfo.lpszCaption, (wcslen(itemInfo.lpszCaption) + 1) * sizeof(WORD));
}
mitem = (MENUITEMTEMPLATE*) ((BYTE*)mitem + itemInfo.GetLength());
}
mitem->mtOption = MF_END;
BOOL bResult = menu.LoadMenuIndirect(lpDlgTemplate);
free(lpDlgTemplate);
return bResult;
}
BOOL CXTPResourceManagerXML::LoadMenu(CMenu* lpMenu, UINT nIDResource)
{
if (!m_bValid || m_pResourceRoot == NULL)
return CXTPResourceManager::LoadMenu(lpMenu, nIDResource);
CString strPattern;
strPattern.Format(_T("menu[@id = \"%i\"]"), nIDResource);
if (!m_pResourceRoot->IsSectionExists(strPattern))
return CXTPResourceManager::LoadMenu(lpMenu, nIDResource);
CXTPPropExchangeSection secMenu(m_pResourceRoot->GetSection(strPattern));
if (CreateMenu(*lpMenu, &secMenu))
return TRUE;
return CXTPResourceManager::LoadMenu(lpMenu, nIDResource);
}
//////////////////////////////////////////////////////////////////////////
// Utils
LPDLGTEMPLATE CXTPResourceManagerXML::CreateDialogTemplate(DLGTEMPLATEINFO& dlgTemplate)
{
int nDlgLength = dlgTemplate.GetLength();
DLGTEMPLATEEX* lpDlgTemplate = (DLGTEMPLATEEX*)malloc(nDlgLength);
if (lpDlgTemplate == NULL)
return NULL;
ZeroMemory(lpDlgTemplate, nDlgLength);
*lpDlgTemplate = dlgTemplate;
BYTE* pMain = (BYTE*) lpDlgTemplate + sizeof(DLGTEMPLATEEX) + sizeof(WORD) * 2;
// Caption
ASSERT(dlgTemplate.lpszCaption != 0);
if (!dlgTemplate.lpszCaption)
return NULL;
size_t nLength = (wcslen(dlgTemplate.lpszCaption) + 1) * sizeof(WORD);
MEMCPY_S(pMain, dlgTemplate.lpszCaption, nLength);
pMain += nLength;
if (dlgTemplate.style & DS_SETFONT)
{
*((WORD *)pMain) = (WORD)dlgTemplate.nPointSize;
pMain += sizeof(WORD);
pMain += sizeof(WORD) + sizeof(BYTE) + sizeof(BYTE);
MBSTOWCS_S((LPWSTR)pMain, dlgTemplate.strFaceName, dlgTemplate.strFaceName.GetLength() + 1);
}
pMain = (BYTE*) lpDlgTemplate + dlgTemplate.GetHeaderLength();
ASSERT(dlgTemplate.cDlgItems == dlgTemplate.aItems.GetSize());
CArray<DLGITEMTEMPLATEINFO*, DLGITEMTEMPLATEINFO*>& aItems = dlgTemplate.aItems;
for (int i = 0; i < aItems.GetSize(); i++)
{
DLGITEMTEMPLATEINFO& itemInfo = *aItems[i];
// Copy constant part of the template
*(DLGITEMTEMPLATEEX*)pMain = itemInfo;
BYTE* pControlMain = pMain + sizeof(DLGITEMTEMPLATEEX);
// Class
MBSTOWCS_S((LPWSTR)pControlMain, itemInfo.strClassName, itemInfo.strClassName.GetLength() + 1);
pControlMain += (itemInfo.strClassName.GetLength() + 1) * sizeof(WORD);
// Copy Caption
if (itemInfo.nCaptionID != 0)
{
*((PWORD)pControlMain) = 0xFFFF;
*((PWORD)pControlMain + 1) = (WORD)itemInfo.nCaptionID;
pControlMain += sizeof(WORD) * 2;
}
else
{
ASSERT(itemInfo.lpszCaption != 0);
if (itemInfo.lpszCaption)
{
nLength = (wcslen(itemInfo.lpszCaption) + 1) * sizeof(WORD);
MEMCPY_S(pControlMain, itemInfo.lpszCaption, nLength);
pControlMain += nLength;
}
else
{
pControlMain += sizeof(WORD);
}
}
// Init Data length
*((WORD *)pControlMain) = 0;
pControlMain += sizeof(WORD);
pMain += itemInfo.GetLength();
}
return (LPDLGTEMPLATE)lpDlgTemplate;
}
LPDLGTEMPLATE CXTPResourceManagerXML::CreateDialogTemplate(CXTPPropExchange* pPX)
{
DLGTEMPLATEINFO dlgTemplate;
CString strPos;
CRect rc;
DWORD dwStyle = 0, dwExtendedStyle = 0, id;
PX_DWord(pPX, _T("style"), dwStyle, 0);
PX_DWord(pPX, _T("styleex"), dwExtendedStyle, 0);
PX_Rect(pPX, _T("position"), rc, CRect(0, 0, 0, 0));
PX_String(pPX, _T("fontface"), dlgTemplate.strFaceName, _T("MS Sans Serif"));
PX_Int(pPX, _T("fontsize"), dlgTemplate.nPointSize, 8);
PX_Bstr(pPX, _T("caption"), dlgTemplate.lpszCaption, L"");
PX_DWord(pPX, _T("id"), id, 0);
dlgTemplate.x = (short)rc.left;
dlgTemplate.y = (short)rc.top;
dlgTemplate.cx = (short)rc.right;
dlgTemplate.cy = (short)rc.bottom;
dlgTemplate.style = dwStyle;
dlgTemplate.exStyle = dwExtendedStyle;
dlgTemplate.helpID = id;
dlgTemplate.cDlgItems = 0;
dlgTemplate.style |= DS_SETFONT;
dlgTemplate.dlgVer = 1;
dlgTemplate.signature = 0xFFFF;
CArray<DLGITEMTEMPLATEINFO*, DLGITEMTEMPLATEINFO*>& aItems = dlgTemplate.aItems;
CXTPPropExchangeEnumeratorPtr enumerator(pPX->GetEnumerator(_T("control")));
POSITION pos = enumerator->GetPosition();
while (pos)
{
CXTPPropExchangeSection sec(enumerator->GetNext(pos));
DLGITEMTEMPLATEINFO* pItemInfo = new DLGITEMTEMPLATEINFO;
PX_DWord(&sec, _T("style"), dwStyle, WS_CHILD | WS_VISIBLE | WS_GROUP);
PX_DWord(&sec, _T("styleex"), dwExtendedStyle, 0);
PX_Rect(&sec, _T("position"), rc, CRect(0, 0, 0, 0));
PX_Bstr(&sec, _T("caption"), pItemInfo->lpszCaption, L"");
PX_String(&sec, _T("class"), pItemInfo->strClassName, _T("STATIC"));
PX_DWord(&sec, _T("id"), id, (DWORD)IDC_STATIC);
PX_Int(&sec, _T("resource"), pItemInfo->nCaptionID, 0);
pItemInfo->x = (short)rc.left;
pItemInfo->y = (short)rc.top;
pItemInfo->cx = (short)rc.right;
pItemInfo->cy = (short)rc.bottom;
pItemInfo->style = dwStyle;
pItemInfo->exStyle = dwExtendedStyle;
pItemInfo->helpID = 0;
pItemInfo->id = id;
aItems.Add(pItemInfo);
dlgTemplate.cDlgItems++;
}
return CreateDialogTemplate(dlgTemplate);
}
LPCDLGTEMPLATE CXTPResourceManagerXML::LoadDialogTemplate(UINT nIDResource)
{
if (!m_bValid || m_pResourceRoot == NULL)
return CXTPResourceManager::LoadDialogTemplate(nIDResource);
CString strPattern;
strPattern.Format(_T("dialog[@id = \"%i\"]"), nIDResource);
DLGTEMPLATE* pTemplate = 0;
if (m_mapDialogs.Lookup(nIDResource, (DLGTEMPLATE*&)pTemplate))
return pTemplate;
if (!m_pResourceRoot->IsSectionExists(strPattern))
return CXTPResourceManager::LoadDialogTemplate(nIDResource);
CXTPPropExchangeSection secDialog(m_pResourceRoot->GetSection(strPattern));
pTemplate = CreateDialogTemplate(&secDialog);
if (pTemplate)
{
m_mapDialogs.SetAt(nIDResource, pTemplate);
return pTemplate;
}
return CXTPResourceManager::LoadDialogTemplate(nIDResource);
}
#endif
| [
"whdnrfo@gmail.com"
] | whdnrfo@gmail.com |
e2d153a44848e56b0f98e0a1ccc8be40bafd738f | 471e7253cc79f86d47c1e53b493131c748364d45 | /ddc/Cursor/m/2m_A_0dbm_1/libalgo.cpp | a1d3738ee7cbe0cd6a0b97437edac1be681d566f | [] | no_license | Quenii/adcevm | 9ed6dff30eac0dd12ecbf08ff19e555aff25c0ca | b15ad0dd33a64f26fc89dbe9c595f80abbf99230 | refs/heads/master | 2016-09-06T11:00:06.719515 | 2014-12-26T08:12:31 | 2014-12-26T08:12:31 | 34,307,888 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,876 | cpp | //
// MATLAB Compiler: 4.0 (R14)
// Date: Sat Sep 18 22:51:24 2010
// Arguments: "-B" "macro_default" "-W" "cpplib:libalgo" "-T" "link:lib"
// "ddc_func"
//
#include <stdio.h>
#include "libalgo.h"
#ifdef __cplusplus
extern "C" {
#endif
extern const unsigned char __MCC_libalgo_public_data[];
extern const char *__MCC_libalgo_name_data;
extern const char *__MCC_libalgo_root_data;
extern const unsigned char __MCC_libalgo_session_data[];
extern const char *__MCC_libalgo_matlabpath_data[];
extern const int __MCC_libalgo_matlabpath_data_count;
extern const char *__MCC_libalgo_mcr_runtime_options[];
extern const int __MCC_libalgo_mcr_runtime_option_count;
extern const char *__MCC_libalgo_mcr_application_options[];
extern const int __MCC_libalgo_mcr_application_option_count;
#ifdef __cplusplus
}
#endif
static HMCRINSTANCE _mcr_inst = NULL;
#if defined( _MSC_VER) || defined(__BORLANDC__) || defined(__WATCOMC__) || defined(__LCC__)
#include <windows.h>
static char path_to_dll[_MAX_PATH];
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, void *pv)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
char szDllPath[_MAX_PATH];
char szDir[_MAX_DIR];
if (GetModuleFileName(hInstance, szDllPath, _MAX_PATH) > 0)
{
_splitpath(szDllPath, path_to_dll, szDir, NULL, NULL);
strcat(path_to_dll, szDir);
}
else return FALSE;
}
else if (dwReason == DLL_PROCESS_DETACH)
{
}
return TRUE;
}
#endif
static int mclDefaultPrintHandler(const char *s)
{
return fwrite(s, sizeof(char), strlen(s), stdout);
}
static int mclDefaultErrorHandler(const char *s)
{
int written = 0, len = 0;
len = strlen(s);
written = fwrite(s, sizeof(char), len, stderr);
if (len > 0 && s[ len-1 ] != '\n')
written += fwrite("\n", sizeof(char), 1, stderr);
return written;
}
bool libalgoInitializeWithHandlers(
mclOutputHandlerFcn error_handler,
mclOutputHandlerFcn print_handler
)
{
if (_mcr_inst != NULL)
return true;
if (!mclmcrInitialize())
return false;
if (!mclInitializeComponentInstance(&_mcr_inst, __MCC_libalgo_public_data,
__MCC_libalgo_name_data,
__MCC_libalgo_root_data,
__MCC_libalgo_session_data,
__MCC_libalgo_matlabpath_data,
__MCC_libalgo_matlabpath_data_count,
__MCC_libalgo_mcr_runtime_options,
__MCC_libalgo_mcr_runtime_option_count,
true, NoObjectType, LibTarget,
path_to_dll, error_handler,
print_handler))
return false;
return true;
}
bool libalgoInitialize(void)
{
return libalgoInitializeWithHandlers(mclDefaultErrorHandler,
mclDefaultPrintHandler);
}
void libalgoTerminate(void)
{
if (_mcr_inst != NULL)
mclTerminateInstance(&_mcr_inst);
}
void mlxDdc_func(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
mclFeval(_mcr_inst, "ddc_func", nlhs, plhs, nrhs, prhs);
}
void ddc_func(int nargout, mwArray& FPGAout_dB, mwArray& ENOB
, mwArray& SNR, mwArray& SFDR_mdfy, const mwArray& data_i
, const mwArray& data_q, const mwArray& numbit
, const mwArray& r, const mwArray& NFFT, const mwArray& fs)
{
mclcppMlfFeval(_mcr_inst, "ddc_func", nargout, 4, 6,
&FPGAout_dB, &ENOB, &SNR, &SFDR_mdfy,
&data_i, &data_q, &numbit, &r, &NFFT, &fs);
}
| [
"quenii@e4c55939-9875-e5a8-f322-dd768a204feb"
] | quenii@e4c55939-9875-e5a8-f322-dd768a204feb |
52a40efe0ab491bd13fe78fe7fb2cbb61c346d08 | 1ab125fc9775b6c290a430bff5ddc461bd88b4a2 | /samples/Cpp/TestCpp/Classes/util/ParticleAnimeList.h | 0e234a23479b4bbdb44d05a5314f5803a8a20317 | [
"MIT"
] | permissive | skywalker1024/DeperateAcademy | d11ce9a66e9cbc62eef1d5ad517ec900afeeee8d | f91c7ac6033f87903d4033f155399e86eb5b129a | refs/heads/master | 2020-04-21T00:08:31.171738 | 2015-06-13T03:33:53 | 2015-06-13T03:33:53 | 12,448,959 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | //
// ParticleAnimeList.h
// BraveFrontier
// Created by WillArk on 10/5/12.
// Copyright (c) 2012 WillArk. All rights reserved.
//
#ifndef BraveFrontier_ParticleAnimeList_h
#define BraveFrontier_ParticleAnimeList_h
#include "cocos2d.h"
#include "ParticleAnime.h"
USING_NS_CC;
class ParticleAnimeList : public CCObject
{
public:
// インスタンスの取得
static ParticleAnimeList* shared();
// アニメを設定
void addAnime( ParticleAnime* info);
// アニメを解放
void removeAllAnime();
void removeAnime( ParticleAnime* anime );
// 件数の取得
int getCount();
// オブジェクトの取得
ParticleAnime* getObject( int index );
// 存在チェック
bool exist( string anime_id, float x, float y, int wait );
// 定期処理
void process();
// ポーズ処理
void pause();
// レジューム処理
void resume();
// add by pengchao.ye
CC_SYNTHESIZE(bool, m_removeFlg, RemoveFlg);
protected:
private:
// コンストラクタ
ParticleAnimeList();
// デストラクタ
~ParticleAnimeList();
// infoリスト
CCMutableArray<ParticleAnime*> *animeList;
};
#endif
| [
"gongchangyou@gmail.com"
] | gongchangyou@gmail.com |
f2fa92561953740b496fe5f4cc6b8070f5833045 | 948d555823c2d123601ff6c149869be377521282 | /SDK/SOT_BP_Murk_functions.cpp | 5aea65ccb3742bfaf458f9908b4fddb9e482bb15 | [] | no_license | besimbicer89/SoT-SDK | 2acf79303c65edab01107ab4511e9b9af8ab9743 | 3a4c6f3b77c1045b7ef0cddd064350056ef7d252 | refs/heads/master | 2022-04-24T01:03:37.163407 | 2020-04-27T12:45:47 | 2020-04-27T12:45:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | // SeaOfThieves (1.6.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function BP_Murk.BP_Murk_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_Murk_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Murk.BP_Murk_C.UserConstructionScript");
ABP_Murk_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"getpeyton@gmail.com"
] | getpeyton@gmail.com |
ce391b65d365106978c6c8d2a3260f2d94d2503f | beca0ef1c53ec573904726698d0f114c550b3d6c | /GameDevelopment 1.0/GameDevelopment 1.0/GameStateMachine.cpp | 57a5da7caeb381d4e16ce0256dbeea4effdb8d86 | [
"libtiff",
"IJG",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"Libpng",
"LicenseRef-scancode-unknown-license-reference",
"Zlib"
] | permissive | CaueBitten/Game_Development | 4e1b2aed4bce7db345728dacfab3bd30ba151afb | 6870d0af593b2e1c5853c731550b40c32a0a2eab | refs/heads/master | 2016-08-13T02:27:11.968167 | 2015-10-19T22:24:54 | 2015-10-19T22:24:54 | 44,567,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,028 | cpp | #include "GameStateMachine.h"
GameStateMachine::GameStateMachine()
{
}
GameStateMachine::~GameStateMachine()
{
}
void GameStateMachine::pushState(GameState * pState)
{
m_gameStates.push_back(pState);
m_gameStates.back()->onEnter();
}
void GameStateMachine::changeState(GameState * pState)
{
if (!m_gameStates.empty()) {
if (m_gameStates.back()->getStateID() == pState->getStateID()) {
return; // do nothing
}
if (m_gameStates.back()->onExit()) {
delete m_gameStates.back();
m_gameStates.pop_back();
}
}
// push back our new state
m_gameStates.push_back(pState);
// initialise it
m_gameStates.back()->onEnter();
}
void GameStateMachine::popState()
{
if (!m_gameStates.empty()) {
if (m_gameStates.back()->onExit()) {
delete m_gameStates.back();
m_gameStates.pop_back();
}
}
}
void GameStateMachine::update()
{
if (!m_gameStates.empty()) {
m_gameStates.back()->update();
}
}
void GameStateMachine::render()
{
if (!m_gameStates.empty()) {
m_gameStates.back()->render();
}
}
| [
"cauebitten5@gmail.com"
] | cauebitten5@gmail.com |
fc0f0c606edd5ecba9bbb501ff3d41040bf2e2e1 | 8decb8f77daf352ab0a4f5466322f281ebf086fc | /shield-common/InputHooks/InputHook.cpp | b05bc6420757164d7cc45aa7d5c14decc876943c | [] | no_license | SHIELD-OS/android_device_nvidia | e4ddb5f80951435674e08467175faefec21f472c | 0d5198417b08bc0838e62eca9d75125ee6cacbd5 | refs/heads/master | 2021-05-08T11:04:44.898019 | 2018-02-22T19:11:55 | 2018-02-22T19:11:55 | 119,878,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | cpp | #include "NvInputHook_Host.h"
static android::InputHook *inputHook;
void inputhook_vendor_init(android::EventHub *ehub)
{
inputHook = new android::InputHook(ehub);
}
| [
"matt.gorski@gmail.com"
] | matt.gorski@gmail.com |
7f919ea6f678f2467784cdedabcc8caa43d11b00 | 831712c60ca27e19cebc68ac243f22f039f578e8 | /src/style/function_properties.cpp | 879de84f85d17de1e57201bc8fd8205f6c94ddbb | [
"BSD-2-Clause"
] | permissive | l4u/mapbox-gl-native | 4bf3c9e4220c8f9e93c6f86cc73ceb9119116734 | 03a6c80fa7f480dbb038446c1bb7a3b3f1a9bf41 | refs/heads/master | 2021-01-16T21:15:30.380791 | 2014-08-16T01:01:49 | 2014-08-16T01:01:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,751 | cpp | #include <mbgl/style/function_properties.hpp>
#include <mbgl/style/types.hpp>
#include <cmath>
namespace mbgl {
template <typename T>
inline T interpolate(T smaller, T larger, const float factor);
template <>
inline float interpolate(const float smaller, const float larger, const float factor) {
return (smaller * (1 - factor)) + (larger * factor);
}
template <>
inline bool interpolate(const bool smaller, const bool larger, const float factor) {
return interpolate(float(smaller), float(larger), factor);
}
template <>
inline Color interpolate(const Color smaller, const Color larger, const float factor) {
return {{
interpolate(smaller[0], larger[0], factor),
interpolate(smaller[1], larger[1], factor),
interpolate(smaller[2], larger[2], factor),
interpolate(smaller[3], larger[3], factor)
}};
}
template <typename T>
inline T defaultStopsValue();
template <> inline bool defaultStopsValue() { return true; }
template <> inline float defaultStopsValue() { return 1.0f; }
template <> inline Color defaultStopsValue() { return {{ 0, 0, 0, 1 }}; }
template <typename T>
T StopsFunction<T>::evaluate(float z) const {
bool smaller = false;
float smaller_z = 0.0f;
T smaller_val {};
bool larger = false;
float larger_z = 0.0f;
T larger_val {};
for (uint32_t i = 0; i < values.size(); i++) {
float stop_z = values[i].first;
T stop_val = values[i].second;
if (stop_z <= z && (!smaller || smaller_z < stop_z)) {
smaller = true;
smaller_z = stop_z;
smaller_val = stop_val;
}
if (stop_z >= z && (!larger || larger_z > stop_z)) {
larger = true;
larger_z = stop_z;
larger_val = stop_val;
}
}
if (smaller && larger) {
if (larger_z == smaller_z || larger_val == smaller_val) {
return smaller_val;
}
const float zoomDiff = larger_z - smaller_z;
const float zoomProgress = z - smaller_z;
if (base == 1.0f) {
const float t = zoomProgress / zoomDiff;
return interpolate<T>(smaller_val, larger_val, t);
} else {
const float t = (std::pow(base, zoomProgress) - 1) / (std::pow(base, zoomDiff) - 1);
return interpolate<T>(smaller_val, larger_val, t);
}
} else if (larger) {
return larger_val;
} else if (smaller) {
return smaller_val;
} else {
// No stop defined.
return defaultStopsValue<T>();
}
}
template bool StopsFunction<bool>::evaluate(float z) const;
template float StopsFunction<float>::evaluate(float z) const;
template Color StopsFunction<Color>::evaluate(float z) const;
}
| [
"mail@kkaefer.com"
] | mail@kkaefer.com |
0021bcf09ed2412a420c6cc626b9d7267838d032 | f9afa27efcfe23bc08ef1ab76fad1b0be6c98432 | /yetanotherPalin.cpp | 64f321aee92e037fc5f9e5c16e297ab295f0efff | [] | no_license | FABhishek/CodeforcesContests | c9686a8c1e1145fe399e5b950dbe9e3080b94884 | 854675e0d2d66098f2cb332c372604c753c13847 | refs/heads/master | 2023-06-02T06:46:47.435090 | 2021-06-15T16:59:58 | 2021-06-15T16:59:58 | 377,235,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,625 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
// Policy based data structure
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define ll long long int
#define pii pair<ll,ll>
#define rep(i,st,en) for(ll i=st;i<en;i++)
#define vi vector<ll>
#define vii vector<pii>
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define eb emplace_back
#define yes cout<<"YES"<<endl; return;
#define no cout<<"NO"<<endl; return;
#define flus fflush(stdout);
#define gin(x) cerr<<#x<<" : "<<x<<" ";
#define fin cerr<<endl;
#define F first
#define S second
#define np next_permutation
#define inf 1e18
#define mod 1000000007
#define N 200009
#define PI 3.14159265358979323846
#define minpq priority_queue <ll, vector<ll>, greater<ll>>
#define maxpq priority_queue<ll>
void sout(){
cout<<endl;
}
template <typename T,typename... Types>
void sout(T var1,Types... var2){
cout<<var1<<" ";
sout(var2...);
}
void solve(){
int n;cin>>n;
vector<int>v(n);
for(int &i:v)
cin>>i;
// vector<pair<int,int>>m;
// for(int i=0;i<n;i++)
// m.push_back(i,v[i]);
for(int i=0;i<n-2;i++){
int ele1 = v[i];
for(int j=i+2;j<n;j++){
int ele2 = v[j];
if(ele1==ele2){
cout<<"YES\n";
return;}
}
}
cout<<"NO\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
clock_t t1=clock();
int t;
cin>>t;
// t=1;
while(t--){
solve();
}
cerr<<"Time elapsed: "<<(double)(clock()-t1)/1000<<" s"<<endl;
}
| [
"abhishekasc3@gmail.com"
] | abhishekasc3@gmail.com |
5152b4af1766b4cd51920d3cf0aad9740e773a25 | 176dc793a1c90c0b6af139f0e12c9b045d43fe72 | /wordMaxtrix/wordMaxtrix/wordMaxtrix.cpp | 0667c763b9ffdfc3202048216c6c867f5ed50e75 | [] | no_license | ramenshen/nijia | 331c8f3be34562243aeab4f8bfde983b7e516657 | 4d1bc5f4adc749165addcca2ad4455c96e3630fd | refs/heads/master | 2020-03-28T18:13:10.773410 | 2019-09-22T14:41:52 | 2019-09-22T14:41:52 | 148,861,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,545 | cpp | // wordMaxtrix.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<stdio.h>
#define MAXN 15
char map[MAXN][MAXN], find[MAXN] = "yizhong";
int check[MAXN][MAXN], n;
const int dir[8][2] = { {-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1} };
//const int dir[1][2] = { {0,1} };
#if 1
bool isOK(int col, int row) {
if (col < 0|| row < 0||col>=n||row>=n)
return false;
return true;
}
void search_direction_dfs(int level,int direction,int col,int row) {
if (map[col][row] != find[level])
return;
if (level == (strlen(find)-1)) {
for (int i = 0; i <= level; i++) {
check[col][row] = 1;
col -= dir[direction][0];
row -= dir[direction][1];
}
return;
}else {
int new_col = col + dir[direction][0];
int new_row = row + dir[direction][1];
if (!isOK(new_col, new_row)) {
return;
}
search_direction_dfs(level + 1, direction, new_col, new_row);
}
}
void search_dfs(int level, int col, int row) {
//搜索8个方向
for (int direction = 0; direction < 8; direction++) {
int new_col = col + dir[direction][0];
int new_row = row + dir[direction][1];
if (isOK(new_col, new_row))//判断坐标合法性
{
search_direction_dfs(level+1, direction,new_col,new_row);
}
}
}
#else
void search(int level, int col, int row) {
//direct 1
for (int direction = 0; direction < 8; direction++) {
int i = 0;
for (i = 1; i < strlen(find); i++) {
if ((col + i * dir[direction][0]) < 0 || (row + i * dir[direction][1] <0)) {
break;
}
if ((col + i * dir[direction][0]) >= n || (row + i * dir[direction][1] >= n) ) {
break;
}
if (map[col+i*dir[direction][0]][row + i*dir[direction][1]] != find[level + i]) {
break;
}
}
if (i == strlen(find)) {
check[col][row] = 1;
for (int i = 1; i < strlen(find); i++) {
check[col + i * dir[direction][0]][row + i * dir[direction][1]] = 1;
}
}
}
}
#endif
int main() {
int max_house = -2147483648;
freopen("data.in","r",stdin);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char tmp;
scanf("%c", &tmp);//故意取走换行符
for (int j = 0; j < n; j++) {
scanf("%c", &map[i][j]);
}
}
int pos;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == 'y')
#if 1
search_dfs(0,i,j);
#else
search(0, i, j);
#endif
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (check[i][j]) {
printf("%c", map[i][j]);
}
else {
printf("*");
}
}
printf("\n");
}
} | [
"ramen.sh@gmail.com"
] | ramen.sh@gmail.com |
e0e6ba3c87adb233d822e3a053ef9d089431ea50 | 1d6788f3ff60142b273ce690291efa97cca81e38 | /QtPluginManagerTest/app/widget.cpp | 659d7bff274155312e179f940da7c275003792f8 | [] | no_license | keiler2018/QtPluginManagerTest | f013b62a94a7433de2c84ab234dd2314ee4a1d88 | e0a8abf2aeed50bec521615a9d84244c67faa473 | refs/heads/master | 2020-05-21T06:26:50.004259 | 2019-05-10T08:03:46 | 2019-05-10T08:03:46 | 185,945,027 | 7 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include "widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
PluginManager::instance()->loadAllPlugins();//插件管理器 加载所有插件
PluginManager::instance()->log(QStringLiteral("测试日志插件"));
PluginManager::instance()->insert(QStringLiteral("测试数据库插件"));
}
Widget::~Widget()
{
}
| [
"39286298+kangsite@users.noreply.github.com"
] | 39286298+kangsite@users.noreply.github.com |
96db78de613c9e3d9d3caccf4d072bce0980cc3e | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /src/frontends/lean/init_module.cpp | 34c7ef7e29ace08f7a686c9e3776f9fb609abba2 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 2021-01-21T17:46:58.281426 | 2017-05-21T03:34:18 | 2017-05-21T03:34:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,573 | cpp | /*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include "frontends/lean/tokens.h"
#include "frontends/lean/parser.h"
#include "frontends/lean/parser_config.h"
#include "frontends/lean/calc.h"
#include "frontends/lean/builtin_cmds.h"
#include "frontends/lean/builtin_exprs.h"
#include "frontends/lean/inductive_cmds.h"
#include "frontends/lean/structure_instance.h"
#include "frontends/lean/parse_table.h"
#include "frontends/lean/token_table.h"
#include "frontends/lean/scanner.h"
#include "frontends/lean/pp.h"
#include "frontends/lean/decl_cmds.h"
#include "frontends/lean/prenum.h"
#include "frontends/lean/elaborator.h"
#include "frontends/lean/match_expr.h"
#include "frontends/lean/notation_cmd.h"
#include "frontends/lean/tactic_notation.h"
#include "frontends/lean/decl_attributes.h"
#include "frontends/lean/util.h"
#include "frontends/lean/info_manager.h"
#include "frontends/lean/brackets.h"
#include "frontends/lean/interactive.h"
#include "frontends/lean/completion.h"
namespace lean {
void initialize_frontend_lean_module() {
initialize_decl_attributes();
initialize_prenum();
initialize_tokens();
initialize_token_table();
initialize_parse_table();
initialize_builtin_cmds();
initialize_builtin_exprs();
initialize_scanner();
initialize_parser();
initialize_parser_config();
initialize_calc();
initialize_inductive_cmds();
initialize_structure_instance();
initialize_pp();
initialize_decl_cmds();
initialize_match_expr();
initialize_elaborator();
initialize_notation_cmd();
initialize_tactic_notation();
initialize_frontend_lean_util();
initialize_info_manager();
initialize_brackets();
initialize_interactive();
initialize_completion();
}
void finalize_frontend_lean_module() {
finalize_completion();
finalize_interactive();
finalize_brackets();
finalize_info_manager();
finalize_frontend_lean_util();
finalize_tactic_notation();
finalize_notation_cmd();
finalize_elaborator();
finalize_match_expr();
finalize_decl_cmds();
finalize_pp();
finalize_structure_instance();
finalize_inductive_cmds();
finalize_calc();
finalize_parser_config();
finalize_parser();
finalize_scanner();
finalize_builtin_exprs();
finalize_builtin_cmds();
finalize_parse_table();
finalize_token_table();
finalize_tokens();
finalize_prenum();
finalize_decl_attributes();
}
}
| [
"leonardo@microsoft.com"
] | leonardo@microsoft.com |
2233432fe5015ac14a7db432da41a12eaf0a7b43 | 27a7b51c853902d757c50cb6fc5774310d09385a | /4DyuchiGXGeometry/SearchGrid.h | 88d69959ef7fe08182e82a3546f7ca6e5ebf6b71 | [] | no_license | WildGenie/LUNAPlus | f3ce20cf5b685efe98ab841eb1068819d2314cf3 | a1d6c24ece725df097ac9a975a94139117166124 | refs/heads/master | 2021-01-11T05:24:16.253566 | 2015-06-19T21:34:46 | 2015-06-19T21:34:46 | 71,666,622 | 4 | 2 | null | 2016-10-22T21:27:35 | 2016-10-22T21:27:34 | null | UHC | C++ | false | false | 791 | h | // SearchGrid.h: interface for the CSearchGrid class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SEARCHGRID_H__E328693B_216B_458A_A51E_80087AEC7DE9__INCLUDED_)
#define AFX_SEARCHGRID_H__E328693B_216B_458A_A51E_80087AEC7DE9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "../4DYUCHIGRX_COMMON/typedef.h"
#include "SearchGridTree.h"
class CSearchGrid
{
MAABB m_aabb; // 이 그리드의 인덱스.
DWORD m_dwTriCount; // 이 그리드가 가진 삼각형 객수.
DWORD* m_pdwTriIndex; // m_Tri.ppBuff 이 인덱스다.
CSearchGridTree* m_pTree;
public:
CSearchGrid();
virtual ~CSearchGrid();
};
#endif // !defined(AFX_SEARCHGRID_H__E328693B_216B_458A_A51E_80087AEC7DE9__INCLUDED_)
| [
"brandonroode75@gmail.com"
] | brandonroode75@gmail.com |
b223fd01032df8616a168be854c572cae700830f | 74d0235c4eed1e4bc57dd906d2b3958cb48b9dba | /torch/csrc/jit/runtime/static/passes.h | 63c64b941ebf0fa1c7f8fdcd341c7e3be46fdfcb | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | anjali411/pytorch | a31ecf84fe892f19452b1063f2b1de1f88d84bb0 | 51b67f2bca3014aa5e7f675237543b8f82743032 | refs/heads/master | 2022-07-22T16:58:56.800837 | 2021-10-14T17:22:15 | 2021-10-14T17:23:55 | 208,863,312 | 1 | 0 | NOASSERTION | 2020-05-14T06:54:25 | 2019-09-16T17:56:13 | C++ | UTF-8 | C++ | false | false | 1,031 | h | #include <torch/csrc/jit/ir/ir.h>
namespace torch {
namespace jit {
TORCH_API void FuseInferenceOpsForSparseNN(
std::shared_ptr<torch::jit::Graph>& graph);
TORCH_API void FuseListUnpack(std::shared_ptr<torch::jit::Graph>& graph);
// If outputs_are_immutable is set to false, don't replace the view ops that
// produce aliases of graph outputs with the copy version.
TORCH_API void ReplaceWithCopy(
std::shared_ptr<torch::jit::Graph>& graph,
bool outputs_are_immutable = true);
TORCH_API void EnableStaticRuntimeLayerNorm(
std::shared_ptr<torch::jit::Graph>& graph);
TORCH_API void RemoveImmutableInputDictLookups(
std::shared_ptr<torch::jit::Graph>& graph);
TORCH_API bool HasInplaceOp(
std::shared_ptr<Graph>& graph,
const AliasDb& alias_db);
TORCH_API bool forwardHasOp(const Module& module, const char* op_name);
TORCH_API void FuseSignLog1P(std::shared_ptr<Graph>& graph);
TORCH_API void UseVariadicTupleUnpack(const std::shared_ptr<Graph>& graph);
} // namespace jit
} // namespace torch
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
e3fdd0ff78202dc5185550805208fd3f0d0f4b87 | 8674fd9aaeea92eb0dd0f6f3e9f3c6ea1356a2f1 | /GX/GXLib/Source/Application/API/Windows/WindowsApplication.cpp | d23b12e26bd0d695d9a361efe41b1c15bb97dc95 | [] | no_license | GeminiQvQ/Roguelike | 7757182455171c98d304c86ac348220f37d4a721 | aa0e069a21642858d2105bf11665b8eb5bb87f8b | refs/heads/master | 2022-04-20T10:54:37.550834 | 2020-04-21T19:21:41 | 2020-04-21T19:21:41 | 257,693,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,364 | cpp | // Local Includes
#include <GXLib/Application/API/Windows/WindowsApplication.h>
// Project Includes
#include <GXLib/Application/API/Windows/WindowsTypes.h>
#include <GXLib/Application/API/Windows/WindowsWindow.h>
#include <GXLib/Application/EventHandler.h>
// Stdlib Includes
#include <cassert>
#include <map>
#include <vector>
// Third-Party Includes
#include <windows.h>
#include <windowsx.h>
namespace GX
{
//-----------------------------------------------------------------------------------------------------
// Internal
//-----------------------------------------------------------------------------------------------------
struct WindowsApplication::Internal
{
static WindowsApplication* s_instance;
HINSTANCE instance;
std::map<HWND, Window*> windows;
Internal(HINSTANCE instance)
: instance {instance}
{
}
};
WindowsApplication* WindowsApplication::Internal::s_instance {nullptr};
//-----------------------------------------------------------------------------------------------------
// Construction & Destruction
//-----------------------------------------------------------------------------------------------------
WindowsApplication::WindowsApplication(HINSTANCE instance)
: m {std::make_unique<Internal>(instance)}
{
// Singleton.
assert(Internal::s_instance == nullptr);
Internal::s_instance = this;
// Window class.
WNDCLASS window_class {};
window_class.lpfnWndProc = &WindowsApplication::wnd_proc;
window_class.hInstance = instance;
window_class.lpszClassName = L"Window";
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
RegisterClass(&window_class);
}
WindowsApplication::~WindowsApplication()
{
Internal::s_instance = nullptr;
}
//-----------------------------------------------------------------------------------------------------
// Application Interface
//-----------------------------------------------------------------------------------------------------
std::pair<bool, int> WindowsApplication::process()
{
return app_proc();
}
Window* WindowsApplication::create_window(const WindowParameters& parameters)
{
auto window = new WindowsWindow(parameters, m->instance);
m->windows.insert(std::make_pair(reinterpret_cast<HWND>(window->handle()), window));
event_callback(&EventHandler::on_window_create, *window);
return window;
}
//-----------------------------------------------------------------------------------------------------
// Windows Callbacks
//-----------------------------------------------------------------------------------------------------
std::pair<bool, int> WindowsApplication::app_proc()
{
MSG message {};
auto message_result = GetMessage(&message, 0, 0, 0);
std::pair<bool, int> result {std::make_pair(true, (int)message.wParam)};
if (message_result != 0)
{
TranslateMessage(&message);
DispatchMessage(&message);
}
else
{
result.first = false;
}
return result;
}
LRESULT WindowsApplication::wnd_proc(HWND window_handle, UINT message, WPARAM wparam, LPARAM lparam)
{
auto app {Internal::s_instance};
switch (message)
{
case WM_CLOSE:
{
DestroyWindow(window_handle);
}
break;
case WM_DESTROY:
{
auto it = app->m->windows.find(window_handle);
assert(it != app->m->windows.end());
app->event_callback(&EventHandler::on_window_destroy, *it->second);
app->m->windows.erase(it);
if (app->m->windows.empty())
{
PostQuitMessage(0);
}
}
break;
case WM_SIZE:
{
auto it = app->m->windows.find(window_handle);
assert(it != app->m->windows.end());
auto width = LOWORD(lparam);
auto height = HIWORD(lparam);
app->event_callback(&EventHandler::on_window_resize, *it->second, width, height);
}
break;
case WM_KEYDOWN:
{
auto window_it = app->m->windows.find(window_handle);
auto window = (window_it != app->m->windows.end() ? window_it->second : nullptr);
auto key = get_platform_key((int)wparam);
if (key != Key::Invalid)
{
app->event_callback(&EventHandler::on_key_down, window, key, std::vector<Modifier>{});
}
}
break;
case WM_KEYUP:
{
auto window_it = app->m->windows.find(window_handle);
auto window = (window_it != app->m->windows.end() ? window_it->second : nullptr);
auto key = get_platform_key((int)wparam);
if (key != Key::Invalid)
{
app->event_callback(&EventHandler::on_key_up, window, key, std::vector<Modifier>{});
}
}
break;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
{
auto window_it = app->m->windows.find(window_handle);
auto window = (window_it != app->m->windows.end() ? window_it->second : nullptr);
auto x = GET_X_LPARAM(lparam);
auto y = GET_Y_LPARAM(lparam);
MouseButton button = MouseButton::Invalid;
switch (message)
{
case WM_LBUTTONDOWN: button = MouseButton::Left; break;
case WM_MBUTTONDOWN: button = MouseButton::Middle; break;
case WM_RBUTTONDOWN: button = MouseButton::Right; break;
}
if (button != MouseButton::Invalid)
{
app->event_callback(&EventHandler::on_mouse_button_down, window, button, x, y, std::vector<Modifier>{});
}
}
break;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
{
auto window_it = app->m->windows.find(window_handle);
auto window = (window_it != app->m->windows.end() ? window_it->second : nullptr);
auto x = GET_X_LPARAM(lparam);
auto y = GET_Y_LPARAM(lparam);
MouseButton button = MouseButton::Invalid;
switch (message)
{
case WM_LBUTTONUP: button = MouseButton::Left; break;
case WM_MBUTTONUP: button = MouseButton::Middle; break;
case WM_RBUTTONUP: button = MouseButton::Right; break;
}
if (button != MouseButton::Invalid)
{
app->event_callback(&EventHandler::on_mouse_button_up, window, button, x, y, std::vector<Modifier>{});
}
}
break;
case WM_MOUSEMOVE:
{
auto window_it = app->m->windows.find(window_handle);
auto window = (window_it != app->m->windows.end() ? window_it->second : nullptr);
auto x = GET_X_LPARAM(lparam);
auto y = GET_Y_LPARAM(lparam);
app->event_callback(&EventHandler::on_mouse_move, window, x, y);
}
break;
}
return DefWindowProc(window_handle, message, wparam, lparam);
}
} | [
"skauert@gmail.com"
] | skauert@gmail.com |
04aeaa85bcb7f3d85fb2326bbf42bb47ce03ae96 | 14f2b0257b5b3fa57ef183310aeb6f541b1068d3 | /divine/vm/lx-slot.hpp | e3f4a2f542f14f441bf7edc22061f7f95210f831 | [] | no_license | zuxichen/divine | 548d1afd514f4d56fbf54a116f1396a53a069fdd | 99b0828f71a4dfea8a355959623b851e1bb942da | refs/heads/master | 2020-09-30T19:15:58.032755 | 2019-11-01T22:50:15 | 2019-11-01T22:50:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,693 | hpp | // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/*
* (c) 2017 Petr Ročkai <code@fixp.eu>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include <divine/vm/pointer.hpp>
#include <divine/vm/value.hpp>
#include <divine/vm/divm.h>
namespace divine::vm::lx
{
/*
* Values (data) used in a program are organised into blocks of memory:
* frames (one for each function), globals (for each process) and constants
* (immutable and shared across all processes). These blocks consist of
* individual slots, one slot per value stored in the given block. Slots
* are typed and they can overlap *if* the lifetimes of the values stored
* in them do not. In this respect, slots behave like pointers into the
* given memory block. All slots are assigned statically. All LLVM Values
* are allocated into slots.
*/
struct Slot : _VM_Operand, _VM_OperandExt
{
bool pointer() { return type == Ptr || type == PtrA; }
bool alloca() { return type == PtrA; }
bool integer() { return type == I1 || type == I8 || type == I16 || type == I32 || type == I64 ||
type == I128 || type == IX; }
bool isfloat() { return type == F32 || type == F64 || type == F80; }
bool aggregate() { return type == Agg; }
bool codePointer() { return type == PtrC; }
bool ext() { return type == Other || type == Agg; }
int size() const
{
if ( type == F80 ) return 16; /* f80 is magical */
return width() % 8 ? width() / 8 + 1 : width() / 8;
}
int width() const
{
switch ( type )
{
case Void: return 0;
case I1: return 1;
case I8: return 8;
case I16: return 16;
case I32: return 32;
case I64: return 64;
case I128: return 128;
case F32: return 32;
case F64: return 64;
case F80: return 80;
case Ptr: case PtrA: case PtrC: return 64;
default: return _VM_OperandExt::width;
}
}
explicit Slot( Location l = Invalid, Type t = Void, int w = 0 )
{
type = t;
location = l;
_VM_OperandExt::width = w;
if ( w )
ASSERT_EQ( w, width() );
if ( w == 1 || w == 8 || w == 16 || w == 32 || w == 64 )
ASSERT_NEQ( type, IX );
}
explicit Slot( _VM_Operand op, _VM_OperandExt ext = _VM_OperandExt() )
: _VM_Operand( op ), _VM_OperandExt( ext )
{}
Slot &operator=( const Slot & ) & = default;
friend std::ostream &operator<<( std::ostream &o, Slot p )
{
static std::vector< std::string > t =
{ "i1", "i8", "i16", "i32", "i64", "f32", "f64", "f80",
"ptr", "ptrc", "ptra", "agg", "void", "other" };
static std::vector< std::string > l = { "const", "global", "local", "invalid" };
return o << "[" << l[ p.location ] << " " << t[ p.type ] << " @" << p.offset << " ↔"
<< p.width() << "]";
}
};
}
| [
"me@mornfall.net"
] | me@mornfall.net |
4dad363e538e5612e6bcce236846281e6301ea51 | b64845f7a1b79a86aa32a05572dae87609b73ec4 | /ТЯП/№3,4, ПИ-61, Оверченко/Diagram.h | 1e64c8ae708d4230e8d2f18608b1cb5502ea73cc | [] | no_license | ViolettaOverchenko/8semestr | e4792b895c1823171c8b140fde0fb10e36f0e2ce | f6a6919f581b99da65813480f578e179fad6dea4 | refs/heads/master | 2022-12-26T19:41:19.102036 | 2020-05-14T12:47:00 | 2020-05-14T12:47:00 | 240,630,248 | 0 | 0 | null | 2022-12-11T18:36:45 | 2020-02-15T02:02:46 | JavaScript | WINDOWS-1251 | C++ | false | false | 1,385 | h | #pragma once
#include "Scaner.h"
#include "Tree.h"
class Diagram
{
private:
TScaner* scaner;
Tree* tree = new Tree();
bool flagInterpret = true;
TData RetValue;
public:
Diagram(TScaner* s) { scaner = s; }
~Diagram() {}
void SetInterpret(bool flag) { this->flagInterpret = flag; }
bool GetInterpret() { return flagInterpret; }
void S(); // описания
void T(); // одно описание
bool FOrW(); // функция или данные
void W(); // данные
void F(); // функция
void Main(); // главная функция
void D(DataType type); // список
void Z(DataType type); // переменая, массив
void A(TData* data); // выражение
void Q(); // составной оператор
void O(); // операторы и описания
void K(); // оператор и вызов функции
void H(); // while
void U(); // присваивание, бинарное присваивание
void B(TData* data); // слагаемое
void P(TData* data);
void E(TData* data); // множитель
void X(TData* data); // элементарное выражение
void FC(TData* data); // вызов функции
TData CallFunc(Tree* func); // вызов функции 2
void V(Tree* var, TData* data); //переменная, элемент массива
void RET();
void printTree();
};
| [
"owerchenko.violetta@yandex.ru"
] | owerchenko.violetta@yandex.ru |
99d73a211427a10d99891d8c82e99a3a3d3f3e0f | b8ebbcddb89bce4b17ba5f44d5706c2904033ad9 | /svm-toy/gtk/callbacks.cpp | 723f7fc251245dcee8b1123395ad012367091c99 | [
"BSD-3-Clause"
] | permissive | aiche/libsvm-buildsystem | 58d40cc7734659b2e8a36b76848f692e88f76390 | 198db51c3d5e00c9768a24993734f9f68ca4ed1a | refs/heads/master | 2021-01-10T20:10:11.087290 | 2013-06-19T08:16:31 | 2013-06-19T08:16:31 | 3,313,859 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,309 | cpp | #include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <list>
#include "callbacks.h"
#include "interface.h"
#include <libsvm/svm.h>
using namespace std;
#define DEFAULT_PARAM "-t 2 -c 100"
#define XLEN 500
#define YLEN 500
GdkColor colors[] =
{
{0,0,0,0},
{0,0,120<<8,120<<8},
{0,120<<8,120<<8,0},
{0,120<<8,0,120<<8},
{0,0,200<<8,200<<8},
{0,200<<8,200<<8,0},
{0,200<<8,0,200<<8},
};
GdkGC *gc;
GdkPixmap *pixmap;
extern "C" GtkWidget *draw_main;
GtkWidget *draw_main;
extern "C" GtkWidget *entry_option;
GtkWidget *entry_option;
typedef struct {
double x, y;
signed char value;
} point;
list<point> point_list;
int current_value = 1;
extern "C" void svm_toy_initialize()
{
gboolean success[7];
gdk_colormap_alloc_colors(
gdk_colormap_get_system(),
colors,
7,
FALSE,
TRUE,
success);
gc = gdk_gc_new(draw_main->window);
pixmap = gdk_pixmap_new(draw_main->window,XLEN,YLEN,-1);
gdk_gc_set_foreground(gc,&colors[0]);
gdk_draw_rectangle(pixmap,gc,TRUE,0,0,XLEN,YLEN);
gtk_entry_set_text(GTK_ENTRY(entry_option),DEFAULT_PARAM);
}
void redraw_area(GtkWidget* widget, int x, int y, int w, int h)
{
gdk_draw_pixmap(widget->window,
gc,
pixmap,
x,y,x,y,w,h);
}
void draw_point(const point& p)
{
gdk_gc_set_foreground(gc,&colors[p.value+3]);
gdk_draw_rectangle(pixmap, gc, TRUE,int(p.x*XLEN),int(p.y*YLEN),4,4);
gdk_draw_rectangle(draw_main->window, gc, TRUE,int(p.x*XLEN),int(p.y*YLEN),4,4);
}
void draw_all_points()
{
for(list<point>::iterator p = point_list.begin(); p != point_list.end();p++)
draw_point(*p);
}
void clear_all()
{
point_list.clear();
gdk_gc_set_foreground(gc,&colors[0]);
gdk_draw_rectangle(pixmap,gc,TRUE,0,0,XLEN,YLEN);
redraw_area(draw_main,0,0,XLEN,YLEN);
}
void
on_button_change_clicked (GtkButton *button,
gpointer user_data)
{
++current_value;
if(current_value > 3) current_value = 1;
}
void
on_button_run_clicked (GtkButton *button,
gpointer user_data)
{
// guard
if(point_list.empty()) return;
svm_parameter param;
int i,j;
// default values
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = 0;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
// parse options
const char *p = gtk_entry_get_text(GTK_ENTRY(entry_option));
while (1) {
while (*p && *p != '-')
p++;
if (*p == '\0')
break;
p++;
switch (*p++) {
case 's':
param.svm_type = atoi(p);
break;
case 't':
param.kernel_type = atoi(p);
break;
case 'd':
param.degree = atoi(p);
break;
case 'g':
param.gamma = atof(p);
break;
case 'r':
param.coef0 = atof(p);
break;
case 'n':
param.nu = atof(p);
break;
case 'm':
param.cache_size = atof(p);
break;
case 'c':
param.C = atof(p);
break;
case 'e':
param.eps = atof(p);
break;
case 'p':
param.p = atof(p);
break;
case 'h':
param.shrinking = atoi(p);
break;
case 'b':
param.probability = atoi(p);
break;
case 'w':
++param.nr_weight;
param.weight_label = (int *)realloc(param.weight_label,sizeof(int)*param.nr_weight);
param.weight = (double *)realloc(param.weight,sizeof(double)*param.nr_weight);
param.weight_label[param.nr_weight-1] = atoi(p);
while(*p && !isspace(*p)) ++p;
param.weight[param.nr_weight-1] = atof(p);
break;
}
}
// build problem
svm_problem prob;
prob.l = point_list.size();
prob.y = new double[prob.l];
if(param.kernel_type == PRECOMPUTED)
{
}
else if(param.svm_type == EPSILON_SVR ||
param.svm_type == NU_SVR)
{
if(param.gamma == 0) param.gamma = 1;
svm_node *x_space = new svm_node[2 * prob.l];
prob.x = new svm_node *[prob.l];
i = 0;
for (list <point>::iterator q = point_list.begin(); q != point_list.end(); q++, i++)
{
x_space[2 * i].index = 1;
x_space[2 * i].value = q->x;
x_space[2 * i + 1].index = -1;
prob.x[i] = &x_space[2 * i];
prob.y[i] = q->y;
}
// build model & classify
svm_model *model = svm_train(&prob, ¶m);
svm_node x[2];
x[0].index = 1;
x[1].index = -1;
int *j = new int[XLEN];
for (i = 0; i < XLEN; i++)
{
x[0].value = (double) i / XLEN;
j[i] = (int)(YLEN*svm_predict(model, x));
}
gdk_gc_set_foreground(gc,&colors[0]);
gdk_draw_line(pixmap,gc,0,0,0,YLEN-1);
gdk_draw_line(draw_main->window,gc,0,0,0,YLEN-1);
int p = (int)(param.p * YLEN);
for(i = 1; i < XLEN; i++)
{
gdk_gc_set_foreground(gc,&colors[0]);
gdk_draw_line(pixmap,gc,i,0,i,YLEN-1);
gdk_draw_line(draw_main->window,gc,i,0,i,YLEN-1);
gdk_gc_set_foreground(gc,&colors[5]);
gdk_draw_line(pixmap,gc,i-1,j[i-1],i,j[i]);
gdk_draw_line(draw_main->window,gc,i-1,j[i-1],i,j[i]);
if(param.svm_type == EPSILON_SVR)
{
gdk_gc_set_foreground(gc,&colors[2]);
gdk_draw_line(pixmap,gc,i-1,j[i-1]+p,i,j[i]+p);
gdk_draw_line(draw_main->window,gc,i-1,j[i-1]+p,i,j[i]+p);
gdk_gc_set_foreground(gc,&colors[2]);
gdk_draw_line(pixmap,gc,i-1,j[i-1]-p,i,j[i]-p);
gdk_draw_line(draw_main->window,gc,i-1,j[i-1]-p,i,j[i]-p);
}
}
svm_free_and_destroy_model(&model);
delete[] j;
delete[] x_space;
delete[] prob.x;
delete[] prob.y;
}
else
{
if(param.gamma == 0) param.gamma = 0.5;
svm_node *x_space = new svm_node[3 * prob.l];
prob.x = new svm_node *[prob.l];
i = 0;
for (list <point>::iterator q = point_list.begin(); q != point_list.end(); q++, i++)
{
x_space[3 * i].index = 1;
x_space[3 * i].value = q->x;
x_space[3 * i + 1].index = 2;
x_space[3 * i + 1].value = q->y;
x_space[3 * i + 2].index = -1;
prob.x[i] = &x_space[3 * i];
prob.y[i] = q->value;
}
// build model & classify
svm_model *model = svm_train(&prob, ¶m);
svm_node x[3];
x[0].index = 1;
x[1].index = 2;
x[2].index = -1;
for (i = 0; i < XLEN; i++)
for (j = 0; j < YLEN; j++) {
x[0].value = (double) i / XLEN;
x[1].value = (double) j / YLEN;
double d = svm_predict(model, x);
if (param.svm_type == ONE_CLASS && d<0) d=2;
gdk_gc_set_foreground(gc,&colors[(int)d]);
gdk_draw_point(pixmap,gc,i,j);
gdk_draw_point(draw_main->window,gc,i,j);
}
svm_free_and_destroy_model(&model);
delete[] x_space;
delete[] prob.x;
delete[] prob.y;
}
free(param.weight_label);
free(param.weight);
draw_all_points();
}
void
on_button_clear_clicked (GtkButton *button,
gpointer user_data)
{
clear_all();
}
void
on_window1_destroy (GtkObject *object,
gpointer user_data)
{
gtk_exit(0);
}
gboolean
on_draw_main_button_press_event (GtkWidget *widget,
GdkEventButton *event,
gpointer user_data)
{
point p = {(double)event->x/XLEN, (double)event->y/YLEN, current_value};
point_list.push_back(p);
draw_point(p);
return FALSE;
}
gboolean
on_draw_main_expose_event (GtkWidget *widget,
GdkEventExpose *event,
gpointer user_data)
{
redraw_area(widget,
event->area.x, event->area.y,
event->area.width, event->area.height);
return FALSE;
}
GtkWidget *fileselection;
static enum { SAVE, LOAD } fileselection_flag;
void show_fileselection()
{
fileselection = create_fileselection();
gtk_signal_connect_object(
GTK_OBJECT(GTK_FILE_SELECTION(fileselection)->ok_button),
"clicked", GTK_SIGNAL_FUNC(gtk_widget_destroy),
(GtkObject *) fileselection);
gtk_signal_connect_object (GTK_OBJECT
(GTK_FILE_SELECTION(fileselection)->cancel_button),
"clicked", GTK_SIGNAL_FUNC(gtk_widget_destroy),
(GtkObject *) fileselection);
gtk_widget_show(fileselection);
}
void
on_button_save_clicked (GtkButton *button,
gpointer user_data)
{
fileselection_flag = SAVE;
show_fileselection();
}
void
on_button_load_clicked (GtkButton *button,
gpointer user_data)
{
fileselection_flag = LOAD;
show_fileselection();
}
void
on_filesel_ok_clicked (GtkButton *button,
gpointer user_data)
{
gtk_widget_hide(fileselection);
const char *filename = gtk_file_selection_get_filename(GTK_FILE_SELECTION(fileselection));
if(fileselection_flag == SAVE)
{
FILE *fp = fopen(filename,"w");
const char *p = gtk_entry_get_text(GTK_ENTRY(entry_option));
const char* svm_type_str = strstr(p, "-s ");
int svm_type = C_SVC;
if(svm_type_str != NULL)
sscanf(svm_type_str, "-s %d", &svm_type);
if(fp)
{
if(svm_type == EPSILON_SVR || svm_type == NU_SVR)
{
for(list<point>::iterator p = point_list.begin(); p != point_list.end();p++)
fprintf(fp,"%f 1:%f\n", p->y, p->x);
}
else
{
for(list<point>::iterator p = point_list.begin(); p != point_list.end();p++)
fprintf(fp,"%d 1:%f 2:%f\n", p->value, p->x, p->y);
}
fclose(fp);
}
}
else if(fileselection_flag == LOAD)
{
FILE *fp = fopen(filename,"r");
if(fp)
{
clear_all();
char buf[4096];
while(fgets(buf,sizeof(buf),fp))
{
int v;
double x,y;
if(sscanf(buf,"%d%*d:%lf%*d:%lf",&v,&x,&y)==3)
{
point p = {x,y,v};
point_list.push_back(p);
}
else if(sscanf(buf,"%lf%*d:%lf",&y,&x)==2)
{
point p = {x,y,current_value};
point_list.push_back(p);
}
else
break;
}
fclose(fp);
draw_all_points();
}
}
}
void
on_fileselection_destroy (GtkObject *object,
gpointer user_data)
{
}
void
on_filesel_cancel_clicked (GtkButton *button,
gpointer user_data)
{
}
| [
"stephan.aiche@fu-berlin.de"
] | stephan.aiche@fu-berlin.de |
db6791ecc937d1005c642ab3c9d824bdd598b08d | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /dts/src/v20211206/model/ContinueSyncJobRequest.cpp | 5accc4ee7a9d4c50a6d3258944df5772b2ade736 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 1,921 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/dts/v20211206/model/ContinueSyncJobRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Dts::V20211206::Model;
using namespace std;
ContinueSyncJobRequest::ContinueSyncJobRequest() :
m_jobIdHasBeenSet(false)
{
}
string ContinueSyncJobRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_jobIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "JobId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_jobId.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string ContinueSyncJobRequest::GetJobId() const
{
return m_jobId;
}
void ContinueSyncJobRequest::SetJobId(const string& _jobId)
{
m_jobId = _jobId;
m_jobIdHasBeenSet = true;
}
bool ContinueSyncJobRequest::JobIdHasBeenSet() const
{
return m_jobIdHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
d00e9ae0c263c67531576b1418010e93f5112932 | 94196ef8e1f3f8e13467d2049a0b1af604b9f0d3 | /Hazel/src/Hazel/OrthographicCameraController.h | 532c042c9b1d5377e1ff3076b1c3f10fb3999f9b | [
"Apache-2.0"
] | permissive | babaliaris/HazelBabaliaris | 7f7de86636def9f9f9df81c5ca5c5066ea2b9786 | e538b36b5074cc9a0af64f5e8d81905da061a546 | refs/heads/master | 2022-12-24T10:03:13.505552 | 2020-09-19T14:59:35 | 2020-09-19T14:59:35 | 294,098,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | h | #pragma once
#include "Renderer/OrthographicCamera.h"
#include "Core/Timestep.h"
#include "Hazel/Events/ApplicationEvent.h"
#include "Hazel/Events/MouseEvent.h"
namespace Hazel
{
class OrthographicCameraController
{
public:
OrthographicCameraController(float aspectRation, bool rotation = false);
inline OrthographicCamera& GetCamera() { return m_Camera; }
void OnUpdate(Timestep ts);
void OnEvent(Event& e);
inline void SetMoveSpeed(float value) { m_CameraTranslationSpeed = value; }
inline void SetRotSpeed(float value) { m_CameraRotationSpeed = value; }
inline void SetZoomSensitivity(float value) { m_ZoomSensitivity = value; }
inline void SetMaxZoom(float value) { m_MaximumZoom = value; }
private:
bool OnMouseScrolled(MouseScrolledEvent& e);
bool OnWindowResized(WindowResizeEvent& e);
private:
float m_AspectRation;
bool m_Rotation;
float m_ZoomLevel = 1.0f;
OrthographicCamera m_Camera;
glm::vec3 m_CameraPosition = { 0.0f, 0.0f, 0.0f };
float m_CameraRotation = 0;
float m_CameraTranslationSpeed = 3.0f;
float m_CameraRotationSpeed = 25.0f;
float m_ZoomSensitivity = 0.05f;
float m_MaximumZoom = 0.25f;
};
} | [
"babaliaris.nikos@gmail.com"
] | babaliaris.nikos@gmail.com |
41d3163f4bdcefd5ebb17183fdfe68cdcbec9b07 | c301a2e4592d761c915f3944663e2a8151d1dcb6 | /do-something.cpp | fdb2091d8fdc8090c0427a5d5498f81d0930023b | [
"Apache-2.0"
] | permissive | TomohiroHayashi/arduino_test1 | eb8203e4a9b950566b64cfd525b7f41634ccaea3 | 6b1bf3d1b94de5b668f809eb1ebfbc0bde91cb46 | refs/heads/master | 2020-04-01T05:58:47.112270 | 2018-10-15T02:45:14 | 2018-10-15T02:45:14 | 152,928,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cpp | #include <Arduino.h>
#include "do-something.h"
int doSomething(void) {
millis(); // this line is only here to test that we're able to refer to the builtins
uint8_t i = 1;
uint8_t j = 1;
uint8_t k = 2;
return (i + j + k);
};
| [
"hayashi@vivita.co"
] | hayashi@vivita.co |
f1827bff663438005fd711b3d30a35d953b4d978 | 4a51af77ee7bfd76d120d914599ff05d36d4e605 | /engine/include/math/FlyMath.h | ee0a1e5af2136a7c375c6784c51dca85ea2ee64f | [] | no_license | vic4key/flyEngine | 6929a3b4d60a7cf4f32191af9b76c296bcb8bfaf | 2ed68f8cd022849fbc7d93d1f42c12bfcd0de098 | refs/heads/master | 2020-03-13T20:45:12.909031 | 2018-04-26T12:40:21 | 2018-04-26T12:40:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | h | #ifndef FLYMATH_H
#define FLYMATH_H
#include <math/Helpers.h>
#include <math/FlyMatrix.h>
namespace fly
{
using Vec2f = Vector<2, float>;
using Vec3f = Vector<3, float>;
using Vec4f = Vector<4, float>;
using Vec2u = Vector<2, unsigned>;
using Vec3u = Vector<3, unsigned>;
using Vec4u = Vector<4, unsigned>;
using Vec2i = Vector<2, int>;
using Vec3i = Vector<3, int>;
using Vec4i = Vector<4, int>;
using Mat2f = Matrix<2, 2, float>;
using Mat3f = Matrix<3, 3, float>;
using Mat4f = Matrix<4, 4, float>;
}
#endif
| [
"phips10@gmx.at"
] | phips10@gmx.at |
199e46f04134a29f3dbb23c2bd6df3be70109938 | 460455e7990de7257aa223a58e73069f3ef7ff43 | /src/server/scripts/World/go_scripts.cpp | 473d494679fbcf3cbd4a8c132cd7b7fda81a4fec | [] | no_license | Shkipper/wmane | 2ce69adea1eedf866921c857cbc5bd1bc6d037f0 | 2da37e1e758f17b61efb6aae8fa7343b234f3dcd | refs/heads/master | 2020-04-24T19:51:51.897587 | 2019-02-25T06:14:18 | 2019-02-25T06:14:18 | 172,225,859 | 0 | 0 | null | 2019-02-23T14:49:31 | 2019-02-23T14:49:31 | null | UTF-8 | C++ | false | false | 42,015 | cpp | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ContentData
go_cat_figurine (the "trap" version of GO, two different exist)
go_northern_crystal_pylon
go_eastern_crystal_pylon
go_western_crystal_pylon
go_barov_journal
go_ethereum_prison
go_ethereum_stasis
go_sacred_fire_of_life
go_shrine_of_the_birds
go_southfury_moonstone
go_field_repair_bot_74A
go_orb_of_command
go_resonite_cask
go_tablet_of_madness
go_tablet_of_the_seven
go_tele_to_dalaran_crystal
go_tele_to_violet_stand
go_scourge_cage
go_jotunheim_cage
go_table_theka
go_soulwell
go_bashir_crystalforge
go_ethereal_teleport_pad
go_soulwell
go_dragonflayer_cage
go_tadpole_cage
go_amberpine_outhouse
go_hive_pod
go_gjalerbron_cage
go_large_gjalerbron_cage
go_veil_skith_cage
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "GameObjectAI.h"
#include "Spell.h"
/*######
## go_cat_figurine
######*/
enum CatFigurine
{
SPELL_SUMMON_GHOST_SABER = 5968,
};
class go_cat_figurine : public GameObjectScript
{
public:
go_cat_figurine() : GameObjectScript("go_cat_figurine") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
player->CastSpell(player, SPELL_SUMMON_GHOST_SABER, true);
return false;
}
};
/*######
## go_crystal_pylons (3x)
######*/
class go_northern_crystal_pylon : public GameObjectScript
{
public:
go_northern_crystal_pylon() : GameObjectScript("go_northern_crystal_pylon") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
{
player->PrepareQuestMenu(go->GetGUID());
player->SendPreparedQuest(go->GetGUID());
}
if (player->GetQuestStatus(4285) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(4285);
return true;
}
};
class go_eastern_crystal_pylon : public GameObjectScript
{
public:
go_eastern_crystal_pylon() : GameObjectScript("go_eastern_crystal_pylon") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
{
player->PrepareQuestMenu(go->GetGUID());
player->SendPreparedQuest(go->GetGUID());
}
if (player->GetQuestStatus(4287) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(4287);
return true;
}
};
class go_western_crystal_pylon : public GameObjectScript
{
public:
go_western_crystal_pylon() : GameObjectScript("go_western_crystal_pylon") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
{
player->PrepareQuestMenu(go->GetGUID());
player->SendPreparedQuest(go->GetGUID());
}
if (player->GetQuestStatus(4288) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(4288);
return true;
}
};
/*######
## go_barov_journal
######*/
class go_barov_journal : public GameObjectScript
{
public:
go_barov_journal() : GameObjectScript("go_barov_journal") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->HasSkill(SKILL_TAILORING) && player->GetBaseSkillValue(SKILL_TAILORING) >= 280 && !player->HasSpell(26086))
player->CastSpell(player, 26095, false);
return true;
}
};
/*######
## go_field_repair_bot_74A
######*/
class go_field_repair_bot_74A : public GameObjectScript
{
public:
go_field_repair_bot_74A() : GameObjectScript("go_field_repair_bot_74A") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->HasSkill(SKILL_ENGINEERING) && player->GetBaseSkillValue(SKILL_ENGINEERING) >= 300 && !player->HasSpell(22704))
player->CastSpell(player, 22864, false);
return true;
}
};
/*######
## go_gilded_brazier (Paladin First Trail quest (9678))
######*/
enum GildedBrazier
{
NPC_STILLBLADE = 17716,
};
class go_gilded_brazier : public GameObjectScript
{
public:
go_gilded_brazier() : GameObjectScript("go_gilded_brazier") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_GOOBER)
{
if (player->GetQuestStatus(9678) == QUEST_STATUS_INCOMPLETE)
{
if (Creature* Stillblade = player->SummonCreature(NPC_STILLBLADE, 8106.11f, -7542.06f, 151.775f, 3.02598f, TEMPSUMMON_DEAD_DESPAWN, 60000))
Stillblade->AI()->AttackStart(player);
}
}
return true;
}
};
/*######
## go_orb_of_command
######*/
class go_orb_of_command : public GameObjectScript
{
public:
go_orb_of_command() : GameObjectScript("go_orb_of_command") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->GetQuestRewardStatus(7761))
player->CastSpell(player, 23460, true);
return true;
}
};
/*######
## go_tablet_of_madness
######*/
class go_tablet_of_madness : public GameObjectScript
{
public:
go_tablet_of_madness() : GameObjectScript("go_tablet_of_madness") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->HasSkill(SKILL_ALCHEMY) && player->GetSkillValue(SKILL_ALCHEMY) >= 300 && !player->HasSpell(24266))
player->CastSpell(player, 24267, false);
return true;
}
};
/*######
## go_tablet_of_the_seven
######*/
class go_tablet_of_the_seven : public GameObjectScript
{
public:
go_tablet_of_the_seven() : GameObjectScript("go_tablet_of_the_seven") { }
//TODO: use gossip option ("Transcript the Tablet") instead, if Trinity adds support.
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER)
return true;
if (player->GetQuestStatus(4296) == QUEST_STATUS_INCOMPLETE)
player->CastSpell(player, 15065, false);
return true;
}
};
/*#####
## go_jump_a_tron
######*/
class go_jump_a_tron : public GameObjectScript
{
public:
go_jump_a_tron() : GameObjectScript("go_jump_a_tron") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->GetQuestStatus(10111) == QUEST_STATUS_INCOMPLETE)
player->CastSpell(player, 33382, true);
return true;
}
};
/*######
## go_ethereum_prison
######*/
enum EthereumPrison
{
SPELL_REP_LC = 39456,
SPELL_REP_SHAT = 39457,
SPELL_REP_CE = 39460,
SPELL_REP_CON = 39474,
SPELL_REP_KT = 39475,
SPELL_REP_SPOR = 39476
};
const uint32 NpcPrisonEntry[] =
{
22810, 22811, 22812, 22813, 22814, 22815, //good guys
20783, 20784, 20785, 20786, 20788, 20789, 20790 //bad guys
};
class go_ethereum_prison : public GameObjectScript
{
public:
go_ethereum_prison() : GameObjectScript("go_ethereum_prison") { }
bool OnGossipHello(Player* player, GameObject* go)
{
int Random = rand() % (sizeof(NpcPrisonEntry) / sizeof(uint32));
if (Creature* creature = player->SummonCreature(NpcPrisonEntry[Random], go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), go->GetAngle(player),
TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000))
{
if (!creature->IsHostileTo(player))
{
if (FactionTemplateEntry const* pFaction = creature->getFactionTemplateEntry())
{
uint32 Spell = 0;
switch (pFaction->faction)
{
case 1011: Spell = SPELL_REP_LC; break;
case 935: Spell = SPELL_REP_SHAT; break;
case 942: Spell = SPELL_REP_CE; break;
case 933: Spell = SPELL_REP_CON; break;
case 989: Spell = SPELL_REP_KT; break;
case 970: Spell = SPELL_REP_SPOR; break;
}
if (Spell)
creature->CastSpell(player, Spell, false);
else
TC_LOG_ERROR("scripts", "go_ethereum_prison summoned Creature (entry %u) but faction (%u) are not expected by script.", creature->GetEntry(), creature->getFaction());
}
}
}
return false;
}
};
/*######
## go_ethereum_stasis
######*/
const uint32 NpcStasisEntry[] =
{
22825, 20888, 22827, 22826, 22828
};
class go_ethereum_stasis : public GameObjectScript
{
public:
go_ethereum_stasis() : GameObjectScript("go_ethereum_stasis") { }
bool OnGossipHello(Player* player, GameObject* go)
{
int Random = rand() % (sizeof(NpcStasisEntry) / sizeof(uint32));
player->SummonCreature(NpcStasisEntry[Random], go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), go->GetAngle(player),
TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000);
return false;
}
};
/*######
## go_resonite_cask
######*/
enum ResoniteCask
{
NPC_GOGGEROC = 11920
};
class go_resonite_cask : public GameObjectScript
{
public:
go_resonite_cask() : GameObjectScript("go_resonite_cask") { }
bool OnGossipHello(Player* /*player*/, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_GOOBER)
go->SummonCreature(NPC_GOGGEROC, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 300000);
return false;
}
};
/*######
## go_sacred_fire_of_life
######*/
#define NPC_ARIKARA 10882
class go_sacred_fire_of_life : public GameObjectScript
{
public:
go_sacred_fire_of_life() : GameObjectScript("go_sacred_fire_of_life") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_GOOBER)
player->SummonCreature(NPC_ARIKARA, -5008.338f, -2118.894f, 83.657f, 0.874f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000);
return true;
}
};
/*######
## go_shrine_of_the_birds
######*/
enum ShrineOfTheBirds
{
NPC_HAWK_GUARD = 22992,
NPC_EAGLE_GUARD = 22993,
NPC_FALCON_GUARD = 22994,
GO_SHRINE_HAWK = 185551,
GO_SHRINE_EAGLE = 185547,
GO_SHRINE_FALCON = 185553
};
class go_shrine_of_the_birds : public GameObjectScript
{
public:
go_shrine_of_the_birds() : GameObjectScript("go_shrine_of_the_birds") { }
bool OnGossipHello(Player* player, GameObject* go)
{
uint32 BirdEntry = 0;
float fX, fY, fZ;
go->GetClosePoint(fX, fY, fZ, go->GetObjectSize(), INTERACTION_DISTANCE);
switch (go->GetEntry())
{
case GO_SHRINE_HAWK:
BirdEntry = NPC_HAWK_GUARD;
break;
case GO_SHRINE_EAGLE:
BirdEntry = NPC_EAGLE_GUARD;
break;
case GO_SHRINE_FALCON:
BirdEntry = NPC_FALCON_GUARD;
break;
}
if (BirdEntry)
player->SummonCreature(BirdEntry, fX, fY, fZ, go->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
return false;
}
};
/*######
## go_southfury_moonstone
######*/
enum Southfury
{
NPC_RIZZLE = 23002,
SPELL_BLACKJACK = 39865, //stuns player
SPELL_SUMMON_RIZZLE = 39866
};
class go_southfury_moonstone : public GameObjectScript
{
public:
go_southfury_moonstone() : GameObjectScript("go_southfury_moonstone") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
//implicitTarget=48 not implemented as of writing this code, and manual summon may be just ok for our purpose
//player->CastSpell(player, SPELL_SUMMON_RIZZLE, false);
if (Creature* creature = player->SummonCreature(NPC_RIZZLE, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0))
creature->CastSpell(player, SPELL_BLACKJACK, false);
return false;
}
};
/*######
## go_tele_to_dalaran_crystal
######*/
enum DalaranCrystal
{
QUEST_LEARN_LEAVE_RETURN = 12790,
QUEST_TELE_CRYSTAL_FLAG = 12845
};
#define GO_TELE_TO_DALARAN_CRYSTAL_FAILED "This teleport crystal cannot be used until the teleport crystal in Dalaran has been used at least once."
class go_tele_to_dalaran_crystal : public GameObjectScript
{
public:
go_tele_to_dalaran_crystal() : GameObjectScript("go_tele_to_dalaran_crystal") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->GetQuestRewardStatus(QUEST_TELE_CRYSTAL_FLAG))
return false;
player->GetSession()->SendNotification(GO_TELE_TO_DALARAN_CRYSTAL_FAILED);
return true;
}
};
/*######
## go_tele_to_violet_stand
######*/
class go_tele_to_violet_stand : public GameObjectScript
{
public:
go_tele_to_violet_stand() : GameObjectScript("go_tele_to_violet_stand") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->GetQuestRewardStatus(QUEST_LEARN_LEAVE_RETURN) || player->GetQuestStatus(QUEST_LEARN_LEAVE_RETURN) == QUEST_STATUS_INCOMPLETE)
return false;
return true;
}
};
/*######
## go_fel_crystalforge
######*/
#define GOSSIP_FEL_CRYSTALFORGE_TEXT 31000
#define GOSSIP_FEL_CRYSTALFORGE_ITEM_TEXT_RETURN 31001
#define GOSSIP_FEL_CRYSTALFORGE_ITEM_1 "Purchase 1 Unstable Flask of the Beast for the cost of 10 Apexis Shards"
#define GOSSIP_FEL_CRYSTALFORGE_ITEM_5 "Purchase 5 Unstable Flask of the Beast for the cost of 50 Apexis Shards"
#define GOSSIP_FEL_CRYSTALFORGE_ITEM_RETURN "Use the fel crystalforge to make another purchase."
enum FelCrystalforge
{
SPELL_CREATE_1_FLASK_OF_BEAST = 40964,
SPELL_CREATE_5_FLASK_OF_BEAST = 40965,
};
class go_fel_crystalforge : public GameObjectScript
{
public:
go_fel_crystalforge() : GameObjectScript("go_fel_crystalforge") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER) /* != GAMEOBJECT_TYPE_QUESTGIVER) */
player->PrepareQuestMenu(go->GetGUID()); /* return true*/
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FEL_CRYSTALFORGE_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FEL_CRYSTALFORGE_ITEM_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(GOSSIP_FEL_CRYSTALFORGE_TEXT, go->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, GameObject* go, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF:
player->CastSpell(player, SPELL_CREATE_1_FLASK_OF_BEAST, false);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FEL_CRYSTALFORGE_ITEM_RETURN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(GOSSIP_FEL_CRYSTALFORGE_ITEM_TEXT_RETURN, go->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 1:
player->CastSpell(player, SPELL_CREATE_5_FLASK_OF_BEAST, false);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FEL_CRYSTALFORGE_ITEM_RETURN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(GOSSIP_FEL_CRYSTALFORGE_ITEM_TEXT_RETURN, go->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FEL_CRYSTALFORGE_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_FEL_CRYSTALFORGE_ITEM_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(GOSSIP_FEL_CRYSTALFORGE_TEXT, go->GetGUID());
break;
}
return true;
}
};
/*######
## go_bashir_crystalforge
######*/
#define GOSSIP_BASHIR_CRYSTALFORGE_TEXT 31100
#define GOSSIP_BASHIR_CRYSTALFORGE_ITEM_TEXT_RETURN 31101
#define GOSSIP_BASHIR_CRYSTALFORGE_ITEM_1 "Purchase 1 Unstable Flask of the Sorcerer for the cost of 10 Apexis Shards"
#define GOSSIP_BASHIR_CRYSTALFORGE_ITEM_5 "Purchase 5 Unstable Flask of the Sorcerer for the cost of 50 Apexis Shards"
#define GOSSIP_BASHIR_CRYSTALFORGE_ITEM_RETURN "Use the bashir crystalforge to make another purchase."
enum BashirCrystalforge
{
SPELL_CREATE_1_FLASK_OF_SORCERER = 40968,
SPELL_CREATE_5_FLASK_OF_SORCERER = 40970,
};
class go_bashir_crystalforge : public GameObjectScript
{
public:
go_bashir_crystalforge() : GameObjectScript("go_bashir_crystalforge") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER) /* != GAMEOBJECT_TYPE_QUESTGIVER) */
player->PrepareQuestMenu(go->GetGUID()); /* return true*/
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BASHIR_CRYSTALFORGE_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BASHIR_CRYSTALFORGE_ITEM_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(GOSSIP_BASHIR_CRYSTALFORGE_TEXT, go->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, GameObject* go, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF:
player->CastSpell(player, SPELL_CREATE_1_FLASK_OF_SORCERER, false);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BASHIR_CRYSTALFORGE_ITEM_RETURN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(GOSSIP_BASHIR_CRYSTALFORGE_ITEM_TEXT_RETURN, go->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 1:
player->CastSpell(player, SPELL_CREATE_5_FLASK_OF_SORCERER, false);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BASHIR_CRYSTALFORGE_ITEM_RETURN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->SEND_GOSSIP_MENU(GOSSIP_BASHIR_CRYSTALFORGE_ITEM_TEXT_RETURN, go->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF + 2:
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BASHIR_CRYSTALFORGE_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_BASHIR_CRYSTALFORGE_ITEM_5, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(GOSSIP_BASHIR_CRYSTALFORGE_TEXT, go->GetGUID());
break;
}
return true;
}
};
/*######
## matrix_punchograph
######*/
enum MatrixPunchograph
{
ITEM_WHITE_PUNCH_CARD = 9279,
ITEM_YELLOW_PUNCH_CARD = 9280,
ITEM_BLUE_PUNCH_CARD = 9282,
ITEM_RED_PUNCH_CARD = 9281,
ITEM_PRISMATIC_PUNCH_CARD = 9316,
SPELL_YELLOW_PUNCH_CARD = 11512,
SPELL_BLUE_PUNCH_CARD = 11525,
SPELL_RED_PUNCH_CARD = 11528,
SPELL_PRISMATIC_PUNCH_CARD = 11545,
MATRIX_PUNCHOGRAPH_3005_A = 142345,
MATRIX_PUNCHOGRAPH_3005_B = 142475,
MATRIX_PUNCHOGRAPH_3005_C = 142476,
MATRIX_PUNCHOGRAPH_3005_D = 142696,
};
class go_matrix_punchograph : public GameObjectScript
{
public:
go_matrix_punchograph() : GameObjectScript("go_matrix_punchograph") { }
bool OnGossipHello(Player* player, GameObject* go)
{
switch (go->GetEntry())
{
case MATRIX_PUNCHOGRAPH_3005_A:
if (player->HasItemCount(ITEM_WHITE_PUNCH_CARD))
{
player->DestroyItemCount(ITEM_WHITE_PUNCH_CARD, 1, true);
player->CastSpell(player, SPELL_YELLOW_PUNCH_CARD, true);
}
break;
case MATRIX_PUNCHOGRAPH_3005_B:
if (player->HasItemCount(ITEM_YELLOW_PUNCH_CARD))
{
player->DestroyItemCount(ITEM_YELLOW_PUNCH_CARD, 1, true);
player->CastSpell(player, SPELL_BLUE_PUNCH_CARD, true);
}
break;
case MATRIX_PUNCHOGRAPH_3005_C:
if (player->HasItemCount(ITEM_BLUE_PUNCH_CARD))
{
player->DestroyItemCount(ITEM_BLUE_PUNCH_CARD, 1, true);
player->CastSpell(player, SPELL_RED_PUNCH_CARD, true);
}
break;
case MATRIX_PUNCHOGRAPH_3005_D:
if (player->HasItemCount(ITEM_RED_PUNCH_CARD))
{
player->DestroyItemCount(ITEM_RED_PUNCH_CARD, 1, true);
player->CastSpell(player, SPELL_PRISMATIC_PUNCH_CARD, true);
}
break;
default:
break;
}
return false;
}
};
/*######
## go_scourge_cage
######*/
enum ScourgeCage
{
NPC_SCOURGE_PRISONER = 25610
};
class go_scourge_cage : public GameObjectScript
{
public:
go_scourge_cage() : GameObjectScript("go_scourge_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (Creature* pNearestPrisoner = go->FindNearestCreature(NPC_SCOURGE_PRISONER, 5.0f, true))
{
go->SetGoState(GO_STATE_ACTIVE);
player->KilledMonsterCredit(NPC_SCOURGE_PRISONER, pNearestPrisoner->GetGUID());
pNearestPrisoner->DisappearAndDie();
}
return true;
}
};
/*######
## go_arcane_prison
######*/
enum ArcanePrison
{
QUEST_PRISON_BREAK = 11587,
SPELL_ARCANE_PRISONER_KILL_CREDIT = 45456
};
class go_arcane_prison : public GameObjectScript
{
public:
go_arcane_prison() : GameObjectScript("go_arcane_prison") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (player->GetQuestStatus(QUEST_PRISON_BREAK) == QUEST_STATUS_INCOMPLETE)
{
go->SummonCreature(25318, 3485.089844f, 6115.7422188f, 70.966812f, 0, TEMPSUMMON_TIMED_DESPAWN, 60000);
player->CastSpell(player, SPELL_ARCANE_PRISONER_KILL_CREDIT, true);
return true;
}
return false;
}
};
/*######
## go_blood_filled_orb
######*/
#define NPC_ZELEMAR 17830
class go_blood_filled_orb : public GameObjectScript
{
public:
go_blood_filled_orb() : GameObjectScript("go_blood_filled_orb") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (go->GetGoType() == GAMEOBJECT_TYPE_GOOBER)
player->SummonCreature(NPC_ZELEMAR, -369.746f, 166.759f, -21.50f, 5.235f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 30000);
return true;
}
};
/*######
## go_jotunheim_cage
######*/
enum JotunheimCage
{
NPC_EBON_BLADE_PRISONER_HUMAN = 30186,
NPC_EBON_BLADE_PRISONER_NE = 30194,
NPC_EBON_BLADE_PRISONER_TROLL = 30196,
NPC_EBON_BLADE_PRISONER_ORC = 30195,
SPELL_SUMMON_BLADE_KNIGHT_H = 56207,
SPELL_SUMMON_BLADE_KNIGHT_NE = 56209,
SPELL_SUMMON_BLADE_KNIGHT_ORC = 56212,
SPELL_SUMMON_BLADE_KNIGHT_TROLL = 56214
};
class go_jotunheim_cage : public GameObjectScript
{
public:
go_jotunheim_cage() : GameObjectScript("go_jotunheim_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
Creature* pPrisoner = go->FindNearestCreature(NPC_EBON_BLADE_PRISONER_HUMAN, 5.0f, true);
if (!pPrisoner)
{
pPrisoner = go->FindNearestCreature(NPC_EBON_BLADE_PRISONER_TROLL, 5.0f, true);
if (!pPrisoner)
{
pPrisoner = go->FindNearestCreature(NPC_EBON_BLADE_PRISONER_ORC, 5.0f, true);
if (!pPrisoner)
pPrisoner = go->FindNearestCreature(NPC_EBON_BLADE_PRISONER_NE, 5.0f, true);
}
}
if (!pPrisoner || !pPrisoner->IsAlive())
return false;
pPrisoner->DisappearAndDie();
player->KilledMonsterCredit(NPC_EBON_BLADE_PRISONER_HUMAN, 0);
switch (pPrisoner->GetEntry())
{
case NPC_EBON_BLADE_PRISONER_HUMAN:
player->CastSpell(player, SPELL_SUMMON_BLADE_KNIGHT_H, true);
break;
case NPC_EBON_BLADE_PRISONER_NE:
player->CastSpell(player, SPELL_SUMMON_BLADE_KNIGHT_NE, true);
break;
case NPC_EBON_BLADE_PRISONER_TROLL:
player->CastSpell(player, SPELL_SUMMON_BLADE_KNIGHT_TROLL, true);
break;
case NPC_EBON_BLADE_PRISONER_ORC:
player->CastSpell(player, SPELL_SUMMON_BLADE_KNIGHT_ORC, true);
break;
}
return true;
}
};
enum TableTheka
{
GOSSIP_TABLE_THEKA = 1653,
QUEST_SPIDER_GOLD = 2936
};
class go_table_theka : public GameObjectScript
{
public:
go_table_theka() : GameObjectScript("go_table_theka") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (player->GetQuestStatus(QUEST_SPIDER_GOLD) == QUEST_STATUS_INCOMPLETE)
player->AreaExploredOrEventHappens(QUEST_SPIDER_GOLD);
player->SEND_GOSSIP_MENU(GOSSIP_TABLE_THEKA, go->GetGUID());
return true;
}
};
/*######
## go_inconspicuous_landmark
######*/
enum InconspicuousLandmark
{
SPELL_SUMMON_PIRATES_TREASURE_AND_TRIGGER_MOB = 11462,
ITEM_CUERGOS_KEY = 9275,
};
class go_inconspicuous_landmark : public GameObjectScript
{
public:
go_inconspicuous_landmark() : GameObjectScript("go_inconspicuous_landmark") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
if (player->HasItemCount(ITEM_CUERGOS_KEY))
return false;
player->CastSpell(player, SPELL_SUMMON_PIRATES_TREASURE_AND_TRIGGER_MOB, true);
return true;
}
};
/*######
## go_ethereal_teleport_pad
######*/
enum EtherealTeleportPad
{
NPC_IMAGE_WIND_TRADER = 20518,
ITEM_TELEPORTER_POWER_PACK = 28969,
};
class go_ethereal_teleport_pad : public GameObjectScript
{
public:
go_ethereal_teleport_pad() : GameObjectScript("go_ethereal_teleport_pad") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (!player->HasItemCount(ITEM_TELEPORTER_POWER_PACK))
return false;
go->SummonCreature(NPC_IMAGE_WIND_TRADER, go->GetPositionX(), go->GetPositionY(), go->GetPositionZ(), go->GetAngle(player), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000);
return true;
}
};
/*######
## go_soulwell
######*/
enum SoulWellData
{
GO_SOUL_WELL = 181621,
SPELL_HEALTH_STONE = 23517
};
class go_soulwell : public GameObjectScript
{
public:
go_soulwell() : GameObjectScript("go_soulwell") { }
struct go_soulwellAI : public GameObjectAI
{
go_soulwellAI(GameObject* go) : GameObjectAI(go)
{
_stoneId = 0;
_stoneSpell = SPELL_HEALTH_STONE;
if (_stoneSpell == 0) // Should never happen
return;
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(_stoneSpell);
if (!spellInfo)
return;
_stoneId = spellInfo->Effects[EFFECT_0].ItemType;
}
/// Due to the fact that this GameObject triggers CMSG_GAMEOBJECT_USE
/// _and_ CMSG_GAMEOBJECT_REPORT_USE, this GossipHello hook is called
/// twice. The script's handling is fine as it won't remove two charges
/// on the well. We have to find how to segregate REPORT_USE and USE.
bool GossipHello(Player* player)
{
Unit* owner = go->GetOwner();
if (_stoneSpell == 0 || _stoneId == 0)
return true;
if (!owner || owner->GetTypeId() != TYPEID_PLAYER || !player->IsInSameRaidWith(owner->ToPlayer()))
return true;
// Don't try to add a stone if we already have one.
if (player->HasItemCount(_stoneId, 1))
{
if (SpellInfo const* spell = sSpellMgr->GetSpellInfo(_stoneSpell))
Spell::SendCastResult(player, spell, NULL, 1, SPELL_FAILED_TOO_MANY_OF_ITEM);
return true;
}
player->CastSpell(player, _stoneSpell, true);
return false;
}
private:
uint32 _stoneSpell;
uint32 _stoneId;
};
GameObjectAI* GetAI(GameObject* go) const
{
return new go_soulwellAI(go);
}
};
/*######
## Quest 11255: Prisoners of Wyrmskull
## go_dragonflayer_cage
######*/
enum PrisonersOfWyrmskull
{
QUEST_PRISONERS_OF_WYRMSKULL = 11255,
QUEST_OBJECTIVE_VALGARDE_PRISONER_RESCUED = 252112,
NPC_PRISONER_PRIEST = 24086,
NPC_PRISONER_MAGE = 24088,
NPC_PRISONER_WARRIOR = 24089,
NPC_PRISONER_PALADIN = 24090
};
class go_dragonflayer_cage : public GameObjectScript
{
public:
go_dragonflayer_cage() : GameObjectScript("go_dragonflayer_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (player->GetQuestStatus(QUEST_PRISONERS_OF_WYRMSKULL) != QUEST_STATUS_INCOMPLETE)
return true;
Creature* pPrisoner = go->FindNearestCreature(NPC_PRISONER_PRIEST, 2.0f);
if (!pPrisoner)
{
pPrisoner = go->FindNearestCreature(NPC_PRISONER_MAGE, 2.0f);
if (!pPrisoner)
{
pPrisoner = go->FindNearestCreature(NPC_PRISONER_WARRIOR, 2.0f);
if (!pPrisoner)
pPrisoner = go->FindNearestCreature(NPC_PRISONER_PALADIN, 2.0f);
}
}
if (!pPrisoner || !pPrisoner->IsAlive())
return true;
Quest const* qInfo = sObjectMgr->GetQuestTemplate(QUEST_PRISONERS_OF_WYRMSKULL);
if (qInfo)
{
//TODO: prisoner should help player for a short period of time
player->QuestObjectiveSatisfy(QUEST_OBJECTIVE_VALGARDE_PRISONER_RESCUED, 1);
pPrisoner->DisappearAndDie();
}
return true;
}
};
/*######
## Quest 11560: Oh Noes, the Tadpoles!
## go_tadpole_cage
######*/
enum Tadpoles
{
QUEST_OH_NOES_THE_TADPOLES = 11560,
NPC_WINTERFIN_TADPOLE = 25201
};
class go_tadpole_cage : public GameObjectScript
{
public:
go_tadpole_cage() : GameObjectScript("go_tadpole_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (player->GetQuestStatus(QUEST_OH_NOES_THE_TADPOLES) == QUEST_STATUS_INCOMPLETE)
{
Creature* pTadpole = go->FindNearestCreature(NPC_WINTERFIN_TADPOLE, 1.0f);
if (pTadpole)
{
go->UseDoorOrButton();
pTadpole->DisappearAndDie();
player->KilledMonsterCredit(NPC_WINTERFIN_TADPOLE, 0);
//FIX: Summon minion tadpole
}
}
return true;
}
};
/*######
## go_amberpine_outhouse
######*/
#define GOSSIP_USE_OUTHOUSE "Use the outhouse."
#define GO_ANDERHOLS_SLIDER_CIDER_NOT_FOUND "Quest item Anderhol's Slider Cider not found."
enum AmberpineOuthouse
{
ITEM_ANDERHOLS_SLIDER_CIDER = 37247,
NPC_OUTHOUSE_BUNNY = 27326,
QUEST_DOING_YOUR_DUTY = 12227,
SPELL_INDISPOSED = 53017,
SPELL_INDISPOSED_III = 48341,
SPELL_CREATE_AMBERSEEDS = 48330,
GOSSIP_OUTHOUSE_INUSE = 12775,
GOSSIP_OUTHOUSE_VACANT = 12779
};
class go_amberpine_outhouse : public GameObjectScript
{
public:
go_amberpine_outhouse() : GameObjectScript("go_amberpine_outhouse") { }
bool OnGossipHello(Player* player, GameObject* go)
{
QuestStatus status = player->GetQuestStatus(QUEST_DOING_YOUR_DUTY);
if (status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE || status == QUEST_STATUS_REWARDED)
{
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_USE_OUTHOUSE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
player->SEND_GOSSIP_MENU(GOSSIP_OUTHOUSE_VACANT, go->GetGUID());
return true;
}
else
player->SEND_GOSSIP_MENU(GOSSIP_OUTHOUSE_INUSE, go->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, GameObject* go, uint32 /*sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
if (action == GOSSIP_ACTION_INFO_DEF +1)
{
player->CLOSE_GOSSIP_MENU();
Creature* target = GetClosestCreatureWithEntry(player, NPC_OUTHOUSE_BUNNY, 3.0f);
if (target)
{
target->AI()->SetData(1, player->getGender());
go->CastSpell(target, SPELL_INDISPOSED_III);
}
go->CastSpell(player, SPELL_INDISPOSED);
if (player->HasItemCount(ITEM_ANDERHOLS_SLIDER_CIDER, 1))
go->CastSpell(player, SPELL_CREATE_AMBERSEEDS);
return true;
}
else
{
player->CLOSE_GOSSIP_MENU();
player->GetSession()->SendNotification(GO_ANDERHOLS_SLIDER_CIDER_NOT_FOUND);
return false;
}
}
};
/*######
## Quest 1126: Hive in the Tower
## go_hive_pod
######*/
enum Hives
{
QUEST_HIVE_IN_THE_TOWER = 9544,
NPC_HIVE_AMBUSHER = 13301
};
class go_hive_pod : public GameObjectScript
{
public:
go_hive_pod() : GameObjectScript("go_hive_pod") { }
bool OnGossipHello(Player* player, GameObject* go)
{
player->SendLoot(go->GetGUID(), LOOT_CORPSE);
go->SummonCreature(NPC_HIVE_AMBUSHER, go->GetPositionX()+1, go->GetPositionY(), go->GetPositionZ(), go->GetAngle(player), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000);
go->SummonCreature(NPC_HIVE_AMBUSHER, go->GetPositionX(), go->GetPositionY()+1, go->GetPositionZ(), go->GetAngle(player), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 60000);
return true;
}
};
class go_massive_seaforium_charge : public GameObjectScript
{
public:
go_massive_seaforium_charge() : GameObjectScript("go_massive_seaforium_charge") { }
bool OnGossipHello(Player* /*player*/, GameObject* go)
{
go->SetLootState(GO_JUST_DEACTIVATED);
return true;
}
};
/*######
## go_gjalerbron_cage
######*/
enum OfKeysAndCages
{
QUEST_ALLIANCE_OF_KEYS_AND_CAGES = 11231,
QUEST_HORDE_OF_KEYS_AND_CAGES = 11265,
NPC_GJALERBRON_PRISONER = 24035,
SAY_FREE = 0,
};
class go_gjalerbron_cage : public GameObjectScript
{
public:
go_gjalerbron_cage() : GameObjectScript("go_gjalerbron_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if ((player->GetTeamId() == TEAM_ALLIANCE && player->GetQuestStatus(QUEST_ALLIANCE_OF_KEYS_AND_CAGES) == QUEST_STATUS_INCOMPLETE) ||
(player->GetTeamId() == TEAM_HORDE && player->GetQuestStatus(QUEST_HORDE_OF_KEYS_AND_CAGES) == QUEST_STATUS_INCOMPLETE))
{
if (Creature* prisoner = go->FindNearestCreature(NPC_GJALERBRON_PRISONER, 5.0f))
{
go->UseDoorOrButton();
if (player)
player->KilledMonsterCredit(NPC_GJALERBRON_PRISONER, 0);
prisoner->AI()->Talk(SAY_FREE);
prisoner->DespawnOrUnsummon(6000);
}
}
return true;
}
};
/*########
## go_large_gjalerbron_cage
#####*/
class go_large_gjalerbron_cage : public GameObjectScript
{
public:
go_large_gjalerbron_cage() : GameObjectScript("go_large_gjalerbron_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if ((player->GetTeamId() == TEAM_ALLIANCE && player->GetQuestStatus(QUEST_ALLIANCE_OF_KEYS_AND_CAGES) == QUEST_STATUS_INCOMPLETE) ||
(player->GetTeamId() == TEAM_HORDE && player->GetQuestStatus(QUEST_HORDE_OF_KEYS_AND_CAGES) == QUEST_STATUS_INCOMPLETE))
{
std::list<Creature*> prisonerList;
GetCreatureListWithEntryInGrid(prisonerList, go, NPC_GJALERBRON_PRISONER, INTERACTION_DISTANCE);
for (std::list<Creature*>::const_iterator itr = prisonerList.begin(); itr != prisonerList.end(); ++itr)
{
go->UseDoorOrButton();
player->KilledMonsterCredit(NPC_GJALERBRON_PRISONER, (*itr)->GetGUID());
(*itr)->DespawnOrUnsummon(6000);
(*itr)->AI()->Talk(SAY_FREE);
}
}
return false;
}
};
/*########
#### go_veil_skith_cage
#####*/
enum MissingFriends
{
QUEST_MISSING_FRIENDS = 10852,
NPC_CAPTIVE_CHILD = 22314,
SAY_FREE_0 = 0,
};
class go_veil_skith_cage : public GameObjectScript
{
public:
go_veil_skith_cage() : GameObjectScript("go_veil_skith_cage") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (player->GetQuestStatus(QUEST_MISSING_FRIENDS) == QUEST_STATUS_INCOMPLETE)
{
std::list<Creature*> childrenList;
GetCreatureListWithEntryInGrid(childrenList, go, NPC_CAPTIVE_CHILD, INTERACTION_DISTANCE);
for (std::list<Creature*>::const_iterator itr = childrenList.begin(); itr != childrenList.end(); ++itr)
{
go->UseDoorOrButton();
player->KilledMonsterCredit(NPC_CAPTIVE_CHILD, (*itr)->GetGUID());
(*itr)->DespawnOrUnsummon(5000);
(*itr)->GetMotionMaster()->MovePoint(1, go->GetPositionX()+5, go->GetPositionY(), go->GetPositionZ());
(*itr)->AI()->Talk(SAY_FREE_0);
(*itr)->GetMotionMaster()->Clear();
}
}
return false;
}
};
/*######
## go_frostblade_shrine
######*/
enum TheCleansing
{
QUEST_THE_CLEANSING_HORDE = 11317,
QUEST_THE_CLEANSING_ALLIANCE = 11322,
SPELL_CLEANSING_SOUL = 43351,
SPELL_RECENT_MEDITATION = 61720,
};
class go_frostblade_shrine : public GameObjectScript
{
public:
go_frostblade_shrine() : GameObjectScript("go_frostblade_shrine") { }
bool OnGossipHello(Player* player, GameObject* go)
{
if (!player->HasAura(SPELL_RECENT_MEDITATION))
if (player->GetQuestStatus(QUEST_THE_CLEANSING_HORDE) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(QUEST_THE_CLEANSING_ALLIANCE) == QUEST_STATUS_INCOMPLETE)
{
go->UseDoorOrButton(10);
player->CastSpell(player, SPELL_CLEANSING_SOUL);
player->SetStandState(UNIT_STAND_STATE_SIT);
}
return true;
}
};
/*######
## go_midsummer_bonfire
######*/
enum MidsummerBonfire
{
STAMP_OUT_BONFIRE_QUEST_COMPLETE = 45458,
};
class go_midsummer_bonfire : public GameObjectScript
{
public:
go_midsummer_bonfire() : GameObjectScript("go_midsummer_bonfire") { }
bool OnGossipSelect(Player* player, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/)
{
player->CastSpell(player, STAMP_OUT_BONFIRE_QUEST_COMPLETE, true);
player->CLOSE_GOSSIP_MENU();
return false;
}
};
class go_seaforium_charge : public GameObjectScript
{
public:
go_seaforium_charge() : GameObjectScript("go_seaforium_charge") { }
bool OnGossipHello(Player* player, GameObject* /*go*/)
{
return player->HasAura(52418);
}
};
void AddSC_go_scripts()
{
new go_cat_figurine;
new go_northern_crystal_pylon;
new go_eastern_crystal_pylon;
new go_western_crystal_pylon;
new go_barov_journal;
new go_field_repair_bot_74A;
new go_gilded_brazier;
new go_orb_of_command;
new go_shrine_of_the_birds;
new go_southfury_moonstone;
new go_tablet_of_madness;
new go_tablet_of_the_seven;
new go_jump_a_tron;
new go_ethereum_prison;
new go_ethereum_stasis;
new go_resonite_cask;
new go_sacred_fire_of_life;
new go_tele_to_dalaran_crystal;
new go_tele_to_violet_stand;
new go_fel_crystalforge;
new go_bashir_crystalforge;
new go_matrix_punchograph;
new go_scourge_cage;
new go_arcane_prison;
new go_blood_filled_orb;
new go_jotunheim_cage;
new go_table_theka;
new go_inconspicuous_landmark;
new go_ethereal_teleport_pad;
new go_soulwell;
new go_tadpole_cage;
new go_dragonflayer_cage;
new go_amberpine_outhouse;
new go_hive_pod;
new go_massive_seaforium_charge;
new go_gjalerbron_cage;
new go_large_gjalerbron_cage;
new go_veil_skith_cage;
new go_frostblade_shrine;
new go_midsummer_bonfire;
new go_seaforium_charge;
}
| [
"felianther15@gmail.com"
] | felianther15@gmail.com |
ec8b23259abc1757931f2f3108334b374759b23a | bf016c39ed9806b9de610f8ecbb48eb9ceffd9e4 | /第四周周赛/求n以内最大的k个素数以及它们的和.cpp | 3e8306452192ab6dc6ad6cf353b53917f5853e2f | [] | no_license | lwddddd/ACM | 4e38d01185993bb860e8a6287ef856b3b45c7673 | 20da28b40888acf945c1b5b9f020c81fe68c442d | refs/heads/master | 2021-01-12T11:43:38.167893 | 2017-03-18T06:06:12 | 2017-03-18T06:06:12 | 72,280,056 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | #include<iostream>
#include<cmath>
using namespace std;
bool sushu(int n)
{
if(n==0||n==1)
return false;
bool a=true;
int k=sqrt(n);
for(int i=2;i<=k;i++)
{
if(n%i==0)
{
a=false;
break;
}
}
return a;
}
int main()
{
int n,k;
int answer[15]={0},a=0;
cin>>n>>k;
while(n--)
{
if(sushu(n))
{
answer[a]=n;
a++;
}
if(a==k)
break;
}
int sum=0;
for(int i=0;i<a;i++)
{
cout<<answer[i];
sum=sum+answer[i];
if(i!=a-1)
cout<<'+';
}
cout<<"="<<sum<<endl;
}
| [
"619145584@qq.com"
] | 619145584@qq.com |
c9dc49c01fa2afb22b121b971d49ab4d17b50a02 | 0946c2ab245537a5ae62ee879e45f9ef1922c33c | /mainwindow/menu/uimenu_p_connectActions.cpp | b3aeec0f256d2ec1f68bbc7acd9a436b4c632209 | [] | no_license | maxkofler/Z80Emulator | 1f761dfca6ba72d4fce9ff016b720b410aff85a2 | a48b8a6f40a54f83481ce7bc117160c3485a1bc2 | refs/heads/main | 2023-07-14T22:59:46.226839 | 2021-08-31T17:25:05 | 2021-08-31T17:25:05 | 372,790,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | cpp | #include "uimenu.h"
void UIMenu::p_connectActions(){
FUN();
//File
connect(this->_a_file_openSource, &QAction::triggered, this, &UIMenu::sl_file_openSource_p);
connect(this->_a_file_saveSource, &QAction::triggered, this, &UIMenu::sl_file_saveSource_p);
connect(this->_a_file_openHex, &QAction::triggered, this, &UIMenu::sl_file_openHex_p);
}
| [
"kofler.max.dev@gmail.com"
] | kofler.max.dev@gmail.com |
7a463a9e251455a94c746273cfd4f2e8fa8e45e6 | a077d0841bb7206650802eeea3e7a3f00a13b2f9 | /src/util.cpp | 7c09a4c4dedbf1ffc2fa1af802d42490f5c64829 | [
"MIT"
] | permissive | facecoin/facecoin | f49834f05c9214d8e5a65eb57ff00d2434db09a8 | 772f06355ddf148c79c949d9896dc2055acf5dda | refs/heads/master | 2021-04-24T18:04:54.750819 | 2016-07-20T18:25:20 | 2016-07-20T18:25:20 | 63,804,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,945 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
static FILE* fileout = NULL;
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "facecoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\FaceCoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\FaceCoin
// Mac: ~/Library/Application Support/FaceCoin
// Unix: ~/.facecoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "FaceCoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "FaceCoin";
#else
// Unix
return pathRet / ".facecoin";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && GetBoolArg("-testnet", false))
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "facecoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "facecoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong FaceCoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("FaceCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
uint32_t insecure_rand_Rz = 11;
uint32_t insecure_rand_Rw = 11;
void seed_insecure_rand(bool fDeterministic)
{
//The seed values have some unlikely fixed points which we avoid.
if(fDeterministic)
{
insecure_rand_Rz = insecure_rand_Rw = 11;
} else {
uint32_t tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x9068ffffU);
insecure_rand_Rz=tmp;
do{
RAND_bytes((unsigned char*)&tmp,4);
}while(tmp==0 || tmp==0x464fffffU);
insecure_rand_Rw=tmp;
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
| [
"facecoin@scryptmail.com"
] | facecoin@scryptmail.com |
6008723ab378587480c2eb8f67419d5ec080da61 | 0ffdf8ab6c5a875bfd8c3e06456131a0f3abad62 | /src/masternode-budget.h | 6e3ce6404a360174b424163c90bd69ee84e1f2a7 | [
"MIT"
] | permissive | FYNCOIN-Foundation/FYNCOIN | d06be9163090155a540b369512b9f6ec7f2410f3 | 835ce3be2fb20632fb9443293d86caad620a1f7e | refs/heads/master | 2020-03-26T11:55:35.065862 | 2018-09-02T10:26:22 | 2018-09-02T10:26:22 | 144,866,105 | 0 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 18,721 | h | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODE_BUDGET_H
#define MASTERNODE_BUDGET_H
#include "base58.h"
#include "init.h"
#include "key.h"
#include "main.h"
#include "masternode.h"
#include "net.h"
#include "sync.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
using namespace std;
extern CCriticalSection cs_budget;
class CBudgetManager;
class CFinalizedBudgetBroadcast;
class CFinalizedBudget;
class CBudgetProposal;
class CBudgetProposalBroadcast;
class CTxBudgetPayment;
#define VOTE_ABSTAIN 0
#define VOTE_YES 1
#define VOTE_NO 2
enum class TrxValidationStatus {
Invalid, /** Transaction verification failed */
Valid, /** Transaction successfully verified */
DoublePayment, /** Transaction successfully verified, but includes a double-budget-payment */
VoteThreshold /** If not enough masternodes have voted on a finalized budget */
};
static const int64_t BUDGET_VOTE_UPDATE_MIN = 60 * 60;
extern std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals;
extern std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets;
static map<uint256, int> mapPayment_History;
extern CBudgetManager budget;
void DumpBudgets();
// Define amount of blocks in budget payment cycle
int GetBudgetPaymentCycleBlocks();
//Check the collateral transaction for the budget proposal/finalized budget
bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf, bool fBudgetFinalization = false);
// Get the budget collateral amount for a block height
CAmount GetBudgetSystemCollateralAmount(int nHeight);
//
// CBudgetVote - Allow a masternode node to vote and broadcast throughout the network
//
class CBudgetVote
{
public:
bool fValid; //if the vote is currently valid / counted
bool fSynced; //if we've sent this to our peers
CTxIn vin;
uint256 nProposalHash;
int nVote;
int64_t nTime;
std::vector<unsigned char> vchSig;
CBudgetVote();
CBudgetVote(CTxIn vin, uint256 nProposalHash, int nVoteIn);
bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode);
bool SignatureValid(bool fSignatureCheck);
void Relay();
std::string GetVoteString()
{
std::string ret = "ABSTAIN";
if (nVote == VOTE_YES) ret = "YES";
if (nVote == VOTE_NO) ret = "NO";
return ret;
}
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << nProposalHash;
ss << nVote;
ss << nTime;
return ss.GetHash();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vin);
READWRITE(nProposalHash);
READWRITE(nVote);
READWRITE(nTime);
READWRITE(vchSig);
}
};
//
// CFinalizedBudgetVote - Allow a masternode node to vote and broadcast throughout the network
//
class CFinalizedBudgetVote
{
public:
bool fValid; //if the vote is currently valid / counted
bool fSynced; //if we've sent this to our peers
CTxIn vin;
uint256 nBudgetHash;
int64_t nTime;
std::vector<unsigned char> vchSig;
CFinalizedBudgetVote();
CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn);
bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode);
bool SignatureValid(bool fSignatureCheck);
void Relay();
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << nBudgetHash;
ss << nTime;
return ss.GetHash();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vin);
READWRITE(nBudgetHash);
READWRITE(nTime);
READWRITE(vchSig);
}
};
/** Save Budget Manager (budget.dat)
*/
class CBudgetDB
{
private:
boost::filesystem::path pathDB;
std::string strMagicMessage;
public:
enum ReadResult {
Ok,
FileError,
HashReadError,
IncorrectHash,
IncorrectMagicMessage,
IncorrectMagicNumber,
IncorrectFormat
};
CBudgetDB();
bool Write(const CBudgetManager& objToSave);
ReadResult Read(CBudgetManager& objToLoad, bool fDryRun = false);
};
//
// Budget Manager : Contains all proposals for the budget
//
class CBudgetManager
{
private:
//hold txes until they mature enough to use
// XX42 map<uint256, CTransaction> mapCollateral;
map<uint256, uint256> mapCollateralTxids;
public:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
// keep track of the scanning errors I've seen
map<uint256, CBudgetProposal> mapProposals;
map<uint256, CFinalizedBudget> mapFinalizedBudgets;
std::map<uint256, CBudgetProposalBroadcast> mapSeenMasternodeBudgetProposals;
std::map<uint256, CBudgetVote> mapSeenMasternodeBudgetVotes;
std::map<uint256, CBudgetVote> mapOrphanMasternodeBudgetVotes;
std::map<uint256, CFinalizedBudgetBroadcast> mapSeenFinalizedBudgets;
std::map<uint256, CFinalizedBudgetVote> mapSeenFinalizedBudgetVotes;
std::map<uint256, CFinalizedBudgetVote> mapOrphanFinalizedBudgetVotes;
CBudgetManager()
{
mapProposals.clear();
mapFinalizedBudgets.clear();
}
void ClearSeen()
{
mapSeenMasternodeBudgetProposals.clear();
mapSeenMasternodeBudgetVotes.clear();
mapSeenFinalizedBudgets.clear();
mapSeenFinalizedBudgetVotes.clear();
}
int sizeFinalized() { return (int)mapFinalizedBudgets.size(); }
int sizeProposals() { return (int)mapProposals.size(); }
void ResetSync();
void MarkSynced();
void Sync(CNode* node, uint256 nProp, bool fPartial = false);
void Calculate();
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
void NewBlock();
CBudgetProposal* FindProposal(const std::string& strProposalName);
CBudgetProposal* FindProposal(uint256 nHash);
CFinalizedBudget* FindFinalizedBudget(uint256 nHash);
std::pair<std::string, std::string> GetVotes(std::string strProposalName);
CAmount GetTotalBudget(int nHeight);
std::vector<CBudgetProposal*> GetBudget();
std::vector<CBudgetProposal*> GetAllProposals();
std::vector<CFinalizedBudget*> GetFinalizedBudgets();
bool IsBudgetPaymentBlock(int nBlockHeight);
bool AddProposal(CBudgetProposal& budgetProposal);
bool AddFinalizedBudget(CFinalizedBudget& finalizedBudget);
void SubmitFinalBudget();
bool UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError);
bool UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError);
bool PropExists(uint256 nHash);
TrxValidationStatus IsTransactionValid(const CTransaction& txNew, int nBlockHeight);
bool IsPaidAlready(uint256 nProposalHash, int nBlockHeight);
std::string GetRequiredPaymentsString(int nBlockHeight);
void FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake);
void CheckOrphanVotes();
void Clear()
{
LOCK(cs);
LogPrintf("Budget object cleared\n");
mapProposals.clear();
mapFinalizedBudgets.clear();
mapSeenMasternodeBudgetProposals.clear();
mapSeenMasternodeBudgetVotes.clear();
mapSeenFinalizedBudgets.clear();
mapSeenFinalizedBudgetVotes.clear();
mapOrphanMasternodeBudgetVotes.clear();
mapOrphanFinalizedBudgetVotes.clear();
}
void CheckAndRemove();
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(mapSeenMasternodeBudgetProposals);
READWRITE(mapSeenMasternodeBudgetVotes);
READWRITE(mapSeenFinalizedBudgets);
READWRITE(mapSeenFinalizedBudgetVotes);
READWRITE(mapOrphanMasternodeBudgetVotes);
READWRITE(mapOrphanFinalizedBudgetVotes);
READWRITE(mapProposals);
READWRITE(mapFinalizedBudgets);
}
};
class CTxBudgetPayment
{
public:
uint256 nProposalHash;
CScript payee;
CAmount nAmount;
CTxBudgetPayment()
{
payee = CScript();
nAmount = 0;
nProposalHash = 0;
}
ADD_SERIALIZE_METHODS;
//for saving to the serialized db
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(payee);
READWRITE(nAmount);
READWRITE(nProposalHash);
}
};
//
// Finalized Budget : Contains the suggested proposals to pay on a given block
//
class CFinalizedBudget
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
bool fAutoChecked; //If it matches what we see, we'll auto vote for it (masternode only)
public:
bool fValid;
std::string strBudgetName;
int nBlockStart;
std::vector<CTxBudgetPayment> vecBudgetPayments;
map<uint256, CFinalizedBudgetVote> mapVotes;
uint256 nFeeTXHash;
int64_t nTime;
CFinalizedBudget();
CFinalizedBudget(const CFinalizedBudget& other);
void CleanAndRemove(bool fSignatureCheck);
bool AddOrUpdateVote(CFinalizedBudgetVote& vote, std::string& strError);
double GetScore();
bool HasMinimumRequiredSupport();
bool IsValid(std::string& strError, bool fCheckCollateral = true);
std::string GetName() { return strBudgetName; }
std::string GetProposals();
int GetBlockStart() { return nBlockStart; }
int GetBlockEnd() { return nBlockStart + (int)(vecBudgetPayments.size() - 1); }
int GetVoteCount() { return (int)mapVotes.size(); }
bool IsPaidAlready(uint256 nProposalHash, int nBlockHeight);
TrxValidationStatus IsTransactionValid(const CTransaction& txNew, int nBlockHeight);
bool GetBudgetPaymentByBlock(int64_t nBlockHeight, CTxBudgetPayment& payment)
{
LOCK(cs);
int i = nBlockHeight - GetBlockStart();
if (i < 0) return false;
if (i > (int)vecBudgetPayments.size() - 1) return false;
payment = vecBudgetPayments[i];
return true;
}
bool GetPayeeAndAmount(int64_t nBlockHeight, CScript& payee, CAmount& nAmount)
{
LOCK(cs);
int i = nBlockHeight - GetBlockStart();
if (i < 0) return false;
if (i > (int)vecBudgetPayments.size() - 1) return false;
payee = vecBudgetPayments[i].payee;
nAmount = vecBudgetPayments[i].nAmount;
return true;
}
//check to see if we should vote on this
void AutoCheck();
//total fyn paid out by this budget
CAmount GetTotalPayout();
//vote on this finalized budget as a masternode
void SubmitVote();
//checks the hashes to make sure we know about them
string GetStatus();
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << strBudgetName;
ss << nBlockStart;
ss << vecBudgetPayments;
uint256 h1 = ss.GetHash();
return h1;
}
ADD_SERIALIZE_METHODS;
//for saving to the serialized db
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(LIMITED_STRING(strBudgetName, 20));
READWRITE(nFeeTXHash);
READWRITE(nTime);
READWRITE(nBlockStart);
READWRITE(vecBudgetPayments);
READWRITE(fAutoChecked);
READWRITE(mapVotes);
}
};
// FinalizedBudget are cast then sent to peers with this object, which leaves the votes out
class CFinalizedBudgetBroadcast : public CFinalizedBudget
{
private:
std::vector<unsigned char> vchSig;
public:
CFinalizedBudgetBroadcast();
CFinalizedBudgetBroadcast(const CFinalizedBudget& other);
CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn);
void swap(CFinalizedBudgetBroadcast& first, CFinalizedBudgetBroadcast& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.strBudgetName, second.strBudgetName);
swap(first.nBlockStart, second.nBlockStart);
first.mapVotes.swap(second.mapVotes);
first.vecBudgetPayments.swap(second.vecBudgetPayments);
swap(first.nFeeTXHash, second.nFeeTXHash);
swap(first.nTime, second.nTime);
}
CFinalizedBudgetBroadcast& operator=(CFinalizedBudgetBroadcast from)
{
swap(*this, from);
return *this;
}
void Relay();
ADD_SERIALIZE_METHODS;
//for propagating messages
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
//for syncing with other clients
READWRITE(LIMITED_STRING(strBudgetName, 20));
READWRITE(nBlockStart);
READWRITE(vecBudgetPayments);
READWRITE(nFeeTXHash);
}
};
//
// Budget Proposal : Contains the masternode votes for each budget
//
class CBudgetProposal
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
CAmount nAlloted;
public:
bool fValid;
std::string strProposalName;
/*
json object with name, short-description, long-description, pdf-url and any other info
This allows the proposal website to stay 100% decentralized
*/
std::string strURL;
int nBlockStart;
int nBlockEnd;
CAmount nAmount;
CScript address;
int64_t nTime;
uint256 nFeeTXHash;
map<uint256, CBudgetVote> mapVotes;
//cache object
CBudgetProposal();
CBudgetProposal(const CBudgetProposal& other);
CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn);
void Calculate();
bool AddOrUpdateVote(CBudgetVote& vote, std::string& strError);
bool HasMinimumRequiredSupport();
std::pair<std::string, std::string> GetVotes();
bool IsValid(std::string& strError, bool fCheckCollateral = true);
bool IsEstablished()
{
// Proposals must be at least a day old to make it into a budget
if (Params().NetworkID() == CBaseChainParams::MAIN) return (nTime < GetTime() - (60 * 60 * 24));
// For testing purposes - 5 minutes
return (nTime < GetTime() - (60 * 5));
}
std::string GetName() { return strProposalName; }
std::string GetURL() { return strURL; }
int GetBlockStart() { return nBlockStart; }
int GetBlockEnd() { return nBlockEnd; }
CScript GetPayee() { return address; }
int GetTotalPaymentCount();
int GetRemainingPaymentCount();
int GetBlockStartCycle();
int GetBlockCurrentCycle();
int GetBlockEndCycle();
double GetRatio();
int GetYeas();
int GetNays();
int GetAbstains();
CAmount GetAmount() { return nAmount; }
void SetAllotted(CAmount nAllotedIn) { nAlloted = nAllotedIn; }
CAmount GetAllotted() { return nAlloted; }
void CleanAndRemove(bool fSignatureCheck);
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << strProposalName;
ss << strURL;
ss << nBlockStart;
ss << nBlockEnd;
ss << nAmount;
ss << address;
uint256 h1 = ss.GetHash();
return h1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
//for syncing with other clients
READWRITE(LIMITED_STRING(strProposalName, 20));
READWRITE(LIMITED_STRING(strURL, 64));
READWRITE(nTime);
READWRITE(nBlockStart);
READWRITE(nBlockEnd);
READWRITE(nAmount);
READWRITE(address);
READWRITE(nTime);
READWRITE(nFeeTXHash);
//for saving to the serialized db
READWRITE(mapVotes);
}
};
// Proposals are cast then sent to peers with this object, which leaves the votes out
class CBudgetProposalBroadcast : public CBudgetProposal
{
public:
CBudgetProposalBroadcast() : CBudgetProposal() {}
CBudgetProposalBroadcast(const CBudgetProposal& other) : CBudgetProposal(other) {}
CBudgetProposalBroadcast(const CBudgetProposalBroadcast& other) : CBudgetProposal(other) {}
CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn);
void swap(CBudgetProposalBroadcast& first, CBudgetProposalBroadcast& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.strProposalName, second.strProposalName);
swap(first.nBlockStart, second.nBlockStart);
swap(first.strURL, second.strURL);
swap(first.nBlockEnd, second.nBlockEnd);
swap(first.nAmount, second.nAmount);
swap(first.address, second.address);
swap(first.nTime, second.nTime);
swap(first.nFeeTXHash, second.nFeeTXHash);
first.mapVotes.swap(second.mapVotes);
}
CBudgetProposalBroadcast& operator=(CBudgetProposalBroadcast from)
{
swap(*this, from);
return *this;
}
void Relay();
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
//for syncing with other clients
READWRITE(LIMITED_STRING(strProposalName, 20));
READWRITE(LIMITED_STRING(strURL, 64));
READWRITE(nTime);
READWRITE(nBlockStart);
READWRITE(nBlockEnd);
READWRITE(nAmount);
READWRITE(address);
READWRITE(nFeeTXHash);
}
};
#endif
| [
"hemant.singh.leu@gmail.com"
] | hemant.singh.leu@gmail.com |
577ad49bfcdbdd79300037e22ee732d4279aeabb | 20e7990890414b27083c10b46b8dbdd91de87094 | /OtherCFiles/PARABOLA.CPP | 34cfe1b7f1ac82a6d01fbeaaa051ba6e25ab6660 | [] | no_license | agudeloandres/C_Struct_Files | eb3aa9a62c596939a79f1e13c2f5cc04543592ec | cafe017f5dad4cec5d1ea2fabf4d6c646c99a23b | refs/heads/master | 2021-01-10T14:04:32.468058 | 2015-10-22T04:12:02 | 2015-10-22T04:12:02 | 44,718,124 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,573 | cpp |
/* parabola.c - alturas para una antena parabólica
**
** Autor: Pablo A. Straub
** Fecha: Miércoles 28 de agosto de 1996
** Miércoles 12 de marzo de 1997, no se usa leer.c
*/
#include<stdio.h>
void main ()
{
/* datos de entrada */
float diametro;
float ymax;
int intervalos;
/* datos de cómputo inicial */
float foco, a, radio, delta;
/* variables de la iteración */
int intervalo;
float x, y;
/* Se piden los parámetros */
printf("Cómputo de una Antena Parabólica\n\n");
printf("Ingrese el diámetro de la antena en [mm]: ");
scanf("%f", &diametro);
printf("Ingrese la altura de la parábola para el"
" radio máximo [mm]: ");
scanf("%f", &ymax);
printf("Ingrese el número de intervalos: ");
scanf("%d", &intervalos);
/* Cómputo inicial */
radio = diametro / 2.0;
a = ymax / (radio * radio);
foco = 1 / (4 * a);
delta = radio / intervalos;
/* Resultados iniciales */
printf("\nEl radio es %6.1f [mm]\n", radio);
printf("El parámetro a es %12.9f [1/mm]\n", a);
printf("El foco está a %6.1f [mm]\n", foco);
/* Tabla de altura de parabola en función del radio */
printf("\nAltura en Función del Radio\n\n");
printf(" Intervalo Radio (mm) Altura (mm)\n");
printf("--------------------------------------\n");
for (intervalo = 0; intervalo <= intervalos; intervalo++) {
x = delta * intervalo;
y = a * x * x;
printf("%7d %13.1f %12.1f\n", intervalo, x, y);
}
}
| [
"agudeloandres@gmail.com"
] | agudeloandres@gmail.com |
4d2d8cd85f9d3d6d57c91c8e8ec402d64a6a0704 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s03/CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84_bad.cpp | d1ee1cebec9d22ef9485b8ff42958626357f608c | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 4,174 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84_bad.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-84_bad.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Full path and file name
* Sinks: ifstream
* BadSink : Open the file named in data using ifstream::open()
* Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84.h"
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#include <fstream>
using namespace std;
namespace CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84
{
CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84_bad::CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84_bad(wchar_t * dataCopy)
{
data = dataCopy;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84_bad::~CWE36_Absolute_Path_Traversal__wchar_t_connect_socket_ifstream_84_bad()
{
{
ifstream inputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
inputFile.open((char *)data);
inputFile.close();
}
}
}
#endif /* OMITBAD */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
cbaed03fb1eee3bf0e635e769aaaeb963c7db7a7 | 75cea607e58ad227eb1b72b7b5e0393e255536d4 | /schmitttrigger.cpp | 3aeb7b6ed4605f28fffd2c3ea2b06e342af91084 | [] | no_license | Lambosaurus/bot | 62585b38047bd533c41398ea6caa9cb5d4cb2859 | 47c8b4b2afcb6f499f439609f56d7a3da4fbc615 | refs/heads/master | 2021-01-10T16:51:03.947640 | 2016-01-17T20:01:28 | 2016-01-17T20:01:28 | 48,638,321 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | cpp | #include "schmitttrigger.h"
SchmittTrigger::SchmittTrigger()
{
}
void SchmittTrigger::Init(float low, float high)
{
v_high = high;
v_low = low;
}
void SchmittTrigger::Update(float value)
{
high = value > (high ? v_low : v_high);
} | [
"tlamborn@gmail.com"
] | tlamborn@gmail.com |
06e0ea6f1a6ea5a6b0dfe548c1b35d1a40ad9686 | 1979eeabcd279b2a688b75fb9106b3fe0c2fb6ea | /time.cpp | 78bd67aeb91c506ed6ad0d89fe21ae93a51eb224 | [] | no_license | ibmlih/calendar | 356cbfbf1723ef38bf5037062abd080462051d1b | 45e144a4cb80278a1ea87279667eeead78333d4d | refs/heads/master | 2020-03-25T22:54:38.925764 | 2018-08-10T08:04:54 | 2018-08-10T08:04:54 | 144,249,588 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,279 | cpp | #include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include "time.h"
using namespace std;
void Time::getTime()
{
char colon;
cin >> hour >> colon >> minute;
while (hour < 0 || hour > 23 || minute < 0 || minute > 59)
{
cout << "Please try again (hh:mm) >> ";
cin >> hour >> colon >> minute;
if(hour < 0 || hour > 23)
cout << "Hour must be between 0 and 23.\n";
if(minute < 0 || minute > 59)
cout << "Minute must be between 0 and 59.\n";
} // while time is wrong
} // getTime()
bool Time::operator< (const Time &time2) const
{
return hour < time2.hour
|| (hour == time2.hour && minute < time2.minute);
} // operator<
ostream& operator<< (ostream &os, const Time &time)
{
os << setw(2) << setfill('0') << time.hour << ":" << setw(2) << time.minute
<< ' ' << setfill(' ');
return os;
} // operator<< ()
istream& operator>> (istream &is, Time &time)
{
char line[80];
is.getline(line, 80, ':');
time.hour = atoi(line);
is.getline(line, 80, ':');
time.minute = atoi(line);
is.getline(line, 80, ',');
if(time.hour == 12 && strchr(line, 'A'))
time.hour = 0;
if(strchr(line, 'P') && time.hour < 12)
time.hour += 12;
return is;
} // operator>>
| [
"petlee@ucdavis.edu"
] | petlee@ucdavis.edu |
9cff5aa9bf4f76556e1ff7a05ea37012e72a38ac | 079dfdb404cf20fad500790492deca2b0edf2fee | /Jedi-VS-Sith_CommandLineVersion/Arena.h | 416d64f5f96c3149593e00f6d0cfa3391eb5ba23 | [] | no_license | JasonG007/Jedi-VS-Sith | 05cabbadd060ee6849095cf59429ac839cab220f | bf1ca8cd90f146de9f7cd5a0993ebc4592948b1d | refs/heads/master | 2022-04-21T20:57:50.666420 | 2020-04-04T01:57:20 | 2020-04-04T01:57:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | h | #ifndef ARENA_H_INCLUDED
#include "Characters.h"
#include <iostream>
#include "MainCharacter.h"
class Arena
{
public:
Arena(int dimX,int dimY, int dimZ);
~Arena();
int getNumJedi();
void setNumJedi(int num);
int getNumSith();
void setNumSith(int num);
void printArena();
int dimX;
int dimY;
int dimZ;
int randomX, randomY, randomZ;
int randomCharacterType; // Random roll for either a jedi or sith character type
int numJedi;
int numSith;
int numMonsters;
Characters ****gameWorld; //Array of characters
//test functions from assignment 3
void create3DArray();
void fill3DArray();
void callTick();
void deletePointers();
void fill3DArrayRandomly(int numJedi, int numSith, int numMonsters,int numObstacles);
void moveUp(int a,int b,int c);
void moveDown(int a,int b,int c);
void moveLeft(int a,int b,int c);
void moveRight(int a,int b,int c);
void moveRandomly(int a, int b, int c, int randomDirection);
bool doDamage(int a, int b, int c);
private:
int Size;
int numObstacals;
int random;
int numLandMines;
protected:
void generateObsticals();
void spawnDebris();
void initialize();
void initCharacters();
void addObsticals(int numObs);
void addSith(int numSith);
void addJedi(int numJedi);
void displayBorder();
void displayCharacters();
void displayStats();
void run();
};
#endif // ARENA_H_INCLUDED
| [
"shayanimran99@gmail.com"
] | shayanimran99@gmail.com |
4769282039b7e5a03cd6de0ffc643964a7d041a7 | a664d3114183d35c7375a7466f93408573bf37a6 | /AdaEngine/data/head/TextureSource.h | 6cf53dbb6a006b1eb359921b8fb54f67e25fa96b | [
"MIT"
] | permissive | CookieYang/AdaEngine | 6dbfde834e2495b372446053116d0829a37f5867 | e027a44113f58bd145880b42e1910487ebd5317f | refs/heads/master | 2020-05-15T21:53:39.561618 | 2019-06-14T12:03:39 | 2019-06-14T12:03:39 | 182,510,930 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | h | #pragma once
#include "GPUResource.h"
#include "TextureData.h"
class TextureSource : public GPUResource {
RefCountedPtr<TextureData> imageRef;
public:
bool loaded;
unsigned int textureID;
void setImageRef(const std::string& name);
int getWidth();
int getHeight();
unsigned char* getRawData();
TextureSource();
TextureSource(const std::string& jsonPath);
~TextureSource();
}; | [
"1359870821@qq.com"
] | 1359870821@qq.com |
3e6c101c62459f315d57485e4af201af4513ac48 | a92b18defb50c5d1118a11bc364f17b148312028 | /src/prod/src/ServiceModel/DeployedApplicationHealthStatesFilter.h | cd85150950d16e5299321d798eeefc6723f0c2f4 | [
"MIT"
] | permissive | KDSBest/service-fabric | 34694e150fde662286e25f048fb763c97606382e | fe61c45b15a30fb089ad891c68c893b3a976e404 | refs/heads/master | 2023-01-28T23:19:25.040275 | 2020-11-30T11:11:58 | 2020-11-30T11:11:58 | 301,365,601 | 1 | 0 | MIT | 2020-11-30T11:11:59 | 2020-10-05T10:05:53 | null | UTF-8 | C++ | false | false | 1,795 | h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace ServiceModel
{
class DeployedApplicationHealthStatesFilter
: public Serialization::FabricSerializable
, public Common::IFabricJsonSerializable
{
DENY_COPY(DeployedApplicationHealthStatesFilter)
public:
DeployedApplicationHealthStatesFilter();
explicit DeployedApplicationHealthStatesFilter(DWORD healthStateFilter);
DeployedApplicationHealthStatesFilter(DeployedApplicationHealthStatesFilter && other) = default;
DeployedApplicationHealthStatesFilter & operator = (DeployedApplicationHealthStatesFilter && other) = default;
~DeployedApplicationHealthStatesFilter();
__declspec(property(get=get_HealthStateFilter)) DWORD HealthStateFilter;
DWORD get_HealthStateFilter() const { return healthStateFilter_; }
bool IsRespected(FABRIC_HEALTH_STATE healthState) const;
Common::ErrorCode FromPublicApi(FABRIC_DEPLOYED_APPLICATION_HEALTH_STATES_FILTER const & publicDeployedApplicationHealthStatesFilter);
std::wstring ToString() const;
static Common::ErrorCode FromString(
std::wstring const & str,
__out DeployedApplicationHealthStatesFilter & filter);
FABRIC_FIELDS_01(healthStateFilter_);
BEGIN_JSON_SERIALIZABLE_PROPERTIES()
SERIALIZABLE_PROPERTY(Constants::HealthStateFilter, healthStateFilter_)
END_JSON_SERIALIZABLE_PROPERTIES()
private:
DWORD healthStateFilter_;
};
}
| [
"noreply-sfteam@microsoft.com"
] | noreply-sfteam@microsoft.com |
135663f6c7f4de0566903d145ffa3ecc5227255a | ed7c71b72c44e89e3a905c9b521996fa8a0756a1 | /Programming_Principles_and_Practice_Using_Cpp/tydzien_7/zad02/zad02.cpp | 7d21986056dd01d0c7732034de7244929f005603 | [] | no_license | KamilPetk/kod | ecf084b2f8aed4a0c2b5c9e9997c80d495cd9bcf | a303eb8f088c67ece2978e2cdc9cf7ece1d6159a | refs/heads/main | 2023-01-30T05:10:56.908837 | 2020-12-14T19:13:09 | 2020-12-14T19:13:09 | 321,426,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,552 | cpp | //
// This is example code from Chapter 12.3 "A first example" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#include "Simple_window.hpp" // get access to our window library
#include "Graph.hpp" // get access to our graphics library facilities
using namespace Graph_lib; // our graphics facilities are in Graph_lib
//------------------------------------------------------------------------------
struct My_window : Graph_lib::Window {
My_window(Point xy, int w, int h, const string& title);
void wait_for_button(); // simple event loop
private:
Open_polyline lines;
Button quit_button;
bool button_pushed;
bool button_quit_pushed;
Out_box xy_out;
Button button1;
bool button1_pushed;
static void cb_1(Address, Address);
void b1();
Button button2;
bool button2_pushed;
static void cb_2(Address, Address);
void b2();
Button button3;
bool button3_pushed;
static void cb_3(Address, Address);
void b3();
Button button4;
bool button4_pushed;
static void cb_4(Address, Address);
void b4();
Button button5;
bool button5_pushed;
static void cb_5(Address, Address);
void b5();
Button button6;
bool button6_pushed;
static void cb_6(Address, Address);
void b6();
Button button7;
bool button7_pushed;
static void cb_7(Address, Address);
void b7();
Button button8;
bool button8_pushed;
static void cb_8(Address, Address);
void b8();
Button button9;
bool button9_pushed;
static void cb_9(Address, Address);
void b9();
Button button10;
bool button10_pushed;
static void cb_10(Address, Address);
void b10();
Button button11;
bool button11_pushed;
static void cb_11(Address, Address);
void b11();
Button button12;
bool button12_pushed;
static void cb_12(Address, Address);
void b12();
Button button13;
bool button13_pushed;
static void cb_13(Address, Address);
void b13();
Button button14;
bool button14_pushed;
static void cb_14(Address, Address);
void b14();
Button button15;
bool button15_pushed;
static void cb_15(Address, Address);
void b15();
Button button16;
bool button16_pushed;
static void cb_16(Address, Address);
void b16();
static void cb_next(Address, Address);
static void cb_quit(Address, Address);
void next(int x, int y);
void quit();
};
My_window::My_window(Point xy, int w, int h, const string& title)
:Window{xy,w,h,title},
button_quit_pushed(false),
quit_button(Point(x_max() - 70, 0), 70, 20, "Quit", cb_quit),
xy_out{Point{100,0}, 100, 20, "coordinates (x,y):"},
button1_pushed(false),
button1(Point(x_max() - 800, 20), 200, 150, "1", cb_1),
button2_pushed(false),
button2(Point(x_max() - 600, 20), 200, 150, "2", cb_2),
button3_pushed(false),
button3(Point(x_max() - 400, 20), 200, 150, "3", cb_3),
button4_pushed(false),
button4(Point(x_max() - 200, 20), 200, 150, "4", cb_4),
button5_pushed(false),
button5(Point(x_max() - 800, 170), 200, 150, "5", cb_5),
button6_pushed(false),
button6(Point(x_max() - 600, 170), 200, 150, "6", cb_6),
button7_pushed(false),
button7(Point(x_max() - 400, 170), 200, 150, "7", cb_7),
button8_pushed(false),
button8(Point(x_max() - 200, 170), 200, 150, "8", cb_8),
button9_pushed(false),
button9(Point(x_max() - 800, 320), 200, 150, "9", cb_9),
button10_pushed(false),
button10(Point(x_max() - 600, 320), 200, 150, "10", cb_10),
button11_pushed(false),
button11(Point(x_max() - 400, 320), 200, 150, "11", cb_11),
button12_pushed(false),
button12(Point(x_max() - 200, 320), 200, 150, "12", cb_12),
button13_pushed(false),
button13(Point(x_max() - 800, 470), 200, 150, "13", cb_13),
button14_pushed(false),
button14(Point(x_max() - 600, 470), 200, 150, "14", cb_14),
button15_pushed(false),
button15(Point(x_max() - 400, 470), 200, 150, "15", cb_15),
button16_pushed(false),
button16(Point(x_max() - 200, 470), 200, 150, "16", cb_16)
{
attach(quit_button);
attach(xy_out);
attach(button1);
attach(button2);
attach(button3);
attach(button4);
attach(button5);
attach(button6);
attach(button7);
attach(button8);
attach(button9);
attach(button10);
attach(button11);
attach(button12);
attach(button13);
attach(button14);
attach(button15);
attach(button16);
}
void My_window::next(int x, int y)
{
lines.add(Point{x,y});
// update current position readout:
ostringstream ss;
ss << '(' << x << ',' << y << ')';
xy_out.put(ss.str());
redraw();
}
void My_window::cb_next(Address, Address pw)
// call My_window::next() for the window located at pw
{
reference_to<My_window>(pw).next(0, 20);
}
void My_window::cb_quit(Address, Address pw)
// call My_window::next() for the window located at pw
{
reference_to<My_window>(pw).quit();
}
void My_window::cb_1(Address, Address pw)
{
reference_to<My_window>(pw).next(0, 20);
}
void My_window::cb_2(Address, Address pw)
{
reference_to<My_window>(pw).next(200, 20);
}
void My_window::cb_3(Address, Address pw)
{
reference_to<My_window>(pw).next(400, 20);
}
void My_window::cb_4(Address, Address pw)
{
reference_to<My_window>(pw).next(600, 20);
}
void My_window::cb_5(Address, Address pw)
{
reference_to<My_window>(pw).next(0, 170);
}
void My_window::cb_6(Address, Address pw)
{
reference_to<My_window>(pw).next(200, 170);
}
void My_window::cb_7(Address, Address pw)
{
reference_to<My_window>(pw).next(400, 170);
}
void My_window::cb_8(Address, Address pw)
{
reference_to<My_window>(pw).next(600, 170);
}
void My_window::cb_9(Address, Address pw)
{
reference_to<My_window>(pw).next(0, 320);
}
void My_window::cb_10(Address, Address pw)
{
reference_to<My_window>(pw).next(200, 320);
}
void My_window::cb_11(Address, Address pw)
{
reference_to<My_window>(pw).next(400, 320);
}
void My_window::cb_12(Address, Address pw)
{
reference_to<My_window>(pw).next(600, 320);
}
void My_window::cb_13(Address, Address pw)
{
reference_to<My_window>(pw).next(0, 470);
}
void My_window::cb_14(Address, Address pw)
{
reference_to<My_window>(pw).next(200, 470);
}
void My_window::cb_15(Address, Address pw)
{
reference_to<My_window>(pw).next(400, 470);
}
void My_window::cb_16(Address, Address pw)
{
reference_to<My_window>(pw).next(600, 470);
}
void My_window::wait_for_button()
// modified event loop:
// handle all events (as per default), quit when button_pushed becomes true
// this allows graphics without control inversion
{
while (!button_pushed) Fl::wait();
button_pushed = false;
Fl::redraw();
}
void My_window::quit()
{
hide(); // curious FLTK idiom to delete window
}
int main()
{
My_window my_win(Point(100,100), 800, 620, "My_window");
return gui_main(); //page 568
}
//------------------------------------------------------------------------------
//Kamil Petk
//13.04.2020
| [
"kamil.petk1@wp.pl"
] | kamil.petk1@wp.pl |
a97c3d710d95fd00e969067395b8aaa06c6fe78e | a6ef9674622f6e7c46ac31f4cfffbd568ff4f97e | /SteadyState_Rectangular_0_dt2t10000/processor9/0/T | fb7320ebbb8d7edffd455a455b9806e08a6adf59 | [] | no_license | jhargun/FluidIP | 4c3f6d9a87ed8ce24ed692a9bf939a9ca04222f6 | d6e0f20c1f5e1f86c160497be9d632e6d17abbf7 | refs/heads/master | 2022-08-26T02:34:26.327956 | 2020-05-26T22:33:29 | 2020-05-26T22:33:29 | 266,886,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,477 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object T;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField uniform 293;
boundaryField
{
frontAndBack
{
type zeroGradient;
}
inlet
{
type fixedValue;
value nonuniform 0();
}
outlet
{
type zeroGradient;
}
solidWall
{
type zeroGradient;
}
procBoundary9to1
{
type processor;
value uniform 293;
}
procBoundary9to8
{
type processor;
value uniform 293;
}
procBoundary9to10
{
type processor;
value uniform 293;
}
procBoundary9to15
{
type processor;
value uniform 293;
}
}
// ************************************************************************* //
| [
"48771820+jhargun@users.noreply.github.com"
] | 48771820+jhargun@users.noreply.github.com | |
4700335eea1abc1f71f9a5430edfb2deafec4d0d | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/QueueForBatchService/UNIX_QueueForBatchService_HPUX.hxx | 3b00f9aea4965ce849f177f86d0473a5788af3ee | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,824 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_HPUX
#ifndef __UNIX_QUEUEFORBATCHSERVICE_PRIVATE_H
#define __UNIX_QUEUEFORBATCHSERVICE_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
5006bfd32a62e4a25b406a90a676979b47693a41 | 4fb2fb5318ea581d2c7c96cdd47026acb5bca359 | /H264AVCEncoderLibTest/H264AVCEncoderTest.cpp | 79183104712ab39932fdb5eadf2255e3ad96f4c0 | [] | no_license | shoonmoon/JSVM_MOD | ff6cc6ef531fc90c5c29a2f4db9a0c2710090b3b | 0d3d8f07708413ce2c9259f015be69a0159722b3 | refs/heads/master | 2021-01-15T21:44:47.486713 | 2013-10-18T07:34:30 | 2013-10-18T07:34:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,622 | cpp | /*
********************************************************************************
COPYRIGHT AND WARRANTY INFORMATION
Copyright 2009-2012, International Telecommunications Union, Geneva
The Fraunhofer HHI hereby donate this source code to the ITU, with the following
understanding:
1. Fraunhofer HHI retain the right to do whatever they wish with the
contributed source code, without limit.
2. Fraunhofer HHI retain full patent rights (if any exist) in the technical
content of techniques and algorithms herein.
3. The ITU shall make this code available to anyone, free of license or
royalty fees.
DISCLAIMER OF WARRANTY
These software programs are available to the user without any license fee or
royalty on an "as is" basis. The ITU disclaims any and all warranties, whether
express, implied, or statutory, including any implied warranties of
merchantability or of fitness for a particular purpose. In no event shall the
contributor or the ITU be liable for any incidental, punitive, or consequential
damages of any kind whatsoever arising from the use of these programs.
This disclaimer of warranty extends to the user of these programs and user's
customers, employees, agents, transferees, successors, and assigns.
The ITU does not represent or warrant that the programs furnished hereunder are
free of infringement of any third-party patents. Commercial implementations of
ITU-T Recommendations, including shareware, may be subject to royalty fees to
patent holders. Information regarding the ITU-T patent policy is available from
the ITU Web site at http://www.itu.int.
THIS IS NOT A GRANT OF PATENT RIGHTS - SEE THE ITU-T PATENT POLICY.
********************************************************************************
*/
#include <time.h>
#include "H264AVCEncoderLibTest.h"
#include "H264AVCEncoderTest.h"
#include "EncoderCodingParameter.h"
#include <cstdio>
// JVT-W043
#include "RateCtlBase.h"
#include "RateCtlQuadratic.h"
// JVT-V068 {
#include "H264AVCCommonLib/SequenceParameterSet.h"
// JVT-V068 }
H264AVCEncoderTest::H264AVCEncoderTest() :
m_pcH264AVCEncoder ( NULL ),
m_pcWriteBitstreamToFile ( NULL ),
m_pcEncoderCodingParameter( NULL )
{
::memset( m_apcReadYuv, 0x00, MAX_LAYERS*sizeof(Void*) );
::memset( m_apcWriteYuv, 0x00, MAX_LAYERS*sizeof(Void*) );
::memset( m_auiLumOffset, 0x00, MAX_LAYERS*sizeof(UInt) );
::memset( m_auiCbOffset, 0x00, MAX_LAYERS*sizeof(UInt) );
::memset( m_auiCrOffset, 0x00, MAX_LAYERS*sizeof(UInt) );
::memset( m_auiHeight, 0x00, MAX_LAYERS*sizeof(UInt) );
::memset( m_auiWidth, 0x00, MAX_LAYERS*sizeof(UInt) );
::memset( m_auiStride, 0x00, MAX_LAYERS*sizeof(UInt) );
::memset( m_aauiCropping, 0x00, MAX_LAYERS*sizeof(UInt)*4);
}
H264AVCEncoderTest::~H264AVCEncoderTest()
{
}
ErrVal
H264AVCEncoderTest::create( H264AVCEncoderTest*& rpcH264AVCEncoderTest )
{
rpcH264AVCEncoderTest = new H264AVCEncoderTest;
ROT( NULL == rpcH264AVCEncoderTest );
return Err::m_nOK;
}
ErrVal H264AVCEncoderTest::init( Int argc,
Char** argv )
{
//===== create and read encoder parameters =====
RNOK( EncoderCodingParameter::create( m_pcEncoderCodingParameter ) );
if( Err::m_nOK != m_pcEncoderCodingParameter->init( argc, argv, m_cEncoderIoParameter.cBitstreamFilename ) )
{
m_pcEncoderCodingParameter->printHelp();
return -3;
}
m_cEncoderIoParameter.nResult = -1;
//===== init instances for reading and writing yuv data =====
UInt uiNumberOfLayers = m_pcEncoderCodingParameter->getAVCmode() ? 1 : m_pcEncoderCodingParameter->getNumberOfLayers();
for( UInt uiLayer = 0; uiLayer < uiNumberOfLayers; uiLayer++ )
{
h264::LayerParameters& rcLayer = m_pcEncoderCodingParameter->getLayerParameters( uiLayer );
RNOKS( WriteYuvToFile::create( m_apcWriteYuv[uiLayer] ) );
RNOKS( m_apcWriteYuv[uiLayer]->init( rcLayer.getOutputFilename() ) );
RNOKS( ReadYuvFile ::create( m_apcReadYuv [uiLayer] ) );
ReadYuvFile::FillMode eFillMode = ( rcLayer.isInterlaced() ? ReadYuvFile::FILL_FIELD : ReadYuvFile::FILL_FRAME );
#if DOLBY_ENCMUX_ENABLE
if(m_pcEncoderCodingParameter->getMuxMethod() && uiNumberOfLayers>1)
{
h264::LayerParameters& rcLayer0 = m_pcEncoderCodingParameter->getLayerParameters( 0 );
RNOKS( m_apcReadYuv[uiLayer]->init( rcLayer.getInputFilename (),
rcLayer0.getFrameHeightInSamples (),
rcLayer0.getFrameWidthInSamples (), 0, MSYS_UINT_MAX, eFillMode ) );
}
else
{
RNOKS( m_apcReadYuv[uiLayer]->init( rcLayer.getInputFilename (),
rcLayer.getFrameHeightInSamples (),
rcLayer.getFrameWidthInSamples (), 0, MSYS_UINT_MAX, eFillMode ) );
}
#else
RNOKS( m_apcReadYuv[uiLayer]->init( rcLayer.getInputFilename (),
rcLayer.getFrameHeightInSamples (),
rcLayer.getFrameWidthInSamples (), 0, MSYS_UINT_MAX, eFillMode ) );
#endif
}
//===== init bitstream writer =====
if( m_pcEncoderCodingParameter->getAVCmode() )
{
RNOKS( WriteBitstreamToFile::create ( m_pcWriteBitstreamToFile ) );
RNOKS( m_pcWriteBitstreamToFile->init ( m_cEncoderIoParameter.cBitstreamFilename ) );
}
else
{
m_cWriteToBitFileTempName = m_cEncoderIoParameter.cBitstreamFilename + ".temp";
m_cWriteToBitFileName = m_cEncoderIoParameter.cBitstreamFilename;
m_cEncoderIoParameter.cBitstreamFilename = m_cWriteToBitFileTempName;
RNOKS( WriteBitstreamToFile::create ( m_pcWriteBitstreamToFile ) );
RNOKS( m_pcWriteBitstreamToFile->init ( m_cEncoderIoParameter.cBitstreamFilename ) );
}
//===== create encoder instance =====
RNOK( h264::CreaterH264AVCEncoder::create( m_pcH264AVCEncoder ) );
//===== set start code =====
m_aucStartCodeBuffer[0] = 0;
m_aucStartCodeBuffer[1] = 0;
m_aucStartCodeBuffer[2] = 0;
m_aucStartCodeBuffer[3] = 1;
m_cBinDataStartCode.reset ();
m_cBinDataStartCode.set ( m_aucStartCodeBuffer, 4 );
// Extended NAL unit priority is enabled by default, since 6-bit short priority
// is incompatible with extended 4CIF Palma test set. Change value to false
// to enable short ID.
// Example priority ID assignment: (a) spatial, (b) temporal, (c) quality
// Other priority assignments can be created by adjusting the mapping table.
// (J. Ridge, Nokia)
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::destroy()
{
m_cBinDataStartCode.reset();
if( m_pcH264AVCEncoder )
{
RNOK( m_pcH264AVCEncoder->uninit() );
RNOK( m_pcH264AVCEncoder->destroy() );
}
for( UInt ui = 0; ui < MAX_LAYERS; ui++ )
{
if( m_apcWriteYuv[ui] )
{
RNOK( m_apcWriteYuv[ui]->uninit () );
RNOK( m_apcWriteYuv[ui]->destroy() );
}
if( m_apcReadYuv[ui] )
{
RNOK( m_apcReadYuv[ui]->uninit() );
RNOK( m_apcReadYuv[ui]->destroy() );
}
}
RNOK( m_pcEncoderCodingParameter->destroy());
for( UInt uiLayer = 0; uiLayer < MAX_LAYERS; uiLayer++ )
{
AOF( m_acActivePicBufferList[uiLayer].empty() );
//===== delete picture buffer =====
PicBufferList::iterator iter;
for( iter = m_acUnusedPicBufferList[uiLayer].begin(); iter != m_acUnusedPicBufferList[uiLayer].end(); iter++ )
{
delete [] (*iter)->getBuffer();
delete (*iter);
}
for( iter = m_acActivePicBufferList[uiLayer].begin(); iter != m_acActivePicBufferList[uiLayer].end(); iter++ )
{
delete [] (*iter)->getBuffer();
delete (*iter);
}
}
delete this;
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::xGetNewPicBuffer ( PicBuffer*& rpcPicBuffer,
UInt uiLayer,
UInt uiSize )
{
if( m_acUnusedPicBufferList[uiLayer].empty() )
{
UChar* pcBuffer = new UChar[ uiSize ];
::memset( pcBuffer, 0x00, uiSize*sizeof(UChar) );
rpcPicBuffer = new PicBuffer( pcBuffer );
}
else
{
rpcPicBuffer = m_acUnusedPicBufferList[uiLayer].popFront();
}
m_acActivePicBufferList[uiLayer].push_back( rpcPicBuffer );
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::xRemovePicBuffer( PicBufferList& rcPicBufferUnusedList,
UInt uiLayer )
{
while( ! rcPicBufferUnusedList.empty() )
{
PicBuffer* pcBuffer = rcPicBufferUnusedList.popFront();
if( NULL != pcBuffer )
{
PicBufferList::iterator begin = m_acActivePicBufferList[uiLayer].begin();
PicBufferList::iterator end = m_acActivePicBufferList[uiLayer].end ();
PicBufferList::iterator iter = std::find( begin, end, pcBuffer );
ROT( iter == end ); // there is something wrong if the address is not in the active list
AOT_DBG( (*iter)->isUsed() );
m_acUnusedPicBufferList[uiLayer].push_back( *iter );
m_acActivePicBufferList[uiLayer].erase ( iter );
}
}
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::xWrite( PicBufferList& rcPicBufferList,
UInt uiLayer )
{
while( ! rcPicBufferList.empty() )
{
PicBuffer* pcBuffer = rcPicBufferList.popFront();
Pel* pcBuf = pcBuffer->getBuffer();
RNOK( m_apcWriteYuv[uiLayer]->writeFrame( pcBuf + m_auiLumOffset[uiLayer],
pcBuf + m_auiCbOffset [uiLayer],
pcBuf + m_auiCrOffset [uiLayer],
m_auiHeight [uiLayer],
m_auiWidth [uiLayer],
m_auiStride [uiLayer], m_aauiCropping[uiLayer] ) );
}
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::xRelease( PicBufferList& rcPicBufferList,
UInt uiLayer )
{
RNOK( xRemovePicBuffer( rcPicBufferList, uiLayer ) );
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::xWrite( ExtBinDataAccessorList& rcList,
UInt& ruiBytesInFrame )
{
while( rcList.size() )
{
ruiBytesInFrame += rcList.front()->size() + 4;
RNOK( m_pcWriteBitstreamToFile->writePacket( &m_cBinDataStartCode ) );
RNOK( m_pcWriteBitstreamToFile->writePacket( rcList.front() ) );
delete[] rcList.front()->data();
delete rcList.front();
rcList.pop_front();
}
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::xRelease( ExtBinDataAccessorList& rcList )
{
while( rcList.size() )
{
delete[] rcList.front()->data();
delete rcList.front();
rcList.pop_front();
}
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::go()
{
UInt uiWrittenBytes = 0;
const UInt uiMaxFrame = m_pcEncoderCodingParameter->getTotalFrames();
UInt uiNumLayers = ( m_pcEncoderCodingParameter->getAVCmode() ? 1 : m_pcEncoderCodingParameter->getNumberOfLayers() );
UInt uiFrame;
UInt uiLayer;
UInt auiMbX [MAX_LAYERS];
UInt auiMbY [MAX_LAYERS];
UInt auiPicSize [MAX_LAYERS];
PicBuffer* apcOriginalPicBuffer [MAX_LAYERS];
PicBuffer* apcReconstructPicBuffer [MAX_LAYERS];
PicBufferList acPicBufferOutputList [MAX_LAYERS];
PicBufferList acPicBufferUnusedList [MAX_LAYERS];
ExtBinDataAccessorList cOutExtBinDataAccessorList;
Bool bMoreSets;
#if DOLBY_ENCMUX_ENABLE
PicBuffer* apcMuxPicBuffer[MAX_LAYERS];
#endif
//===== initialization =====
RNOK( m_pcH264AVCEncoder->init( m_pcEncoderCodingParameter ) );
// JVT-W043 {
bRateControlEnable = (Bool)((m_pcH264AVCEncoder->getCodingParameter()->m_uiRateControlEnable) > 0 ? true : false );
if ( bRateControlEnable )
{
Int iGOPSize = m_pcEncoderCodingParameter->getGOPSize();
Int iFullGOPs = uiMaxFrame / iGOPSize;
Double dMaximumFrameRate = m_pcEncoderCodingParameter->getMaximumFrameRate();
iGOPSize = (Int)floor( 0.5F + iGOPSize / (dMaximumFrameRate / (Float) (m_pcH264AVCEncoder->getCodingParameter()->getLayerParameters(0).m_dOutputFrameRate)) );
iGOPSize = gMax( iGOPSize, 1 );
Int uiLocalMaxFrame = (Int)floor( 0.5F + uiMaxFrame / (dMaximumFrameRate / (Float) (m_pcH264AVCEncoder->getCodingParameter()->getLayerParameters(0).m_dOutputFrameRate)) );
if ( uiLocalMaxFrame % iGOPSize == 0 )
iFullGOPs--;
Int iNb = iFullGOPs * (iGOPSize - 1);
pcJSVMParams = new jsvm_parameters;
pcGenericRC = new rc_generic( pcJSVMParams );
pcQuadraticRC = new rc_quadratic( pcGenericRC, pcJSVMParams );
// parameter initialization
pcQuadraticRC->m_iDDquant = (Int) m_pcH264AVCEncoder->getCodingParameter()->m_uiMaxQpChange;
pcQuadraticRC->m_iPMaxQpChange = (Int) m_pcH264AVCEncoder->getCodingParameter()->m_uiMaxQpChange;
pcJSVMParams->bit_rate = (Float) (m_pcH264AVCEncoder->getCodingParameter()->m_uiBitRate);
pcJSVMParams->BasicUnit = m_pcH264AVCEncoder->getCodingParameter()->m_uiBasicUnit;
pcJSVMParams->basicunit = m_pcH264AVCEncoder->getCodingParameter()->m_uiBasicUnit;
pcJSVMParams->RCMaxQP = m_pcH264AVCEncoder->getCodingParameter()->m_uiRCMaxQP;
pcJSVMParams->RCMinQP = m_pcH264AVCEncoder->getCodingParameter()->m_uiRCMinQP;
pcJSVMParams->SetInitialQP = m_pcH264AVCEncoder->getCodingParameter()->m_uiInitialQp;
pcJSVMParams->m_uiIntraPeriod = m_pcEncoderCodingParameter->getIntraPeriod();
pcJSVMParams->FrameRate = (Float) (m_pcH264AVCEncoder->getCodingParameter()->getLayerParameters(0).m_dOutputFrameRate);
pcJSVMParams->height = m_pcH264AVCEncoder->getCodingParameter()->getLayerParameters(0).m_uiFrameHeightInSamples;
pcJSVMParams->width = m_pcH264AVCEncoder->getCodingParameter()->getLayerParameters(0).m_uiFrameWidthInSamples;
pcJSVMParams->no_frames = uiMaxFrame;
pcJSVMParams->successive_Bframe = iGOPSize - 1;
pcJSVMParams->m_uiLayerId = 0;
if ( m_pcH264AVCEncoder->getCodingParameter()->m_uiAdaptInitialQP )
pcGenericRC->adaptInitialQP();
switch( iGOPSize )
{
case 1:
pcJSVMParams->HierarchicalLevels = 0;
break;
case 2:
pcJSVMParams->HierarchicalLevels = 1;
break;
case 4:
pcJSVMParams->HierarchicalLevels = 2;
break;
case 8:
pcJSVMParams->HierarchicalLevels = 3;
break;
case 16:
pcJSVMParams->HierarchicalLevels = 4;
break;
case 32:
default:
fprintf(stderr, "\n RC not stable for large number of hierarchical levels...exiting...\n" );
assert(0); // some compilers do not compile assert in release/Ox mode
exit(1);
break;
}
// rate control initialization functions
pcQuadraticRC->init();
pcQuadraticRC->rc_init_seq();
pcQuadraticRC->rc_init_GOP(uiMaxFrame - iNb - 1, iNb);
pcGenericRC->generic_alloc();
}
// JVT-W043 }
//===== write parameter sets =====
for( bMoreSets = true; bMoreSets; )
{
UChar aucParameterSetBuffer[1000];
BinData cBinData;
cBinData.reset();
cBinData.set( aucParameterSetBuffer, 1000 );
ExtBinDataAccessor cExtBinDataAccessor;
cBinData.setMemAccessor( cExtBinDataAccessor );
h264::SequenceParameterSet* pcAVCSPS = NULL;
RNOK( m_pcH264AVCEncoder->writeParameterSets( &cExtBinDataAccessor, pcAVCSPS, bMoreSets ) );
if( m_pcH264AVCEncoder->getScalableSeiMessage() )
{
RNOK( m_pcWriteBitstreamToFile->writePacket ( &m_cBinDataStartCode ) );
RNOK( m_pcWriteBitstreamToFile->writePacket ( &cExtBinDataAccessor ) );
uiWrittenBytes += 4 + cExtBinDataAccessor.size();
}
cBinData.reset();
// JVT-V068 {
/* luodan */
if (pcAVCSPS)
{
cBinData.set( aucParameterSetBuffer, 1000 );
ExtBinDataAccessor cExtBinDataAccessorl;
cBinData.setMemAccessor( cExtBinDataAccessorl );
RNOK( m_pcH264AVCEncoder->writeAVCCompatibleHRDSEI( &cExtBinDataAccessorl, pcAVCSPS ) );
RNOK( m_pcWriteBitstreamToFile->writePacket ( &m_cBinDataStartCode ) );
RNOK( m_pcWriteBitstreamToFile->writePacket ( &cExtBinDataAccessorl ) );
uiWrittenBytes += 4 + cExtBinDataAccessorl.size();
cBinData.reset();
}
/* luodan */
// JVT-V068 }
}
//===== determine parameters for required frame buffers =====
UInt uiAllocMbX = 0;
UInt uiAllocMbY = 0;
for( uiLayer = 0; uiLayer < uiNumLayers; uiLayer++ )
{
h264::LayerParameters& rcLayer = m_pcEncoderCodingParameter->getLayerParameters( uiLayer );
auiMbX [uiLayer] = rcLayer.getFrameWidthInMbs ();
auiMbY [uiLayer] = rcLayer.getFrameHeightInMbs();
uiAllocMbX = gMax( uiAllocMbX, auiMbX[uiLayer] );
uiAllocMbY = gMax( uiAllocMbY, auiMbY[uiLayer] );
m_aauiCropping[uiLayer][0] = 0;
m_aauiCropping[uiLayer][1] = rcLayer.getHorPadding ();
m_aauiCropping[uiLayer][2] = 0;
m_aauiCropping[uiLayer][3] = rcLayer.getVerPadding ();
m_auiHeight [uiLayer] = auiMbY[uiLayer]<<4;
m_auiWidth [uiLayer] = auiMbX[uiLayer]<<4;
UInt uiSize = ((uiAllocMbY<<4)+2*YUV_Y_MARGIN)*((uiAllocMbX<<4)+2*YUV_X_MARGIN);
auiPicSize [uiLayer] = ((uiAllocMbX<<4)+2*YUV_X_MARGIN)*((uiAllocMbY<<4)+2*YUV_Y_MARGIN)*3/2;
m_auiLumOffset[uiLayer] = ((uiAllocMbX<<4)+2*YUV_X_MARGIN)* YUV_Y_MARGIN + YUV_X_MARGIN;
m_auiCbOffset [uiLayer] = ((uiAllocMbX<<3)+ YUV_X_MARGIN)* YUV_Y_MARGIN/2 + YUV_X_MARGIN/2 + uiSize;
m_auiCrOffset [uiLayer] = ((uiAllocMbX<<3)+ YUV_X_MARGIN)* YUV_Y_MARGIN/2 + YUV_X_MARGIN/2 + 5*uiSize/4;
m_auiStride [uiLayer] = (uiAllocMbX<<4)+ 2*YUV_X_MARGIN;
}
#if DOLBY_ENCMUX_ENABLE
if(m_pcEncoderCodingParameter->getMuxMethod() && uiNumLayers >1)
{
for(uiLayer=0; uiLayer<2; uiLayer++)
{
apcMuxPicBuffer[uiLayer] = NULL;
UChar* pcBuffer = new UChar[ auiPicSize[uiLayer] ];
::memset( pcBuffer, 0x00, auiPicSize[uiLayer] *sizeof(UChar) );
apcMuxPicBuffer[uiLayer] = new PicBuffer( pcBuffer );
}
}
else
{
for(uiLayer=0; uiLayer<2; uiLayer++)
{
apcMuxPicBuffer[uiLayer] = NULL;
}
}
#endif
// start time measurement
clock_t start = clock();
//===== loop over frames =====
for( uiFrame = 0; uiFrame < uiMaxFrame; uiFrame++ )
{
//===== get picture buffers and read original pictures =====
for( uiLayer = 0; uiLayer < uiNumLayers; uiLayer++ )
{
UInt uiSkip = ( 1 << m_pcEncoderCodingParameter->getLayerParameters( uiLayer ).getTemporalResolution() );
if( uiFrame % uiSkip == 0 )
{
RNOK( xGetNewPicBuffer( apcReconstructPicBuffer [uiLayer], uiLayer, auiPicSize[uiLayer] ) );
RNOK( xGetNewPicBuffer( apcOriginalPicBuffer [uiLayer], uiLayer, auiPicSize[uiLayer] ) );
#if DOLBY_ENCMUX_ENABLE
if( (m_pcEncoderCodingParameter->getMuxMethod() && uiNumLayers >1) )
{
RNOK( m_apcReadYuv[uiLayer]->readFrame( *apcOriginalPicBuffer[uiLayer] + m_auiLumOffset[0],
*apcOriginalPicBuffer[uiLayer] + m_auiCbOffset [0],
*apcOriginalPicBuffer[uiLayer] + m_auiCrOffset [0],
m_auiHeight [0],
m_auiWidth [0],
m_auiStride [0] ) );
}
else
{
RNOK( m_apcReadYuv[uiLayer]->readFrame( *apcOriginalPicBuffer[uiLayer] + m_auiLumOffset[uiLayer],
*apcOriginalPicBuffer[uiLayer] + m_auiCbOffset [uiLayer],
*apcOriginalPicBuffer[uiLayer] + m_auiCrOffset [uiLayer],
m_auiHeight [uiLayer],
m_auiWidth [uiLayer],
m_auiStride [uiLayer] ) );
}
#else
RNOK( m_apcReadYuv[uiLayer]->readFrame( *apcOriginalPicBuffer[uiLayer] + m_auiLumOffset[uiLayer],
*apcOriginalPicBuffer[uiLayer] + m_auiCbOffset [uiLayer],
*apcOriginalPicBuffer[uiLayer] + m_auiCrOffset [uiLayer],
m_auiHeight [uiLayer],
m_auiWidth [uiLayer],
m_auiStride [uiLayer] ) );
#endif
}
else
{
apcReconstructPicBuffer [uiLayer] = 0;
apcOriginalPicBuffer [uiLayer] = 0;
}
}
#if DOLBY_ENCMUX_ENABLE
if( (m_pcEncoderCodingParameter->getMuxMethod() && uiNumLayers >1) && (apcOriginalPicBuffer[0] && apcOriginalPicBuffer[1]))
{
//mux process;
if(m_pcEncoderCodingParameter->getMuxMethod() == 1)
{
h264::LayerParameters& rcLayer0 = m_pcEncoderCodingParameter->getLayerParameters( 0 );
UInt uiWidth = rcLayer0.getFrameWidthInSamples();
UInt uiHeight = rcLayer0.getFrameHeightInSamples();
sbsMux(*apcMuxPicBuffer[0] + m_auiLumOffset[0], m_auiStride[0], *apcOriginalPicBuffer[0] + m_auiLumOffset[0], *apcOriginalPicBuffer[1] + m_auiLumOffset[0], m_auiStride[0],
uiWidth, uiHeight, m_pcEncoderCodingParameter->getMuxOffset(0), m_pcEncoderCodingParameter->getMuxOffset(1), m_pcEncoderCodingParameter->getMuxFilter());
sbsMux(*apcMuxPicBuffer[0] + m_auiCbOffset[0], (m_auiStride[0]>>1), *apcOriginalPicBuffer[0] + m_auiCbOffset[0], *apcOriginalPicBuffer[1] + m_auiCbOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1), m_pcEncoderCodingParameter->getMuxOffset(0), m_pcEncoderCodingParameter->getMuxOffset(1), m_pcEncoderCodingParameter->getMuxFilter());
sbsMux(*apcMuxPicBuffer[0] + m_auiCrOffset[0], (m_auiStride[0]>>1), *apcOriginalPicBuffer[0] + m_auiCrOffset[0], *apcOriginalPicBuffer[1] + m_auiCrOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1), m_pcEncoderCodingParameter->getMuxOffset(0), m_pcEncoderCodingParameter->getMuxOffset(1), m_pcEncoderCodingParameter->getMuxFilter());
//padding;
RNOK(padBuf(*apcMuxPicBuffer[0] + m_auiLumOffset[0], m_auiStride[0], uiWidth, uiHeight, m_auiWidth[0], m_auiHeight[0], m_apcReadYuv[0]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[0] + m_auiCbOffset[0], (m_auiStride[0]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[0]>>1), (m_auiHeight[0]>>1), m_apcReadYuv[0]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[0] + m_auiCrOffset[0], (m_auiStride[0]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[0]>>1), (m_auiHeight[0]>>1), m_apcReadYuv[0]->getFillMode()));
sbsMuxFR(*apcMuxPicBuffer[1] + m_auiLumOffset[1], m_auiStride[1], *apcOriginalPicBuffer[0] + m_auiLumOffset[0], *apcOriginalPicBuffer[1] + m_auiLumOffset[0], m_auiStride[0],
uiWidth, uiHeight);
sbsMuxFR(*apcMuxPicBuffer[1] + m_auiCbOffset[1], (m_auiStride[1]>>1), *apcOriginalPicBuffer[0] + m_auiCbOffset[0], *apcOriginalPicBuffer[1] + m_auiCbOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1));
sbsMuxFR(*apcMuxPicBuffer[1] + m_auiCrOffset[1], (m_auiStride[1]>>1), *apcOriginalPicBuffer[0] + m_auiCrOffset[0], *apcOriginalPicBuffer[1] + m_auiCrOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1));
//padding;
uiWidth = m_pcEncoderCodingParameter->getLayerParameters( 1 ).getFrameWidthInSamples();
uiHeight = m_pcEncoderCodingParameter->getLayerParameters( 1 ).getFrameHeightInSamples();
RNOK(padBuf(*apcMuxPicBuffer[1] + m_auiLumOffset[1], m_auiStride[1], uiWidth, uiHeight, m_auiWidth[1], m_auiHeight[1], m_apcReadYuv[1]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[1] + m_auiCbOffset[1], (m_auiStride[1]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[1]>>1), (m_auiHeight[1]>>1), m_apcReadYuv[1]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[1] + m_auiCrOffset[1], (m_auiStride[1]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[1]>>1), (m_auiHeight[1]>>1), m_apcReadYuv[1]->getFillMode()));
}
else
{
h264::LayerParameters& rcLayer0 = m_pcEncoderCodingParameter->getLayerParameters( 0 );
UInt uiWidth = rcLayer0.getFrameWidthInSamples();
UInt uiHeight = rcLayer0.getFrameHeightInSamples();
tabMux(*apcMuxPicBuffer[0] + m_auiLumOffset[0], m_auiStride[0], *apcOriginalPicBuffer[0] + m_auiLumOffset[0], *apcOriginalPicBuffer[1] + m_auiLumOffset[0], m_auiStride[0],
uiWidth, uiHeight, m_pcEncoderCodingParameter->getMuxOffset(0), m_pcEncoderCodingParameter->getMuxOffset(1), m_pcEncoderCodingParameter->getMuxFilter());
tabMux(*apcMuxPicBuffer[0] + m_auiCbOffset[0], (m_auiStride[0]>>1), *apcOriginalPicBuffer[0] + m_auiCbOffset[0], *apcOriginalPicBuffer[1] + m_auiCbOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1), m_pcEncoderCodingParameter->getMuxOffset(0), m_pcEncoderCodingParameter->getMuxOffset(1), m_pcEncoderCodingParameter->getMuxFilter());
tabMux(*apcMuxPicBuffer[0] + m_auiCrOffset[0], (m_auiStride[0]>>1), *apcOriginalPicBuffer[0] + m_auiCrOffset[0], *apcOriginalPicBuffer[1] + m_auiCrOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1), m_pcEncoderCodingParameter->getMuxOffset(0), m_pcEncoderCodingParameter->getMuxOffset(1), m_pcEncoderCodingParameter->getMuxFilter());
//padding;
RNOK(padBuf(*apcMuxPicBuffer[0] + m_auiLumOffset[0], m_auiStride[0], uiWidth, uiHeight, m_auiWidth[0], m_auiHeight[0], m_apcReadYuv[0]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[0] + m_auiCbOffset[0], (m_auiStride[0]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[0]>>1), (m_auiHeight[0]>>1), m_apcReadYuv[0]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[0] + m_auiCrOffset[0], (m_auiStride[0]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[0]>>1), (m_auiHeight[0]>>1), m_apcReadYuv[0]->getFillMode()));
tabMuxFR(*apcMuxPicBuffer[1] + m_auiLumOffset[1], m_auiStride[1], *apcOriginalPicBuffer[0] + m_auiLumOffset[0], *apcOriginalPicBuffer[1] + m_auiLumOffset[0], m_auiStride[0],
uiWidth, uiHeight);
tabMuxFR(*apcMuxPicBuffer[1] + m_auiCbOffset[1], (m_auiStride[1]>>1), *apcOriginalPicBuffer[0] + m_auiCbOffset[0], *apcOriginalPicBuffer[1] + m_auiCbOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1));
tabMuxFR(*apcMuxPicBuffer[1] + m_auiCrOffset[1], (m_auiStride[1]>>1), *apcOriginalPicBuffer[0] + m_auiCrOffset[0], *apcOriginalPicBuffer[1] + m_auiCrOffset[0], (m_auiStride[0]>>1),
(uiWidth>>1), (uiHeight>>1));
//padding;
uiWidth = m_pcEncoderCodingParameter->getLayerParameters( 1 ).getFrameWidthInSamples();
uiHeight = m_pcEncoderCodingParameter->getLayerParameters( 1 ).getFrameHeightInSamples();
RNOK(padBuf(*apcMuxPicBuffer[1] + m_auiLumOffset[1], m_auiStride[1], uiWidth, uiHeight, m_auiWidth[1], m_auiHeight[1], m_apcReadYuv[1]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[1] + m_auiCbOffset[1], (m_auiStride[1]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[1]>>1), (m_auiHeight[1]>>1), m_apcReadYuv[1]->getFillMode()));
RNOK(padBuf(*apcMuxPicBuffer[1] + m_auiCrOffset[1], (m_auiStride[1]>>1), (uiWidth>>1), (uiHeight>>1), (m_auiWidth[1]>>1), (m_auiHeight[1]>>1), m_apcReadYuv[1]->getFillMode()));
}
//swap the buffer;
for( uiLayer = 0; uiLayer < 2; uiLayer++ )
{
PicBuffer *pTmp = m_acActivePicBufferList[uiLayer].popBack();
apcOriginalPicBuffer[uiLayer] = apcMuxPicBuffer[uiLayer];
m_acActivePicBufferList[uiLayer].pushBack(apcOriginalPicBuffer[uiLayer]);
apcMuxPicBuffer[uiLayer] = pTmp;
}
}
#endif
//===== call encoder =====
RNOK( m_pcH264AVCEncoder->process( cOutExtBinDataAccessorList,
apcOriginalPicBuffer,
apcReconstructPicBuffer,
acPicBufferOutputList,
acPicBufferUnusedList ) );
//===== write and release NAL unit buffers =====
UInt uiBytesUsed = 0;
RNOK( xWrite ( cOutExtBinDataAccessorList, uiBytesUsed ) );
uiWrittenBytes += uiBytesUsed;
//===== write and release reconstructed pictures =====
for( uiLayer = 0; uiLayer < uiNumLayers; uiLayer++ )
{
RNOK( xWrite ( acPicBufferOutputList[uiLayer], uiLayer ) );
RNOK( xRelease( acPicBufferUnusedList[uiLayer], uiLayer ) );
}
}
// stop time measurement
clock_t end = clock();
//===== finish encoding =====
UInt uiNumCodedFrames = 0;
Double dHighestLayerOutputRate = 0.0;
RNOK( m_pcH264AVCEncoder->finish( cOutExtBinDataAccessorList,
acPicBufferOutputList,
acPicBufferUnusedList,
uiNumCodedFrames,
dHighestLayerOutputRate ) );
//===== write and release NAL unit buffers =====
RNOK( xWrite ( cOutExtBinDataAccessorList, uiWrittenBytes ) );
//===== write and release reconstructed pictures =====
for( uiLayer = 0; uiLayer < uiNumLayers; uiLayer++ )
{
RNOK( xWrite ( acPicBufferOutputList[uiLayer], uiLayer ) );
RNOK( xRelease( acPicBufferUnusedList[uiLayer], uiLayer ) );
}
//===== set parameters and output summary =====
m_cEncoderIoParameter.nFrames = uiFrame;
m_cEncoderIoParameter.nResult = 0;
if( ! m_pcEncoderCodingParameter->getAVCmode() )
{
UChar aucParameterSetBuffer[10000];
BinData cBinData;
cBinData.reset();
cBinData.set( aucParameterSetBuffer, 10000 );
ExtBinDataAccessor cExtBinDataAccessor;
cBinData.setMemAccessor( cExtBinDataAccessor );
m_pcH264AVCEncoder->SetVeryFirstCall();
h264::SequenceParameterSet* pcAVCSPS = NULL;
RNOK( m_pcH264AVCEncoder->writeParameterSets( &cExtBinDataAccessor, pcAVCSPS, bMoreSets ) );
RNOK( m_pcWriteBitstreamToFile->writePacket ( &m_cBinDataStartCode ) );
RNOK( m_pcWriteBitstreamToFile->writePacket ( &cExtBinDataAccessor ) );
uiWrittenBytes += 4 + cExtBinDataAccessor.size();
cBinData.reset();
}
if( m_pcWriteBitstreamToFile )
{
RNOK( m_pcWriteBitstreamToFile->uninit() );
RNOK( m_pcWriteBitstreamToFile->destroy() );
}
if( ! m_pcEncoderCodingParameter->getAVCmode() )
{
RNOK ( ScalableDealing() );
}
// JVT-W043 {
if ( bRateControlEnable )
{
delete pcJSVMParams;
delete pcGenericRC;
delete pcQuadraticRC;
}
// JVT-W043 }
#if DOLBY_ENCMUX_ENABLE
for(uiLayer=0; uiLayer<2; uiLayer++)
{
if(apcMuxPicBuffer[uiLayer])
{
delete [] (*apcMuxPicBuffer[uiLayer]);
delete apcMuxPicBuffer[uiLayer];
}
}
#endif
// output encoding time
fprintf(stdout, "Encoding speed: %.3lf ms/frame, Time:%.3lf ms, Frames: %d\n", (double)(end-start)*1000/CLOCKS_PER_SEC/uiMaxFrame, (double)(end-start)*1000/CLOCKS_PER_SEC, uiMaxFrame);
return Err::m_nOK;
}
ErrVal
H264AVCEncoderTest::ScalableDealing()
{
FILE *ftemp = fopen( m_cWriteToBitFileTempName.c_str(), "rb" );
FILE *f = fopen( m_cWriteToBitFileName.c_str (), "wb" );
UChar pvBuffer[4];
fseek( ftemp, SEEK_SET, SEEK_END );
long lFileLength = ftell( ftemp );
long lpos = 0;
long loffset = -5; //start offset from end of file
Bool bMoreSets = true;
do
{
fseek( ftemp, loffset, SEEK_END);
ROF( 4 == fread( pvBuffer, 1, 4, ftemp ) );
if( pvBuffer[0] == 0 && pvBuffer[1] == 0 && pvBuffer[2] == 0 && pvBuffer[3] == 1)
{
bMoreSets = false;
lpos = abs( loffset );
}
else
{
loffset --;
}
} while( bMoreSets );
fseek( ftemp, loffset, SEEK_END );
UChar *pvChar = new UChar[lFileLength];
ROF( lpos == fread( pvChar, 1, lpos, ftemp ) );
fseek( ftemp, 0, SEEK_SET );
ROF( lFileLength-lpos == fread( pvChar+lpos, 1, lFileLength-lpos, ftemp) );
fflush(ftemp);
fclose(ftemp);
ROF( lFileLength == fwrite( pvChar, 1, lFileLength, f ) );
delete [] pvChar;
fflush(f);
fclose(f);
RNOK( remove( m_cWriteToBitFileTempName.c_str() ) );
return Err::m_nOK;
}
| [
"moonsh1028@gmail.com"
] | moonsh1028@gmail.com |
ba75ef94e54675f0c67b8bbfafa59e1e16fd159a | 053eba798f0d9d9cc1b435b206d7084c1277e181 | /GLTest/src/Mesh.cpp | 00d94cac4ad8f12c191a1bf0ae8dbab723070f19 | [
"MIT"
] | permissive | hmmvot/gltest | c79ef4f667d5c7badbf1b3b55ffbb7454ff4027c | 642b57c75d85744c07c037ad6110fa0fd382b5d4 | refs/heads/master | 2021-01-25T09:45:22.570003 | 2018-03-07T13:05:26 | 2018-03-07T13:05:26 | 123,318,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,139 | cpp | #include "Mesh.h"
Mesh::Mesh()
{
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glGenBuffers(1, &m_EBO);
}
Mesh::~Mesh()
{
glDeleteVertexArrays(1, &m_VAO);
glDeleteBuffers(1, &m_VBO);
glDeleteBuffers(1, &m_EBO);
}
void Mesh::SetVertices(const std::initializer_list<glm::vec3> &vertices)
{
SetVertices(std::begin(vertices), std::end(vertices));
}
void Mesh::SetUv0(const std::initializer_list<glm::vec2> &uvs)
{
SetUv0(std::begin(uvs), std::end(uvs));
}
void Mesh::SetUv1(const std::initializer_list<glm::vec2> &uvs)
{
SetUv1(std::begin(uvs), std::end(uvs));
}
void Mesh::SetUv2(const std::initializer_list<glm::vec2> &uvs)
{
SetUv2(std::begin(uvs), std::end(uvs));
}
void Mesh::SetUv3(const std::initializer_list<glm::vec2> &uvs)
{
SetUv3(std::begin(uvs), std::end(uvs));
}
void Mesh::SetNormals(const std::initializer_list<glm::vec3> &normals)
{
SetNormals(std::begin(normals), std::end(normals));
}
void Mesh::SetTriangles(const std::initializer_list<Triangle> &triangles)
{
SetTriangles(std::begin(triangles), std::end(triangles));
}
template <class T>
static void SetupAttributeArray(
GLuint index,
GLint size,
GLenum type,
GLboolean normalized,
size_t &shift)
{
glVertexAttribPointer(index, size, type, normalized, sizeof(Vertex), reinterpret_cast<GLvoid*>(shift));
glEnableVertexAttribArray(index);
shift += sizeof(T);
}
void Mesh::Update()
{
if (!m_Dirty)
{
return;
}
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, m_Vertices.size() * sizeof(Vertex), m_Vertices.data(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Triangles.size() * sizeof(Triangle), m_Triangles.data(), GL_DYNAMIC_DRAW);
size_t shift = 0;
SetupAttributeArray<glm::vec3>(0, 3, GL_FLOAT, GL_FALSE, shift);
SetupAttributeArray<glm::vec4>(1, 4, GL_FLOAT, GL_FALSE, shift);
SetupAttributeArray<glm::vec2>(2, 2, GL_FLOAT, GL_FALSE, shift);
SetupAttributeArray<glm::vec2>(3, 2, GL_FLOAT, GL_FALSE, shift);
SetupAttributeArray<glm::vec2>(4, 2, GL_FLOAT, GL_FALSE, shift);
SetupAttributeArray<glm::vec2>(5, 2, GL_FLOAT, GL_FALSE, shift);
SetupAttributeArray<glm::vec3>(6, 3, GL_FLOAT, GL_FALSE, shift);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
m_Dirty = false;
}
void Mesh::Resize(int targetSize)
{
if (targetSize <= 0)
{
return;
}
const auto size = static_cast<size_t>(targetSize);
if (m_Vertices.size() < size)
{
const auto oldSize = m_Vertices.size();
m_Vertices.resize(size);
for (auto i = oldSize; i < size; ++i)
{
m_Vertices[i].color = {1, 1, 1, 1};
}
}
}
void Mesh::Draw()
{
Update();
glBindVertexArray(m_VAO);
glDrawElements(GL_TRIANGLES, m_Triangles.size() * 3, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
}
std::shared_ptr<Mesh> Mesh::CreateCube()
{
auto mesh = std::make_shared<Mesh>();
mesh->SetVertices({
{0.5f, 0.5f, 0.5f}, {0.5f, -0.5f, 0.5f}, {-0.5f, -0.5f, 0.5f}, {-0.5f, 0.5f, 0.5f}, // front
{0.5f, 0.5f, -0.5f}, {0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, -0.5f}, {-0.5f, 0.5f, -0.5f}, // back
{0.5f, 0.5f, 0.5f}, {0.5f, 0.5f, -0.5f}, {-0.5f, 0.5f, -0.5f}, {-0.5f, 0.5f, 0.5f}, // top
{0.5f, -0.5f, 0.5f}, {0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, -0.5f}, {-0.5f, -0.5f, 0.5f}, // down
{0.5f, 0.5f, 0.5f}, {0.5f, -0.5f, 0.5f}, {0.5f, -0.5f, -0.5f}, {0.5f, 0.5f, -0.5f}, // right
{-0.5f, 0.5f, 0.5f}, {-0.5f, -0.5f, 0.5f}, {-0.5f, -0.5f, -0.5f}, {-0.5f, 0.5f, -0.5f}, // left
});
std::initializer_list<glm::vec2> uvs = {
{1, 1}, {1, 0}, {0, 0}, {0, 1},
{1, 1}, {1, 0}, {0, 0}, {0, 1},
{1, 1}, {1, 0}, {0, 0}, {0, 1},
{1, 1}, {1, 0}, {0, 0}, {0, 1},
{1, 1}, {1, 0}, {0, 0}, {0, 1},
{1, 1}, {1, 0}, {0, 0}, {0, 1},
};
mesh->SetUv0(uvs);
mesh->SetUv1(uvs);
mesh->SetUv2(uvs);
mesh->SetUv3(uvs);
mesh->SetTriangles({
{0, 1, 3}, {1, 2, 3},
{4, 5, 7}, {5, 6, 7},
{8, 9, 11}, {9, 10, 11},
{12, 13, 15}, {13, 14, 15},
{16, 17, 19}, {17, 18, 19},
{20, 21, 23}, {21, 22, 23},
});
mesh->SetNormals({
{0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}, // front
{0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, // back
{0, 1, 0}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0}, // top
{0, -1, 0}, {0, -1, 0}, {0, -1, 0}, {0, -1, 0}, // down
{1, 0, 0}, {1, 0, 0}, {1, 0, 0}, {1, 0, 0}, // right
{-1, 0, 0}, {-1, 0, 0}, {-1, 0, 0}, {-1, 0, 0}, // left
});
return mesh;
}
std::shared_ptr<Mesh> Mesh::CreatePlane()
{
auto mesh = std::make_shared<Mesh>();
mesh->SetVertices({
{0.5f, 0.5f, 0}, {0.5f, -0.5f, 0}, {-0.5f, -0.5f, 0}, {-0.5f, 0.5f, 0}
});
mesh->SetUv0({
{1, 1}, {1, 0}, {0, 0}, {0, 1},
});
mesh->SetUv1({
{1, 1}, {1, 0}, {0, 0}, {0, 1},
});
mesh->SetUv2({
{1, 1}, {1, 0}, {0, 0}, {0, 1},
});
mesh->SetUv3({
{1, 1}, {1, 0}, {0, 0}, {0, 1},
});
mesh->SetTriangles({
{0, 1, 3}, {1, 2, 3},
});
mesh->SetNormals({
{0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1},
});
return mesh;
}
| [
"a.sokolenko@corp.mail.ru"
] | a.sokolenko@corp.mail.ru |
192d79e5169d9964987130940cb81ebe422660dd | 998a64d787a47a78a4c6dbad3057937ac022bfc7 | /PA 8 Data Analysis Using BSTs/TransactionNode.cpp | e0cd92fab2773a6544e741bc551d14e47b372e85 | [] | no_license | zfechko/PA-8-Data-Analysis-Using-BSTs | 19efe9ce4845d68ed5a11d7b6ae111fc84a0ff13 | 9db7e7a474794c532db683c3fe35e17ad5abd63b | refs/heads/master | 2023-09-06T06:20:55.380120 | 2021-11-19T23:23:37 | 2021-11-19T23:23:37 | 429,515,028 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 424 | cpp | #include "TransactionNode.h"
TransactionNode::TransactionNode(string newData, int newUnits) : Node(newData)
{
units = newUnits;
}
TransactionNode::~TransactionNode()
{
//implicit
}
int TransactionNode::getUnits() const
{
return units;
}
void TransactionNode::setUnits(int newUnits)
{
units = newUnits;
}
void TransactionNode::printData()
{
cout << " " << this->mData << " : " << this->units << " units." << endl;
} | [
"zachary.fechko@wsu.edu"
] | zachary.fechko@wsu.edu |
1eaebb43323cfdd7308fb1abdcd46436d2c9a809 | 5126b44bfcaf9bb0de69d41049dc37cc4bf45a75 | /Classes/MultiScene.cpp | 46d868be727716156ab5e49688aa99f8e7565400 | [] | no_license | zoominhao/CountMoney | e61b50609bf3b71e3d7f069a577ead518c877bd7 | e8c20727e901cd3d8da3ff0723654ccaad8abfd2 | refs/heads/master | 2021-01-15T16:29:08.392740 | 2015-09-16T10:31:25 | 2015-09-16T10:31:25 | 41,010,494 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 58,253 | cpp | #include "MultiScene.h"
#include "StartScene.h"
#include "AudioControl.h"
#include "MultiEndScene.h"
#include "MCManual.h"
#include <time.h>
USING_NS_CC;
Scene* MultiScene::createScene()
{
auto scene = Scene::create();
auto layer = MultiScene::create();
scene->addChild(layer);
return scene;
}
bool MultiScene::init()
{
if (!Layer::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
addControlBtns(1);
addControlBtns(2);
//preload audio
//AudioControl::preLoad();
//add background image
setBgImage();
//target num
srand((unsigned)time(NULL));
//int x = rand() % 30;
//m_targetNum = x * 100 + 5000;
/*if (MCManual::novice[3])
{
m_targetNum = 7000;
}*/
m_targetNum = 7000;
char targetNumStr[30];
sprintf(targetNumStr, " %d", m_targetNum);
addTargetNumLabel(1, targetNumStr);
addTargetNumLabel(2, targetNumStr);
//添加玩家,该场景为双人模式
m_player1 = Player::create();
m_player1->createPlayer(2);
m_player1->MoneyTotal()->MoneySprite()->setScale(0.5);
m_player1->setTotalMoneySpritePos(0, -130);
m_player1->setTotalMoneyNumPos(0, -20);
m_player1->setScoreFontSize(20);
m_player1->ScoreFrame()->setPosition(visibleSize.width / 2, origin.y + 50);
m_player1->ScoreFrame()->setScale(0.335);
this->addChild(m_player1, 1);
m_player2 = Player::create();
m_player2->createPlayer(2);
m_player2->MoneyTotal()->MoneySprite()->setScale(0.5);
m_player2->MoneyTotal()->MoneySprite()->setRotation(270);
m_player2->setTotalMoneySpritePos(0, visibleSize.width - 95);
m_player2->setTotalMoneyNumPos(0, visibleSize.height - 115);
m_player2->setScoreFontSize(20);
m_player2->setTotalMoneyNumRot(180);
m_player2->ScoreFrame()->setPosition(visibleSize.width / 2, visibleSize.height - 50);
m_player2->ScoreFrame()->setRotation(180);
m_player2->ScoreFrame()->setScale(0.335);
this->addChild(m_player2, 1);
addWallet();
addGateWay();
addCurScore();
addPlayerName2();
//飘字
m_flyWord[0][0] = FlyWord::create("flyword/+100.png", 0.5, Vec2(origin.x + visibleSize.width/2 - 100, origin.y + visibleSize.height / 2 - 300), 25);
this->addChild(m_flyWord[0][0], 2);
m_flyWord[0][1] = FlyWord::create("flyword/+200.png", 0.5, Vec2(origin.x + visibleSize.width / 2 - 100, origin.y + visibleSize.height / 2 - 300), 25);
this->addChild(m_flyWord[0][1], 2);
m_flyWord[0][2] = FlyWord::create("flyword/-300.png", 0.5, Vec2(origin.x + visibleSize.width / 2 - 100, origin.y + visibleSize.height / 2 - 300), 25);
this->addChild(m_flyWord[0][2], 2);
m_flyWord[0][3] = FlyWord::create("flyword/-500.png", 0.5, Vec2(origin.x + visibleSize.width / 2 - 100, origin.y + visibleSize.height / 2 - 300), 25);
this->addChild(m_flyWord[0][3], 2);
m_flyWord[1][0] = FlyWord::create("flyword/+100.png", 0.5, Vec2(origin.x + visibleSize.width / 2 + 100, origin.y + visibleSize.height / 2 + 300), -25);
m_flyWord[1][0]->setRotation(180);
this->addChild(m_flyWord[1][0], 2);
m_flyWord[1][1] = FlyWord::create("flyword/+200.png", 0.5, Vec2(origin.x + visibleSize.width / 2 + 100, origin.y + visibleSize.height / 2 + 300), -25);
m_flyWord[1][1]->setRotation(180);
this->addChild(m_flyWord[1][1], 2);
m_flyWord[1][2] = FlyWord::create("flyword/-300.png", 0.5, Vec2(origin.x + visibleSize.width / 2 + 100, origin.y + visibleSize.height / 2 + 300), -25);
m_flyWord[1][2]->setRotation(180);
this->addChild(m_flyWord[1][2], 2);
m_flyWord[1][3] = FlyWord::create("flyword/-500.png", 0.5, Vec2(origin.x + visibleSize.width / 2 + 100, origin.y + visibleSize.height / 2 + 300), -25);
this->addChild(m_flyWord[1][3], 2);
//鼓励文字
for (int i = 0; i < 6; ++i)
{
m_zoomingWord[0][i] = ZoomingWord::create(String::createWithFormat("encourage/encourage_%d.png", i + 1)->getCString(),
Vec2(origin.x + visibleSize.width / 2 - 200, origin.y + visibleSize.height / 2 - 200));
m_zoomingWord[0][i]->setScale(0.8);
this->addChild(m_zoomingWord[0][i], 2);
m_zoomingWord[1][i] = ZoomingWord::create(String::createWithFormat("encourage/encourage_%d.png", i + 1)->getCString(),
Vec2(origin.x + visibleSize.width / 2 + 200, origin.y + visibleSize.height / 2 + 200));
m_zoomingWord[1][i]->setScale(0.8);
m_zoomingWord[1][i]->setRotation(180);
this->addChild(m_zoomingWord[1][i], 2);
}
m_p1GoodCount = 0;
m_p2GoodCount = 0;
//播放背景音乐
AudioControl::stopBGMusic();
AudioControl::playBgMusic(PK_OFFLINE);
//注册多点触屏事件
auto mutiTouchlistener = EventListenerTouchAllAtOnce::create();
mutiTouchlistener->onTouchesBegan = CC_CALLBACK_2(MultiScene::onTouchesBegan, this);
mutiTouchlistener->onTouchesMoved = CC_CALLBACK_2(MultiScene::onTouchesMoved, this);
mutiTouchlistener->onTouchesEnded = CC_CALLBACK_2(MultiScene::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mutiTouchlistener, this);
_eventDispatcher->setPriority(mutiTouchlistener, 1);
//注册帧事件
this->scheduleUpdate();
//初始化
m_p1NextMType = Real_100_S;
m_p1CurMType = Real_100_S;
m_p1NeedRand = true;
_touchP1ID = -1;
m_p2NextMType = Real_100_S;
m_p2CurMType = Real_100_S;
m_p2NeedRand = true;
_touchP2ID = -1;
initProArr();
initStatus();
m_stageCount = 0;
if (MCManual::novice[3])
{
manualAct1();
}
return true;
}
void MultiScene::setBgImage()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//bg
auto bgSprite = Sprite::create("multi/multi_bg.png");
bgSprite->setPosition(ccp(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
this->addChild(bgSprite, 0);
}
void MultiScene::onTouchesBegan(const std::vector<Touch*>& touches, Event* event)
{
if (MCManual::novice[3] && m_stageCount == 0)
return;
for (auto &item : touches)
{
auto touch = item;
auto location = touch->getLocation();
if (_touchP1ID != -1 && _touchP2ID != -1)
break;
if (_touchP1ID == -1 && m_player1->MoneyTotal()->isOnMoney(location))
{
_sP1Pos = location;
_curP1Pos = _sP1Pos;
_touchP1ID = touch->getID();
m_effect_id1 = AudioControl::playCountEffect();
if (m_p1NeedRand)
{
m_player1->addSingleMoneyMLabel(m_p1CurMType, "center", Vec2(5, -110));
m_player1->MoneySingle()->MoneySprite()->setScale(0.5);
randNewSingleMoney(1);
}
}
if (_touchP2ID == -1 && m_player2->MoneyTotal()->isOnMoney(location))
{
if (MCManual::novice[3])
{
return;
}
_sP2Pos = location;
_curP2Pos = _sP2Pos;
_touchP2ID = touch->getID();
m_effect_id2 = AudioControl::playCountEffect();
if (m_p2NeedRand)
{
m_player2->addSingleMoneyMLabel(m_p2CurMType, "center", Vec2(-5, 693));
m_player2->MoneySingle()->MoneySprite()->setRotation(270);
m_player2->MoneySingle()->MoneySprite()->setScale(0.5);
randNewSingleMoney(2);
}
}
}
}
void MultiScene::onTouchesEnded(const std::vector<Touch*>& touches, Event* event)
{
if (_touchP1ID == -1 && _touchP2ID == -1)
return;
for (auto &item : touches)
{
auto touch = item;
auto location = touch->getLocation();
if (touch->getID() == _touchP1ID) //right player
{
switch (MCUtil::direction(_sP1Pos, location))
{
case UP:
if (MCManual::novice[3] && m_stageCount > 6)
{
returnPos(location, 1);
m_p1NeedRand = false;
}
else
{
if (m_p1Status[2] && std::abs(_sP1Pos.y - location.y) < WeightDis) //加重状态
{
returnPos(location, 1);
m_p1NeedRand = false;
}
else
{
if (m_p1Status[1])
{
giveOpponent(UP, location, 1);
}
else
{
giveMyself(UP, location, 1);
}
m_player1->removeChildByName("up");
m_player1->MoneySingle()->setName("up");
if (MCManual::novice[3] && m_stageCount == 1)
{
m_stageCount = 0;
manualAct2();
}
else if (MCManual::novice[3] && m_stageCount == 2)
{
m_stageCount = 0;
manualAct3();
}
else if (MCManual::novice[3] && m_stageCount == 5)
{
m_stageCount = 0;
manualAct4();
}
else
{
m_stageCount++;
}
m_p1NeedRand = true;
}
}
break;
case RIGHT:
if (MCManual::novice[3] && m_stageCount < 6)
{
returnPos(location, 1);
m_p1NeedRand = false;
}
else
{
if (m_p1Status[2] && std::abs(_sP1Pos.x - location.x) < WeightDis) //加重状态
{
returnPos(location, 1);
m_p1NeedRand = false;
}
else
{
if (m_p1Status[1])
{
giveMyself(RIGHT, location, 1);
}
else
{
giveOpponent(RIGHT, location, 1);
}
m_player1->removeChildByName("right");
m_player1->MoneySingle()->setName("right");
if (MCManual::novice[3] && m_stageCount == 7)
{
m_stageCount = 0;
manualAct5();
}
m_p1NeedRand = true;
}
}
break;
default:
returnPos(location, 1);
m_p1NeedRand = false;
break;
}
_touchP1ID = -1;
if (m_p1NeedRand)
m_p1CurMType = m_p1NextMType;
//AudioControl::stopEffectMusic(m_effect_id1);
m_player1->changeTotalMoneyLabel();
changeCurScore(1);
}
if (touch->getID() == _touchP2ID) //left player
{
switch (MCUtil::direction(_sP2Pos, location))
{
case DOWN:
if (m_p2Status[2] && std::abs(_sP2Pos.y - location.y) < WeightDis) //加重状态
{
returnPos(location, 2);
m_p2NeedRand = false;
}
else
{
if (m_p2Status[1])
{
giveOpponent(DOWN, location, 2);
}
else
{
giveMyself(DOWN, location, 2);
}
m_player2->removeChildByName("down");
m_player2->MoneySingle()->setName("down");
m_p2NeedRand = true;
}
break;
case LEFT:
if (m_p2Status[2] && std::abs(_sP2Pos.x - location.x) < WeightDis) //加重状态
{
returnPos(location, 2);
m_p2NeedRand = false;
}
else
{
if (m_p2Status[1])
{
giveMyself(LEFT, location, 2);
}
else
{
giveOpponent(LEFT, location, 2);
}
m_player2->removeChildByName("left");
m_player2->MoneySingle()->setName("left");
m_p2NeedRand = true;
}
break;
default:
returnPos(location, 2);
m_p2NeedRand = false;
break;
}
_touchP2ID = -1;
if (m_p2NeedRand)
m_p2CurMType = m_p2NextMType;
//AudioControl::stopEffectMusic(m_effect_id2);
m_player2->changeTotalMoneyLabel();
changeCurScore(2);
if (m_p2Status[5])
{
m_player2->MoneyTotal()->changeMoney(Real_100_T);
m_p2CurMType = Real_100_S;
}
}
//AudioControl::stopMCEffects();
}
}
void MultiScene::onTouchesMoved(const std::vector<Touch*>& touches, Event* event)
{
for (auto &item : touches)
{
auto touch = item;
auto location = touch->getLocation();
if (touch->getID() == _touchP1ID)
{
if (location.y <= _sP1Pos.y)
location.y = _sP1Pos.y;
if (location.y >= 512)
location.y = 512;
m_player1->MoneySingle()->MoneySprite()->setPosition(m_player1->MoneySingle()->MoneySprite()->getPositionX(),
m_player1->MoneySingle()->MoneySprite()->getPositionY() + (location.y - _curP1Pos.y)*0.5);
_curP1Pos = location;
}
if (touch->getID() == _touchP2ID)
{
if (location.y >= _sP2Pos.y)
location.y = _sP2Pos.y;
if (location.y <= 512)
location.y = 512;
m_player2->MoneySingle()->MoneySprite()->setPosition(m_player2->MoneySingle()->MoneySprite()->getPositionX(),
m_player2->MoneySingle()->MoneySprite()->getPositionY() + (location.y - _curP2Pos.y)*0.5);
_curP2Pos = location;
}
}
}
void MultiScene::addTargetNumLabel(int whichPlayer, const char* str)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto label = Label::createWithTTF(str, "fonts/DTLNobelT-Bold.otf", 35);
auto sprite = Sprite::create("multi/multi_target.png");
if (whichPlayer == 1)
{
label->setPosition(origin.x + visibleSize.width / 2 - 120, origin.y + visibleSize.height / 2 - 40);
sprite->setPosition(origin.x + visibleSize.width / 2 - 235, origin.y + visibleSize.height / 2 - 40);
}
else
{
label->setPosition(origin.x + visibleSize.width / 2 + 120, origin.y + visibleSize.height / 2 + 40);
label->setRotation(180);
sprite->setPosition(origin.x + visibleSize.width / 2 + 235, origin.y + visibleSize.height / 2 + 40);
sprite->setRotation(180);
}
label->setColor(MCUtil::m_targetColor);
this->addChild(sprite, 1);
this->addChild(label, 1);
}
void MultiScene::addCurScore()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
char scoreStr1[10], scoreStr2[10];
sprintf(scoreStr1, "%d", m_player1->totalMoneyNum());
sprintf(scoreStr2, "%d", m_player2->totalMoneyNum());
m_p1Label1 = Label::createWithTTF(scoreStr1, "fonts/DTLNobelT-Bold.otf", 30);
m_p1Label2 = Label::createWithTTF(scoreStr2, "fonts/DTLNobelT-Bold.otf", 30);
m_p1Label1->setPosition(origin.x + visibleSize.width / 2 + 190, origin.y + visibleSize.height / 2 - 40);
m_p1Label2->setPosition(origin.x + visibleSize.width / 2 + 280, origin.y + visibleSize.height / 2 - 40);
m_p2Label1 = Label::createWithTTF(scoreStr1, "fonts/DTLNobelT-Bold.otf", 30);
m_p2Label2 = Label::createWithTTF(scoreStr2, "fonts/DTLNobelT-Bold.otf", 30);
m_p2Label1->setRotation(180);
m_p2Label2->setRotation(180);
m_p2Label1->setPosition(origin.x + visibleSize.width / 2 - 280, origin.y + visibleSize.height / 2 + 40);
m_p2Label2->setPosition(origin.x + visibleSize.width / 2 - 190, origin.y + visibleSize.height / 2 + 40);
m_p1Label1->setColor(Color3B(255, 255, 255));
m_p1Label2->setColor(Color3B(255, 255, 255));
m_p2Label1->setColor(Color3B(255, 255, 255));
m_p2Label2->setColor(Color3B(255, 255, 255));
Label *m_label3 = Label::createWithTTF(":", "fonts/DTLNobelT-Bold.otf", 40);
m_label3->setPosition(origin.x + visibleSize.width / 2 + 235, origin.y + visibleSize.height / 2 - 40);
Label *m_label4 = Label::createWithTTF(":", "fonts/DTLNobelT-Bold.otf", 40);
m_label4->setPosition(origin.x + visibleSize.width / 2 - 235, origin.y + visibleSize.height / 2 + 40);
m_label3->setColor(Color3B(255, 255, 255));
m_label4->setColor(Color3B(255, 255, 255));
this->addChild(m_p1Label1, 1);
this->addChild(m_p1Label2, 1);
this->addChild(m_p2Label1, 1);
this->addChild(m_p2Label2, 1);
this->addChild(m_label3, 2);
this->addChild(m_label4, 2);
}
void MultiScene::changeCurScore(int whichPlayer)
{
char scoreStr[10];
if (whichPlayer == 1)
{
sprintf(scoreStr, "%d", m_player1->totalMoneyNum());
m_p1Label1->setString(scoreStr);
m_p2Label1->setString(scoreStr);
}
else
{
sprintf(scoreStr, "%d", m_player2->totalMoneyNum());
m_p1Label2->setString(scoreStr);
m_p2Label2->setString(scoreStr);
}
}
void MultiScene::update(float dt)
{
if (m_player1->totalMoneyNum() == m_targetNum && m_player2->totalMoneyNum() == m_targetNum)
{
auto scene = MultiEndScene::createScene("0");
Director::sharedDirector()->pushScene(scene);
this->unscheduleUpdate();
}
if (m_player1->totalMoneyNum() >= m_targetNum)
{
auto scene = MultiEndScene::createScene("1");
Director::sharedDirector()->pushScene(scene);
this->unscheduleUpdate();
}
if (m_player2->totalMoneyNum() >= m_targetNum)
{
auto scene = MultiEndScene::createScene("-1");
Director::sharedDirector()->pushScene(scene);
this->unscheduleUpdate();
}
}
void MultiScene::returnCallback(cocos2d::Ref* pSender)
{
AudioControl::stopBGMusic();
auto scene = StartScene::createScene();
Director::getInstance()->replaceScene(CCTransitionZoomFlipX::create(0.5, scene, TransitionScene::Orientation::LEFT_OVER));
}
void MultiScene::pauseCallback(cocos2d::Ref* pSender)
{
/*Size visibleSize = Director::getInstance()->getVisibleSize();
RenderTexture *renderTexture = RenderTexture::create(visibleSize.width, visibleSize.height + 30);
renderTexture->begin();
this->getParent()->visit();
renderTexture->end();
auto scene = MultiPauseScene::createScene(renderTexture, m_player1->totalMoneyNum(), m_player2->totalMoneyNum());
Director::sharedDirector()->pushScene(scene);
AudioControl::stopBGMusic();*/
}
void MultiScene::addControlBtns(int whichPlayer)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto returnItem = MenuItemImage::create(
"multi/icon_back.png",
"multi/icon_back.png",
CC_CALLBACK_1(MultiScene::returnCallback, this));
/*auto pauseItem = MenuItemImage::create(
"multi/icon_pause.png",
"multi/icon_pause.png",
CC_CALLBACK_1(MultiScene::pauseCallback, this));*/
if (whichPlayer == 1)
{
returnItem->setPosition(origin.x + 60, origin.y + visibleSize.height / 2 - 60);
//pauseItem->setPosition(origin.x + visibleSize.width - 60, origin.y + visibleSize.height / 2 - 60);
}
else
{
returnItem->setPosition(origin.x + visibleSize.width - 60, origin.y + visibleSize.height / 2 + 60);
returnItem->setRotation(180);
//pauseItem->setPosition(origin.x + 60, origin.y + visibleSize.height / 2 + 60);
}
// create menu, it's an autorelease object
//auto menu = Menu::create(returnItem, pauseItem, NULL);
auto menu = Menu::create(returnItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
}
void MultiScene::addGateWay()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//gateway 1
m_gateWay1 = Sprite::create("multi/gateway.png");
m_gateWay1->setScale(1);
m_gateWay1->setRotation(0);
m_gateWay1->setPosition(Vec2(origin.x + visibleSize.width - 90, origin.y + visibleSize.height / 2 - 350));
this->addChild(m_gateWay1, 1);
//gateway 2
m_gateWay2 = Sprite::create("multi/gateway.png");
m_gateWay2->setScale(1);
m_gateWay2->setRotation(180);
m_gateWay2->setPosition(Vec2(origin.x + 90, origin.y + visibleSize.height - 150));
this->addChild(m_gateWay2, 1);
}
void MultiScene::addWallet()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//wallet 1
m_wallet1 = Sprite::create("multi/person.png");
m_wallet1->setScale(1);
m_wallet1->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 100));
this->addChild(m_wallet1, 0);
Sprite *m_icon1 = Sprite::create("multi/person_icon.png");
m_icon1->setPosition(Vec2(origin.x + visibleSize.width / 2 + 120, origin.y + visibleSize.height / 2 - 40));
this->addChild(m_icon1, 1);
Sprite *m_icon2 = Sprite::create("multi/duck_icon.png");
m_icon2->setPosition(Vec2(origin.x + visibleSize.width / 2 + 350, origin.y + visibleSize.height / 2 - 40));
this->addChild(m_icon2, 1);
//wallet 2
m_wallet2 = Sprite::create("multi/duck.png");
m_wallet2->setScale(1);
m_wallet2->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 + 90));
this->addChild(m_wallet2, 0);
Sprite *m_icon3 = Sprite::create("multi/duck_icon.png");
m_icon3->setPosition(Vec2(origin.x + visibleSize.width / 2 - 120, origin.y + visibleSize.height / 2 + 40));
m_icon3->setRotation(180);
this->addChild(m_icon3, 1);
Sprite *m_icon4 = Sprite::create("multi/person_icon.png");
m_icon4->setPosition(Vec2(origin.x + visibleSize.width / 2 - 350, origin.y + visibleSize.height / 2 + 40));
m_icon4->setRotation(180);
this->addChild(m_icon4, 1);
}
void MultiScene::randNewSingleMoney(int whichPlayer)
{
Player* tmpPlayer = m_player1;
Money_Type nextMType;
if (whichPlayer == 2)
{
tmpPlayer = m_player2;
}
int x = rand() % 100;
if (MCManual::novice[3])
{
if (m_stageCount == 1)
{
x = m_pro[4]; // 财神
}
else if (m_stageCount < 5 && m_stageCount > 1)
{
x = 99;
}
else if (m_stageCount == 5)
{
x = m_pro[1]; // 换位
}
}
if (x <= m_pro[0])
{
tmpPlayer->MoneyTotal()->changeMoney(Tool_1_T);
nextMType = Tool_1_S;
}
else if (x <= m_pro[1])
{
tmpPlayer->MoneyTotal()->changeMoney(Tool_2_T);
nextMType = Tool_2_S;
}
else if (x <= m_pro[2])
{
tmpPlayer->MoneyTotal()->changeMoney(Tool_3_T);
nextMType = Tool_3_S;
}
else if (x <= m_pro[3])
{
tmpPlayer->MoneyTotal()->changeMoney(Tool_4_T);
nextMType = Tool_4_S;
}
else if (x <= m_pro[4])
{
tmpPlayer->MoneyTotal()->changeMoney(Tool_5_T);
nextMType = Tool_5_S;
}
else if (x <= m_pro[5])
{
tmpPlayer->MoneyTotal()->changeMoney(Tool_6_T);
nextMType = Tool_6_S;
}
else if (x <= m_pro[6])
{
tmpPlayer->MoneyTotal()->changeMoney(Fake_100_T);
nextMType = Fake_100_S;
}
else
{
tmpPlayer->MoneyTotal()->changeMoney(Real_100_T);
nextMType = Real_100_S;
}
if (whichPlayer == 1)
{
m_p1NextMType = nextMType;
}
else
{
m_p2NextMType = nextMType;
}
}
void MultiScene::initProArr()
{
m_pro[0] = 3; //迷雾
m_pro[1] = 5; //换位
m_pro[2] = 8; //加重
m_pro[3] = 19; //穷神
m_pro[4] = 21; //双倍
m_pro[5] = 23; //免疫
m_pro[6] = 23; //假钱
}
void MultiScene::giveOpponent(MCDirection direction, Vec2 location, int whichPlayer)
{
Player* tmpPlayer = m_player1;
Vec2 spos = _sP1Pos;
Money_Type curType = m_p1CurMType;
bool isInvincible = m_p2Status[5];
if (whichPlayer == 2)
{
tmpPlayer = m_player2;
spos = _sP2Pos;
curType = m_p2CurMType;
isInvincible = m_p1Status[5];
}
if (curType == Real_100_S || curType == Tool_5_S || curType == Tool_6_S || ((curType == Tool_2_S) && m_p1Status[1]))
{
if (whichPlayer == 1)
m_p1GoodCount = 0;
if (whichPlayer == 2)
m_p2GoodCount = 0;
}
if (curType == Tool_1_S || curType == Tool_3_S || curType == Tool_4_S || ((curType == Tool_2_S) && !m_p1Status[1]))
{
if (whichPlayer == 1)
m_p1GoodCount++;
if (whichPlayer == 2)
m_p2GoodCount++;
encourageEffect(whichPlayer);
}
triggerFlash(whichPlayer);
switch (direction)
{
case UP:
//防止玩家1,也即向上划钱到界面另一半,其实玩家2是不会有up操作的
if (location.y >= 512)
location.y = 512;
//飘钱效果
tmpPlayer->MoneySingle()->moneyFakeFly(0.0, 250.0 - (location.y - spos.y)*0.5, 0.1);
break;
case DOWN:
//防止玩家2,也即向上划钱到界面另一半,其实玩家1是不会有down操作的
if (location.y <= 512)
location.y = 512;
tmpPlayer->MoneySingle()->moneyFakeFly(0.0, -250.0 - (location.y - spos.y)*0.5, 0.1);
break;
case LEFT:
tmpPlayer->MoneySingle()->moneyHFakeFly(-270.0, 0.0, 0.1);
break;
case RIGHT:
tmpPlayer->MoneySingle()->moneyHFakeFly(270.0, 0.0, 0.1);
break;
default:
break;
}
switch (curType)
{
case Real_100_S:
break;
case Fake_100_S:
break;
case Tool_1_S:
if (!isInvincible)
{
AudioControl::playTool1Effect();
halfSmoke(whichPlayer % 2 + 1);
}
break;
case Tool_2_S:
if (!isInvincible)
{
AudioControl::playTool2Effect();
changePos(whichPlayer % 2 + 1);
}
break;
case Tool_3_S:
if (!isInvincible)
{
AudioControl::playTool3Effect();
increaseWeight(whichPlayer % 2 + 1);
}
break;
case Tool_4_S:
if (!isInvincible)
{
AudioControl::playTool4Effect();
triggerPoor(whichPlayer % 2 + 1, PoorOtherNum);
}
break;
case Tool_5_S:
AudioControl::playTool5Effect();
triggerRich(whichPlayer % 2 + 1);
break;
case Tool_6_S:
AudioControl::playTool6Effect();
triggerInvincible(whichPlayer % 2 + 1);
break;
default:
break;
}
}
void MultiScene::triggerFlash(int whichPlayer)
{
if (whichPlayer == 1)
{
m_gateWay1->setTexture("multi/gateway_light.png");
ActionInterval* delaytime = DelayTime::create(0.2f);
CallFunc * funcall = CallFunc::create([&](){
m_gateWay1->setTexture("multi/gateway.png");
});
FiniteTimeAction * seq = Sequence::create(delaytime, funcall, NULL);
m_gateWay1->runAction(seq);
}
if (whichPlayer == 2)
{
m_gateWay2->setTexture("multi/gateway_light.png");
ActionInterval* delaytime = DelayTime::create(0.2f);
CallFunc * funcall = CallFunc::create([&](){
m_gateWay2->setTexture("multi/gateway.png");
});
FiniteTimeAction * seq = Sequence::create(delaytime, funcall, NULL);
m_gateWay2->runAction(seq);
}
}
void MultiScene::throwTrashCan(MCDirection direction, Vec2 location, int whichPlayer)
{
Player* tmpPlayer = m_player1;
Vec2 spos = _sP1Pos;
if (whichPlayer == 2)
{
tmpPlayer = m_player2;
spos = _sP2Pos;
}
switch (direction)
{
case UP:
//防止玩家1,也即向上划钱到界面另一半,其实玩家2是不会有up操作的
if (location.y >= 512)
location.y = 512;
//飘钱效果
tmpPlayer->MoneySingle()->moneyFakeFly(0.0, 200.0 - (location.y - spos.y)*0.5, 0.1);
break;
case DOWN:
//防止玩家2,也即向上划钱到界面另一半,其实玩家1是不会有down操作的
if (location.y <= 512)
location.y = 512;
tmpPlayer->MoneySingle()->moneyFakeFly(0.0, -200.0 - (location.y - spos.y)*0.5, 0.1);
break;
case LEFT:
tmpPlayer->MoneySingle()->moneyFakeFly(-110.0, 0.0, 0.1);
break;
case RIGHT:
tmpPlayer->MoneySingle()->moneyFakeFly(110.0, 0.0, 0.1);
break;
default:
break;
}
}
void MultiScene::giveMyself(MCDirection direction, Vec2 location, int whichPlayer)
{
Player* tmpPlayer = m_player1;
Vec2 spos = _sP1Pos;
Money_Type curType = m_p1CurMType;
bool isDouble = m_p1Status[4];
bool isInvincible = m_p1Status[5];
if (whichPlayer == 2)
{
tmpPlayer = m_player2;
spos = _sP2Pos;
curType = m_p2CurMType;
isDouble = m_p2Status[4];
isInvincible = m_p2Status[5];
}
if (curType == Real_100_S || curType == Tool_5_S || curType == Tool_6_S || ((curType == Tool_2_S) && m_p1Status[1]))
{
if (whichPlayer == 1)
m_p1GoodCount++;
if (whichPlayer == 2)
m_p2GoodCount++;
encourageEffect(whichPlayer);
}
if (curType == Tool_1_S || curType == Tool_3_S || curType == Tool_4_S || ((curType == Tool_2_S) && !m_p1Status[1]))
{
if (whichPlayer == 1)
m_p1GoodCount = 0;
if (whichPlayer == 2)
m_p2GoodCount = 0;
}
switch (direction)
{
case UP:
//防止玩家1,也即向上划钱到界面另一半,其实玩家2是不会有up操作的
if (location.y >= 512)
location.y = 512;
//飘钱效果
tmpPlayer->MoneySingle()->moneyFakeFly(0.0, 250.0 - (location.y - spos.y)*0.5, 0.1);
break;
case DOWN:
//防止玩家2,也即向上划钱到界面另一半,其实玩家1是不会有down操作的
if (location.y <= 512)
location.y = 512;
tmpPlayer->MoneySingle()->moneyFakeFly(0.0, -250.0 - (location.y - spos.y)*0.5, 0.1);
break;
case LEFT:
tmpPlayer->MoneySingle()->moneyHFakeFly(-270.0, 0.0, 0.1);
break;
case RIGHT:
tmpPlayer->MoneySingle()->moneyHFakeFly(270.0, 0.0, 0.1);
break;
default:
break;
}
switch (curType)
{
case Real_100_S:
if (isDouble)
{
m_flyWord[whichPlayer - 1][1]->Flying();
tmpPlayer->addTotalMoney(200);
}
else
{
m_flyWord[whichPlayer - 1][0]->Flying();
tmpPlayer->addTotalMoney(100);
}
break;
case Fake_100_S:
if (!isInvincible)
{
tmpPlayer->addFakeWrong(1);
tmpPlayer->addTotalMoney(-200);
}
break;
case Tool_1_S:
if (!isInvincible)
{
AudioControl::playTool1Effect();
halfSmoke(whichPlayer);
}
break;
case Tool_2_S:
if (!isInvincible)
{
AudioControl::playTool2Effect();
changePos(whichPlayer);
}
break;
case Tool_3_S:
if (!isInvincible)
{
AudioControl::playTool3Effect();
increaseWeight(whichPlayer);
}
break;
case Tool_4_S:
if (!isInvincible)
{
AudioControl::playTool4Effect();
triggerPoor(whichPlayer, PoorMeNum);
}
break;
case Tool_5_S:
AudioControl::playTool5Effect();
triggerRich(whichPlayer);
break;
case Tool_6_S:
AudioControl::playTool6Effect();
triggerInvincible(whichPlayer);
break;
default:
break;
}
}
void MultiScene::returnPos(Vec2 location, int whichPlayer)
{
if (whichPlayer == 1 && location.y - _sP1Pos.y > 0)
{
m_player1->MoneySingle()->MoneySprite()->setPositionY(m_player1->MoneySingle()->MoneySprite()->getPositionY() - (location.y - _sP1Pos.y)*0.5);
}
if (whichPlayer == 2 && location.y - _sP2Pos.y < 0)
{
m_player2->MoneySingle()->MoneySprite()->setPositionY(m_player2->MoneySingle()->MoneySprite()->getPositionY() - (location.y - _sP2Pos.y)*0.5);
}
}
void MultiScene::halfSmoke(int whichHalf)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
//添加效果
smokeEffect(whichHalf);
if (whichHalf == 1 && !m_p1Status[0])
{
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP1[i])
{
m_p1Occupied[0] = i;
m_occupiedP1[i] = true;
break;
}
}
auto sprite1 = Sprite::create(m_status_file[0]);
sprite1->setPosition(m_p1StatusPos[m_p1Occupied[0]]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1, "tool1_1");
m_p1Status[0] = true;
scheduleOnce(schedule_selector(MultiScene::updateSmoke1), 3.0f);
}
if (whichHalf == 2 && !m_p2Status[0])
{
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP2[i])
{
m_p2Occupied[0] = i;
m_occupiedP2[i] = true;
break;
}
}
auto sprite2 = Sprite::create(m_status_file[0]);
sprite2->setPosition(m_p2StatusPos[m_p2Occupied[0]]);
sprite2->setRotation(180);
sprite2->setScale(0.3);
this->addChild(sprite2, 1, "tool1_2");
m_p2Status[0] = true;
scheduleOnce(schedule_selector(MultiScene::updateSmoke2), 3.0f);
}
}
void MultiScene::updateSmoke1(float time)
{
this->removeChildByName("tool1_1");
m_p1Status[0] = false;
m_occupiedP1[m_p1Occupied[0]] = false;
m_p1Occupied[0] = -1;
}
void MultiScene::updateSmoke2(float time)
{
this->removeChildByName("tool1_2");
m_p2Status[0] = false;
m_occupiedP2[m_p2Occupied[0]] = false;
m_p2Occupied[0] = -1;
}
void MultiScene::changePos(int whichHalf)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
if (whichHalf == 1)
{
if (m_p1Status[1])
{
//去除状态
this->removeChildByName("tool2_1");
m_occupiedP1[m_p1Occupied[1]] = false;
m_p1Occupied[1] = -1;
}
else
{
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP1[i])
{
m_p1Occupied[1] = i;
m_occupiedP1[i] = true;
break;
}
}
auto sprite1 = Sprite::create(m_status_file[1]);
sprite1->setPosition(m_p1StatusPos[m_p1Occupied[1]]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1, "tool2_1");
}
m_p1Status[1] = !m_p1Status[1];
if (m_p1Status[1])
{
m_gateWay1->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 110));
m_wallet1->setPosition(Vec2(origin.x + visibleSize.width - 120, origin.y + visibleSize.height / 2 - 350));
}
else
{
m_gateWay1->setPosition(Vec2(origin.x + visibleSize.width - 90, origin.y + visibleSize.height / 2 - 350));
m_wallet1->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 100));
}
CCActionInterval * gateWayBlink = CCBlink::create(1, 2);
CCActionInterval * walletBlink = CCBlink::create(1, 2);
m_gateWay1->runAction(gateWayBlink);
m_wallet1->runAction(walletBlink);
}
else
{
if (m_p2Status[1])
{
//去除状态
this->removeChildByName("tool2_2");
m_occupiedP2[m_p2Occupied[1]] = false;
m_p2Occupied[1] = -1;
}
else
{
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP2[i])
{
m_p2Occupied[1] = i;
m_occupiedP2[i] = true;
break;
}
}
auto sprite2 = Sprite::create(m_status_file[1]);
sprite2->setPosition(m_p2StatusPos[m_p2Occupied[1]]);
sprite2->setScale(0.3);
this->addChild(sprite2, 1, "tool2_2");
}
m_p2Status[1] = !m_p2Status[1];
if (m_p2Status[1])
{
m_gateWay2->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 + 120));
m_gateWay2->setRotation(180);
m_wallet2->setPosition(Vec2(origin.x + 120, origin.y + visibleSize.height - 150));
}
else
{
m_gateWay2->setPosition(Vec2(origin.x + 90, origin.y + visibleSize.height - 150));
m_gateWay2->setRotation(180);
m_wallet2->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 + 90));
}
CCActionInterval * gateWayBlink = CCBlink::create(1, 2);
CCActionInterval * walletBlink = CCBlink::create(1, 2);
m_gateWay2->runAction(gateWayBlink);
m_wallet2->runAction(walletBlink);
}
}
void MultiScene::increaseWeight(int whichHalf)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
if (whichHalf == 1 && !m_p1Status[2])
{
//添加效果
CCSprite * sp = CCSprite::create("multi/weight_effect.png");
Vec2 pos = Vec2(origin.x + visibleSize.width / 2 + 20, origin.y + sp->getContentSize().height / 2 - 10);
sp->setPosition(pos);
sp->setRotation(90);
sp->setScale(0.8);
this->addChild(sp, 2, "weighteffect1");
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP1[i])
{
m_p1Occupied[2] = i;
m_occupiedP1[i] = true;
break;
}
}
auto sprite1 = Sprite::create(m_status_file[2]);
sprite1->setPosition(m_p1StatusPos[m_p1Occupied[2]]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1, "tool3_1");
m_p1Status[2] = true;
scheduleOnce(schedule_selector(MultiScene::updateWeight1), 3.0f);
}
if (whichHalf == 2 && !m_p2Status[2])
{
//添加效果
CCSprite * sp = CCSprite::create("multi/weight_effect.png");
Vec2 pos = Vec2(origin.x + visibleSize.width / 2 - 20, origin.y + visibleSize.height - sp->getContentSize().height / 2 + 10);
sp->setPosition(pos);
sp->setRotation(270);
sp->setScale(0.8);
this->addChild(sp, 2, "weighteffect2");
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP2[i])
{
m_p2Occupied[2] = i;
m_occupiedP2[i] = true;
break;
}
}
auto sprite2 = Sprite::create(m_status_file[2]);
sprite2->setPosition(m_p2StatusPos[m_p2Occupied[2]]);
sprite2->setRotation(180);
sprite2->setScale(0.3);
this->addChild(sprite2, 1, "tool3_2");
m_p2Status[2] = true;
scheduleOnce(schedule_selector(MultiScene::updateWeight2), 3.0f);
}
}
void MultiScene::updateWeight1(float time)
{
this->removeChildByName("weighteffect1");
this->removeChildByName("tool3_1");
m_p1Status[2] = false;
m_occupiedP1[m_p1Occupied[2]] = false;
m_p1Occupied[2] = -1;
}
void MultiScene::updateWeight2(float time)
{
this->removeChildByName("weighteffect2");
this->removeChildByName("tool3_2");
m_p2Status[2] = false;
m_occupiedP2[m_p2Occupied[2]] = false;
m_p2Occupied[2] = -1;
}
void MultiScene::triggerPoor(int whichHalf, int minusScore)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
if (whichHalf == 1 && !m_p1Status[3])
{
//添加效果
poorAnimation(1);
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP1[i])
{
m_p1Occupied[3] = i;
m_occupiedP1[i] = true;
break;
}
}
auto sprite1 = Sprite::create(m_status_file[3]);
sprite1->setPosition(m_p1StatusPos[m_p1Occupied[3]]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1, "tool4_1");
m_p1Status[3] = true;
if (minusScore == -300)
m_flyWord[0][2]->Flying();
else if (minusScore == -500)
m_flyWord[0][3]->Flying();
m_player1->addTotalMoney(minusScore);
m_player1->changeTotalMoneyLabel();
changeCurScore(1);
scheduleOnce(schedule_selector(MultiScene::updatePoor1), 1.0f);
}
if (whichHalf == 2 && !m_p2Status[3])
{
//添加效果
poorAnimation(2);
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP2[i])
{
m_p2Occupied[3] = i;
m_occupiedP2[i] = true;
break;
}
}
auto sprite2 = Sprite::create(m_status_file[3]);
sprite2->setPosition(m_p2StatusPos[m_p2Occupied[3]]);
sprite2->setRotation(180);
sprite2->setScale(0.3);
this->addChild(sprite2, 1, "tool4_2");
m_p2Status[3] = true;
if (minusScore == -300)
m_flyWord[1][2]->Flying();
else if (minusScore == -500)
m_flyWord[1][3]->Flying();
m_player2->addTotalMoney(minusScore);
m_player2->changeTotalMoneyLabel();
changeCurScore(2);
scheduleOnce(schedule_selector(MultiScene::updatePoor2), 1.0f);
}
}
void MultiScene::updatePoor1(float time)
{
this->removeChildByName("tool4_1");
m_p1Status[3] = false;
m_occupiedP1[m_p1Occupied[3]] = false;
m_p1Occupied[3] = -1;
}
void MultiScene::updatePoor2(float time)
{
this->removeChildByName("tool4_2");
m_p2Status[3] = false;
m_occupiedP2[m_p2Occupied[3]] = false;
m_p2Occupied[3] = -1;
}
void MultiScene::triggerRich(int whichHalf)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
if (whichHalf == 1 && !m_p1Status[4])
{
//添加效果
richAnimation(1);
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP1[i])
{
m_p1Occupied[4] = i;
m_occupiedP1[i] = true;
break;
}
}
auto sprite1 = Sprite::create(m_status_file[4]);
sprite1->setPosition(m_p1StatusPos[m_p1Occupied[4]]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1, "tool5_1");
m_p1Status[4] = true;
scheduleOnce(schedule_selector(MultiScene::updateRich1), 4.0f);
}
if (whichHalf == 2 && !m_p2Status[4])
{
//添加效果
richAnimation(2);
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP2[i])
{
m_p2Occupied[4] = i;
m_occupiedP2[i] = true;
break;
}
}
auto sprite2 = Sprite::create(m_status_file[4]);
sprite2->setPosition(m_p2StatusPos[m_p2Occupied[4]]);
sprite2->setRotation(180);
sprite2->setScale(0.3);
this->addChild(sprite2, 1, "tool5_2");
m_p2Status[4] = true;
scheduleOnce(schedule_selector(MultiScene::updateRich2), 4.0f);
}
}
void MultiScene::updateRich1(float time)
{
this->removeChildByName("tool5_1");
m_p1Status[4] = false;
m_occupiedP1[m_p1Occupied[4]] = false;
m_p1Occupied[4] = -1;
}
void MultiScene::updateRich2(float time)
{
this->removeChildByName("tool5_2");
m_p2Status[4] = false;
m_occupiedP2[m_p2Occupied[4]] = false;
m_p2Occupied[4] = -1;
}
void MultiScene::triggerInvincible(int whichHalf)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
if (whichHalf == 1 && !m_p1Status[5])
{
//添加效果
invincibleAnimation(1);
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP1[i])
{
m_p1Occupied[5] = i;
m_occupiedP1[i] = true;
break;
}
}
auto sprite1 = Sprite::create(m_status_file[5]);
sprite1->setPosition(m_p1StatusPos[m_p1Occupied[5]]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1, "tool6_1");
m_p1Status[5] = true;
scheduleOnce(schedule_selector(MultiScene::updateInvincible1), 4.0f);
}
if (whichHalf == 2 && !m_p2Status[5])
{
//添加效果
invincibleAnimation(2);
//添加状态
for (int i = 0; i < 6; i++)
{
if (!m_occupiedP2[i])
{
m_p2Occupied[5] = i;
m_occupiedP2[i] = true;
break;
}
}
auto sprite2 = Sprite::create(m_status_file[5]);
sprite2->setPosition(m_p2StatusPos[m_p2Occupied[5]]);
sprite2->setRotation(180);
sprite2->setScale(0.3);
this->addChild(sprite2, 1, "tool6_2");
m_p2Status[5] = true;
scheduleOnce(schedule_selector(MultiScene::updateInvincible2), 4.0f);
}
}
void MultiScene::updateInvincible1(float time)
{
this->removeChildByName("tool6_1");
m_p1Status[5] = false;
m_occupiedP1[m_p1Occupied[5]] = false;
m_p1Occupied[5] = -1;
}
void MultiScene::updateInvincible2(float time)
{
this->removeChildByName("tool6_2");
m_p2Status[5] = false;
m_occupiedP2[m_p2Occupied[5]] = false;
m_p2Occupied[5] = -1;
}
void MultiScene::initStatus()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
for (int i = 0; i < 6; ++i)
{
m_p1Status[i] = false;
m_p2Status[i] = false;
m_p1Occupied[i] = -1;
m_p2Occupied[i] = -1;
m_occupiedP1[i] = false;
m_occupiedP2[i] = false;
m_p1StatusPos[i] = Vec2(origin.x + 80 + (i % 2) * 70, origin.y + visibleSize.height / 2 - 250 - (i / 2) * 70);
m_p2StatusPos[i] = Vec2(origin.x + +visibleSize.width - 80 - (i % 2) * 70, origin.y + visibleSize.height / 2 + 250 + (i / 2) * 70);
}
m_status_file[0] = "multi/tool1.png";
m_status_file[1] = "multi/tool2.png";
m_status_file[2] = "multi/tool3.png";
m_status_file[3] = "multi/tool4.png";
m_status_file[4] = "multi/tool5.png";
m_status_file[5] = "multi/tool6.png";
/*for (int i = 0; i < 6; ++i)
{
auto sprite1 = Sprite::create("multi/tool1.png");
sprite1->setPosition(m_p1StatusPos[i]);
sprite1->setScale(0.3);
this->addChild(sprite1, 1);
auto sprite2 = Sprite::create("multi/tool1.png");
sprite2->setPosition(m_p2StatusPos[i]);
sprite2->setRotation(180);
sprite2->setScale(0.3);
this->addChild(sprite2, 1);
}*/
}
void MultiScene::addPlayerName()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto pname1 = Label::createWithTTF("player1", "fonts/DTLNobelT-Bold.otf", 40);
auto pname2 = Label::createWithTTF("player2", "fonts/DTLNobelT-Bold.otf", 40);
pname1->setPosition(origin.x + 60, origin.y + 40);
pname2->setPosition(origin.x + visibleSize.width - 60, origin.y + visibleSize.height - 40);
pname2->setRotation(180);
pname1->setColor(Color3B(151.0, 36.0, 9.0));
pname2->setColor(Color3B(39.0, 93.0, 139.0));
this->addChild(pname1, 1);
this->addChild(pname2, 1);
}
void MultiScene::addPlayerName2()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto pname1 = Sprite::create("multi/player1.png");
pname1->setPosition(origin.x + 60, origin.y + 40);
this->addChild(pname1, 1);
auto pnameicon1 = Sprite::create("multi/person_icon.png");
pnameicon1->setPosition(origin.x + 155, origin.y + 40);
this->addChild(pnameicon1, 1);
auto pname2 = Sprite::create("multi/player2.png");
pname2->setPosition(origin.x + visibleSize.width - 60, origin.y + visibleSize.height - 40);
this->addChild(pname2, 1);
auto pnameicon2 = Sprite::create("multi/duck_icon.png");
pnameicon2->setPosition(origin.x + visibleSize.width - 150, origin.y + visibleSize.height - 40);
pnameicon2->setRotation(180);
this->addChild(pnameicon2, 1);
}
void MultiScene::manualAct1()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto manual_mask = Sprite::create("manual/mask.png");
manual_mask->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
this->addChild(manual_mask, 5, "manual_mask");
CCSprite* gesture = CCSprite::create("manual/gesture.png");
gesture->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 8);
gesture->setScale(0.6);
this->addChild(gesture, 5, "gesture");
CCSprite* up_count = CCSprite::create("manual/up_count.png");
up_count->setPosition(origin.x + visibleSize.width / 2 + 120, origin.y + visibleSize.height / 4);
this->addChild(up_count, 5, "up_count");
CCActionInterval * moveup = CCMoveBy::create(1.0f, ccp(0, 100));
CCActionInterval * movedown = CCMoveBy::create(0.1f, ccp(0, -100));
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("manual_mask");
this->removeChildByName("gesture");
this->removeChildByName("up_count");
m_stageCount = 1;
});
CCFiniteTimeAction * seq = CCSequence::create(moveup, movedown, moveup, funcall, NULL);
gesture->runAction(seq);
}
void MultiScene::manualAct2()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto manual_mask = Sprite::create("manual/mask.png");
manual_mask->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
this->addChild(manual_mask, 5, "manual_mask");
auto multi_tip1 = Sprite::create("manual/multiTip1.png");
multi_tip1->setPosition(origin.x + visibleSize.width / 2 - 50, origin.y + visibleSize.height / 2 - 250);
this->addChild(multi_tip1, 5, "multitip1");
CCSprite* gesture = CCSprite::create("manual/gesture.png");
gesture->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 8);
gesture->setScale(0.6);
this->addChild(gesture, 5, "gesture");
CCActionInterval * moveup = CCMoveBy::create(1.0f, ccp(0, 100));
CCActionInterval * movedown = CCMoveBy::create(0.1f, ccp(0, -100));
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("manual_mask");
this->removeChildByName("gesture");
this->removeChildByName("multitip1");
m_stageCount = 2;
});
CCFiniteTimeAction * seq = CCSequence::create(moveup, movedown, moveup, funcall, NULL);
gesture->runAction(seq);
}
void MultiScene::manualAct3()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto manual_mask = Sprite::create("manual/mask.png");
manual_mask->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
this->addChild(manual_mask, 5, "manual_mask");
auto multi_tip2 = Sprite::create("manual/multiTip2.png");
multi_tip2->setPosition(origin.x + visibleSize.width / 2 - 50, origin.y + visibleSize.height / 2 - 150);
this->addChild(multi_tip2, 5, "multitip2");
CCSprite* tool_cm = CCSprite::create("multi/tool5.png");
tool_cm->setPosition(origin.x + 80, origin.y + visibleSize.height / 2 - 250);
this->addChild(tool_cm, 5, "tool_cm");
CCActionInterval * scaleTo = CCScaleTo::create(3.0, 0.3, 0.3);
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("manual_mask");
this->removeChildByName("tool_cm");
this->removeChildByName("multitip2");
m_stageCount = 3;
});
CCFiniteTimeAction * seq = CCSequence::create(scaleTo, funcall, NULL);
tool_cm->runAction(seq);
}
void MultiScene::manualAct4()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto manual_mask = Sprite::create("manual/mask.png");
manual_mask->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
this->addChild(manual_mask, 5, "manual_mask");
auto multi_tip3 = Sprite::create("manual/multiTip3.png");
multi_tip3->setPosition(origin.x + visibleSize.width / 2 - 50, origin.y + visibleSize.height / 2 - 150);
this->addChild(multi_tip3, 5, "multitip3");
CCSprite* gesture = CCSprite::create("manual/gesture.png");
gesture->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 8);
gesture->setScale(0.6);
this->addChild(gesture, 5, "gesture");
CCActionInterval* moveright = CCMoveBy::create(1.5f, ccp(130, 0));
CCActionInterval* moveleft = CCMoveBy::create(0.2f, ccp(-130, 0));
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("manual_mask");
this->removeChildByName("gesture");
this->removeChildByName("multitip3");
m_stageCount = 7;
});
CCFiniteTimeAction * seq = CCSequence::create(moveright, moveleft, moveright, funcall, NULL);
gesture->runAction(seq);
}
void MultiScene::manualAct5()
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto manual_mask = Sprite::create("manual/mask.png");
manual_mask->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2);
this->addChild(manual_mask, 5, "manual_mask");
auto multi_tip4 = Sprite::create("manual/multiTip4.png");
multi_tip4->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 200);
this->addChild(multi_tip4, 5, "multitip4");
scheduleOnce(schedule_selector(MultiScene::updateManualAct1), 3.0f);
}
void MultiScene::updateManualAct1(float time)
{
this->removeChildByName("multitip4");
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
CCSprite* target_frame = CCSprite::create("manual/redFrame.png");
target_frame->setPosition(origin.x + visibleSize.width / 2 - 180, origin.y + visibleSize.height / 2 - 40);
target_frame->setScale(1.0, 0.4);
this->addChild(target_frame, 5, "target_frame");
auto multi_tip5 = Sprite::create("manual/multiTip5.png");
multi_tip5->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 250);
this->addChild(multi_tip5, 5, "multitip5");
scheduleOnce(schedule_selector(MultiScene::updateManualAct2), 3.0f);
}
void MultiScene::updateManualAct2(float time)
{
this->removeChildByName("multitip5");
this->removeChildByName("target_frame");
MCManual::writeUserProfile(MANUAL_MULTI, false);
auto scene = MultiScene::createScene();
Director::sharedDirector()->replaceScene(CCTransitionPageTurn::create(0.5f, scene, false));
}
void MultiScene::smokeEffect(int whichHalf)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
if (whichHalf == 1)
{
auto smokeLayer1 = Sprite::create("multi/cloud1.png");
smokeLayer1->setPosition(origin.x + visibleSize.width / 2 + 5, origin.y + smokeLayer1->getContentSize().height / 2);
this->addChild(smokeLayer1, 2, "smokeLayer1_1");
auto smokeLayer2 = Sprite::create("multi/cloud2.png");
smokeLayer2->setPosition(origin.x + visibleSize.width / 2 + 5, origin.y + smokeLayer1->getContentSize().height / 2);
this->addChild(smokeLayer2, 2, "smokeLayer1_2");
auto smokeLayer3 = Sprite::create("multi/cloud3.png");
smokeLayer3->setPosition(origin.x + visibleSize.width / 2 + 5, origin.y + smokeLayer1->getContentSize().height / 2);
this->addChild(smokeLayer3, 2, "smokeLayer1_3");
CCActionInterval* moveleft = CCMoveBy::create(2.5f, ccp(-30, 0));
CCActionInterval* fadeout = CCFadeOut::create(0.5f);
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("smokeLayer1_1");
this->removeChildByName("smokeLayer1_2");
this->removeChildByName("smokeLayer1_3");
m_stageCount = 7;
});
CCFiniteTimeAction * seq = CCSequence::create(moveleft, fadeout, funcall, NULL);
smokeLayer2->runAction(seq);
}
if (whichHalf == 2)
{
auto smokeLayer1 = Sprite::create("multi/cloud1.png");
smokeLayer1->setPosition(origin.x + visibleSize.width / 2 - 5, origin.y + visibleSize.height - smokeLayer1->getContentSize().height / 2 - 1);
smokeLayer1->setRotation(180);
this->addChild(smokeLayer1, 2, "smokeLayer2_1");
auto smokeLayer2 = Sprite::create("multi/cloud2.png");
smokeLayer2->setPosition(origin.x + visibleSize.width / 2 - 5, origin.y + visibleSize.height - smokeLayer1->getContentSize().height / 2 - 1);
smokeLayer2->setRotation(180);
this->addChild(smokeLayer2, 2, "smokeLayer2_2");
auto smokeLayer3 = Sprite::create("multi/cloud3.png");
smokeLayer3->setPosition(origin.x + visibleSize.width / 2 - 5, origin.y + visibleSize.height - smokeLayer1->getContentSize().height / 2 - 1);
smokeLayer3->setRotation(180);
this->addChild(smokeLayer3, 2, "smokeLayer2_3");
CCActionInterval* moveright = CCMoveBy::create(2.5f, ccp(30, 0));
CCActionInterval* fadeout = CCFadeOut::create(0.5f);
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("smokeLayer2_1");
this->removeChildByName("smokeLayer2_2");
this->removeChildByName("smokeLayer2_3");
m_stageCount = 7;
});
CCFiniteTimeAction * seq = CCSequence::create(moveright, fadeout, funcall, NULL);
smokeLayer2->runAction(seq);
}
}
void MultiScene::poorAnimation(int whichPlayer)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto poorSp = Sprite::create();
if (whichPlayer == 1)
{
poorSp->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 250));
poorSp->setName("poorsp");
}
else
{
poorSp->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 + 250));
poorSp->setRotation(180);
poorSp->setName("poorsp");
}
this->addChild(poorSp, 1);
SpriteFrameCache *m_frameCache = SpriteFrameCache::sharedSpriteFrameCache();
m_frameCache->addSpriteFramesWithFile("multi/poor_animation.plist", "multi/poor_animation.png");
Vector<SpriteFrame*> frameArray;
for (unsigned int i = 1; i <= 12; i++)
{
SpriteFrame* frame = m_frameCache->spriteFrameByName(String::createWithFormat("poor_%d.png", i)->getCString());
frameArray.pushBack(frame);
}
Animation* animation = Animation::createWithSpriteFrames(frameArray);
animation->setLoops(1);
animation->setDelayPerUnit(0.083f);
Animate* act = Animate::create(animation);
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("poorsp");
});
CCFiniteTimeAction * seq = CCSequence::create(act, funcall, NULL);
poorSp->runAction(seq);
}
void MultiScene::invincibleAnimation(int whichPlayer)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto invincibleSp = Sprite::create();
auto invincibleLightSp = Sprite::create("multi/engel_light.png");
auto invincibTipSp = Sprite::create("multi/invic_tip.png");
if (whichPlayer == 1)
{
invincibleSp->setPosition(Vec2(origin.x + visibleSize.width / 2 - 50, origin.y + visibleSize.height / 2 - 250));
invincibleSp->setScale(0.8);
invincibleLightSp->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 - 335));
invincibleLightSp->setScale(0.73, 0.9);
invincibTipSp->setPosition(Vec2(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2 - 250));
invincibTipSp->setScale(0.8);
}
else
{
invincibleSp->setPosition(Vec2(origin.x + visibleSize.width / 2 + 50, origin.y + visibleSize.height / 2 + 250));
invincibleSp->setRotation(180);
invincibleSp->setScale(0.8);
invincibleLightSp->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2 + 335));
invincibleLightSp->setScale(0.73, 0.9);
invincibleLightSp->setRotation(180);
invincibTipSp->setPosition(Vec2(origin.x + visibleSize.width / 2 - 80, origin.y + visibleSize.height / 2 + 250));
invincibTipSp->setRotation(180);
invincibTipSp->setScale(0.8);
}
invincibleSp->setName("invinciblesp");
invincibleLightSp->setName("invincibleLightsp");
invincibTipSp->setName("invincibTipsp");
this->addChild(invincibleSp, 1);
this->addChild(invincibleLightSp, 1);
this->addChild(invincibTipSp, 1);
SpriteFrameCache *m_frameCache = SpriteFrameCache::sharedSpriteFrameCache();
m_frameCache->addSpriteFramesWithFile("multi/invincible.plist", "multi/invincible.png");
Vector<SpriteFrame*> frameArray;
for (unsigned int i = 1; i <= 2; i++)
{
SpriteFrame* frame = m_frameCache->spriteFrameByName(String::createWithFormat("invincible_%d.png", i)->getCString());
frameArray.pushBack(frame);
}
Animation* animation = Animation::createWithSpriteFrames(frameArray);
animation->setLoops(10);
animation->setDelayPerUnit(0.2f);
Animate* act = Animate::create(animation);
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("invinciblesp");
this->removeChildByName("invincibleLightsp");
this->removeChildByName("invincibTipsp");
});
CCFiniteTimeAction * seq = CCSequence::create(act, funcall, NULL);
invincibleSp->runAction(seq);
}
void MultiScene::richAnimation(int whichPlayer)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto richSp = Sprite::create();
auto richNumSp = Sprite::create("multi/rich_rate.png");
richSp->setScale(0.5);
richNumSp->setScale(0.8);
if (whichPlayer == 1)
{
richSp->setPosition(Vec2(origin.x + visibleSize.width / 2 - 30, origin.y + visibleSize.height / 2 - 250));
richNumSp->setPosition(Vec2(origin.x + visibleSize.width / 2 + 30, origin.y + visibleSize.height / 2 - 250));
}
else
{
richSp->setPosition(Vec2(origin.x + visibleSize.width / 2 + 30, origin.y + visibleSize.height / 2 + 250));
richNumSp->setPosition(Vec2(origin.x + visibleSize.width / 2 - 30, origin.y + visibleSize.height / 2 + 250));
richSp->setRotation(180);
richNumSp->setRotation(180);
}
richSp->setName("richsp");
richNumSp->setName("richNumsp");
this->addChild(richSp, 1);
this->addChild(richNumSp, 1);
SpriteFrameCache *m_frameCache = SpriteFrameCache::sharedSpriteFrameCache();
m_frameCache->addSpriteFramesWithFile("multi/rich_animation.plist", "multi/rich_animation.png");
Vector<SpriteFrame*> frameArray;
for (unsigned int i = 1; i <= 13; i++)
{
SpriteFrame* frame = m_frameCache->spriteFrameByName(String::createWithFormat("rich_%d.png", i)->getCString());
frameArray.pushBack(frame);
}
Animation* animation = Animation::createWithSpriteFrames(frameArray);
animation->setLoops(2);
animation->setDelayPerUnit(0.154f);
Animate* act = Animate::create(animation);
CCCallFunc * funcall = CCCallFunc::create([&](){
this->removeChildByName("richsp");
this->removeChildByName("richNumsp");
});
CCFiniteTimeAction * seq = CCSequence::create(act, funcall, NULL);
richSp->runAction(seq);
}
void MultiScene::encourageEffect(int whichPlayer)
{
int goodCount = m_p1GoodCount;
if (whichPlayer == 2)
goodCount = m_p2GoodCount;
if (goodCount == 4)
{
AudioControl::playEncourageEffect(COOL);
m_zoomingWord[whichPlayer-1][0]->Zooming();
}
else if (goodCount == 7)
{
AudioControl::playEncourageEffect(NICE);
m_zoomingWord[whichPlayer - 1][1]->Zooming();
}
else if (goodCount == 10)
{
AudioControl::playEncourageEffect(GREAT);
m_zoomingWord[whichPlayer - 1][2]->Zooming();
}
else if (goodCount == 13)
{
AudioControl::playEncourageEffect(ACE);
m_zoomingWord[whichPlayer - 1][3]->Zooming();
}
else if (goodCount == 16)
{
AudioControl::playEncourageEffect(EXCELLENT);
m_zoomingWord[whichPlayer - 1][4]->Zooming();
}
else if (goodCount % 4 == 0 && goodCount > 16)
{
AudioControl::playEncourageEffect(AWESOME);
m_zoomingWord[whichPlayer - 1][5]->Zooming();
}
}
| [
"tencenthao@gmail.com"
] | tencenthao@gmail.com |
9cd51a5bafc2898837a96cf7239a7e413ba135f3 | 2d5e747d7430896585a828ff94828572a3bf7770 | /source/externalplaylist.h | a901b2bdb24f6a224b723508d3f786578a66f43f | [] | no_license | lefty01/is_KeyFinder | e76a5bfa0eaea07e2183f3aa20de9f6bb83cc8f4 | f6706074435ac14c5238ee3f0dd22ac22d72af9c | refs/heads/master | 2021-01-18T10:56:29.700286 | 2014-10-22T21:08:27 | 2014-10-22T21:08:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,826 | h | /*************************************************************************
Copyright 2011-2013 Ibrahim Sha'ath
This file is part of KeyFinder.
KeyFinder is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KeyFinder 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with KeyFinder. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef EXTERNALPLAYLIST_H
#define EXTERNALPLAYLIST_H
#include <QUrl>
#include <QMutex>
#include <QRegularExpressionMatch>
#ifndef Q_OS_MAC
#include <QtXml/QtXml>
#include <QtXmlPatterns/QtXmlPatterns>
#else
// XQilla
#include <xqilla/xqilla-simple.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xqilla/xqilla-dom3.hpp>
#endif
#include "preferences.h"
#include "strings.h"
#include "externalplaylistserato.h"
const QString SOURCE_KEYFINDER = GuiStrings::getInstance()->appName();
const QString SOURCE_ITUNES = "iTunes";
const QString SOURCE_TRAKTOR = "Traktor";
const QString SOURCE_SERATO = "Serato";
class ExternalPlaylistObject{
public:
ExternalPlaylistObject(const QString&, const QString&);
QString name;
QString source;
};
class ExternalPlaylist{
public:
static QList<ExternalPlaylistObject> readLibrary(const Preferences&);
static QList<QUrl> readLibraryPlaylist(const QString&, const QString&, const Preferences&);
static QList<QUrl> readITunesStandalonePlaylist(const QString&);
static QList<QUrl> readM3uStandalonePlaylist(const QString&);
private:
// iTunes
static QList<ExternalPlaylistObject> readPlaylistsFromITunesLibrary(const Preferences&);
static QList<QUrl> readITunesLibraryPlaylist(const QString&, const Preferences&);
static QUrl fixITunesAddressing(const QString&);
// Serato
static QList<ExternalPlaylistObject> readPlaylistsFromSeratoLibrary(const Preferences&);
static QList<QUrl> readSeratoLibraryPlaylist(const QString&, const Preferences&);
static QUrl fixSeratoAddressing(const QString&, const QString&);
// Traktor
static QList<ExternalPlaylistObject> readPlaylistsFromTraktorLibrary(const Preferences&);
static QList<QUrl> readTraktorLibraryPlaylist(const QString&, const Preferences&);
static QUrl fixTraktorAddressing(const QString&);
// XML handling
static QStringList executeXmlQuery(const QString&, const QString&, const QStringList& = QStringList());
};
#endif // EXTERNALPLAYLIST_H
| [
"ibrahimshaath@gmail.com"
] | ibrahimshaath@gmail.com |
59d9117c20e84927417cbf5a82dccb0ef5456ade | a565eef51e8445b519288ac32affbd7adca874d3 | /libgringo/tests/ground/instantiation.cc | cecc899e763a3102d42f8db3b50435b85576623f | [
"MIT"
] | permissive | CaptainUnbrauchbar/clingo | b28a9b5218552240ea03444e157a21079fc77019 | 58cb702db83c23aedea28b26a617102fae9b557a | refs/heads/master | 2023-02-27T23:53:44.566739 | 2021-02-01T18:36:10 | 2021-02-01T18:36:10 | 290,831,881 | 1 | 0 | MIT | 2021-02-01T18:36:11 | 2020-08-27T16:53:18 | C++ | UTF-8 | C++ | false | false | 45,892 | cc | // {{{ MIT License
// Copyright 2017 Roland Kaminski
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// }}}
#include "gringo/input/nongroundparser.hh"
#include "gringo/input/program.hh"
#include "gringo/ground/program.hh"
#include "gringo/output/output.hh"
#include "tests/tests.hh"
#include <regex>
namespace Gringo { namespace Ground { namespace Test {
using namespace Gringo::IO;
namespace {
std::string ground(std::string const &str, std::initializer_list<std::string> filter = {""}) {
std::regex delayedDef("^#delayed\\(([0-9]+)\\) <=> (.*)$");
std::regex delayedOcc("#delayed\\(([0-9]+)\\)");
std::map<std::string, std::string> delayedMap;
std::stringstream ss;
Potassco::TheoryData td;
Output::OutputBase out(td, {}, ss, Output::OutputFormat::TEXT);
Input::Program prg;
Defines defs;
Gringo::Test::TestGringoModule module;
Gringo::Test::TestContext context;
Input::NongroundProgramBuilder pb{ context, prg, out, defs };
bool incmode;
Input::NonGroundParser ngp{ pb, incmode };
ngp.pushStream("-", gringo_make_unique<std::stringstream>(str), module);
ngp.parse(module);
prg.rewrite(defs, module);
Program gPrg(prg.toGround({Sig{"base", 0, false}}, out.data, module));
Parameters params;
params.add("base", {});
gPrg.ground(params, context, out, module);
out.endStep({});
std::string line;
std::vector<std::string> res;
ss.seekg(0, std::ios::beg);
while (std::getline(ss, line)) {
std::smatch m;
if (std::regex_match(line, m, delayedDef)) {
delayedMap[m[1]] = m[2];
}
else if (!line.compare(0, 9, "#delayed(")) {
res.emplace_back(std::move(line));
}
else {
for (auto &x : filter) {
if (!line.compare(0, x.size(), x)) {
res.emplace_back(std::move(line));
break;
}
}
}
}
for (auto &x : res) {
std::string r;
auto st = x.cbegin();
for (auto it = std::sregex_iterator(x.begin(), x.end(), delayedOcc), ie = std::sregex_iterator(); it != ie; ++it) {
std::smatch match = *it;
r.append(st, match.prefix().second);
st = match.suffix().first;
r.append(delayedMap[match[1]]);
}
r.append(st, x.cend());
x = r;
}
std::stringstream oss;
std::sort(res.begin(), res.end());
for (auto &x : res) { oss << x << "\n"; }
for (auto &x : module.messages()) { oss << x; }
return oss.str();
}
std::string gbie() {
return
"char_to_digit(X,X) :- X=0..9.\n"
"digit(Y-1,Y,D) :- char(C,Y), char_to_digit(C,D), Y > 0.\n"
"sign(X, 1) :- char(p,X).\n"
"sign(X,-1) :- char(m,X).\n"
"num_1(X,Y,A) :- digit(X,Y,A), not digit(_,X,_).\n"
"num_1(X,Z,10*A+B) :- num_1(X,Y,A), digit(Y,Z,B).\n"
"num(X,Y,A) :- num_1(X,Y,A), not digit(_,Y+1,_).\n"
"par_expr(Y-1,Z+1,A) :- char(o,Y), expr(Y,Z,A), char(c,Z+1), Y >= 0.\n"
"sign_expr(Y-1,Z,A*S) :- par_expr(Y,Z,A), sign(Y,S), Y > 0.\n"
"sign_expr(Y-1,Z,A*S) :- num(Y,Z,A), sign(Y,S), Y > 0.\n"
"expr(0,Y,A) :- num(0,Y,A).\n"
"expr(X,Y,A) :- char(o,X), num(X,Y,A).\n"
"expr(X,Y,A) :- par_expr(X,Y,A).\n"
"expr(X,Y,A) :- sign_expr(X,Y,A).\n"
"expr(X,Z,A+B) :- expr(X,Y,A), sign_expr(Y,Z,B).\n"
"cmp(Y-1,A) :- char(g,Y), num(Y,_,A), Y > 0.\n"
"cmp(Y-1,A*S) :- char(g,Y), sign(Y+1,S), num(Y+1,_,A), Y > 0.\n"
"le(A,B) :- expr(0,Y,A), cmp(Y,B), A <= B.\n"
"gt(A,B) :- expr(0,Y,A), cmp(Y,B), A > B.\n";
}
std::string gbie1() {
return
"char(p,1).\n" "char(0,2).\n" "char(m,3).\n" "char(o,4).\n"
"char(o,5).\n" "char(6,6).\n" "char(m,7).\n" "char(7,8).\n"
"char(p,9).\n" "char(3,10).\n" "char(p,11).\n" "char(o,12).\n"
"char(4,13).\n" "char(c,14).\n" "char(c,15).\n" "char(m,16).\n"
"char(2,17).\n" "char(p,18).\n" "char(o,19).\n" "char(p,20).\n"
"char(0,21).\n" "char(c,22).\n" "char(c,23).\n" "char(p,24).\n"
"char(2,25).\n" "char(m,26).\n" "char(o,27).\n" "char(p,28).\n"
"char(1,29).\n" "char(c,30).\n" "char(g,31).\n" "char(m,32).\n"
"char(4,33).\n";
}
std::string gbie2() {
return
"char(o,1).\n" "char(m,2).\n" "char(o,3).\n" "char(p,4).\n"
"char(1,5).\n" "char(m,6).\n" "char(o,7).\n" "char(m,8).\n"
"char(2,9).\n" "char(c,10).\n" "char(p,11).\n" "char(7,12).\n"
"char(c,13).\n" "char(m,14).\n" "char(5,15).\n" "char(m,16).\n"
"char(o,17).\n" "char(m,18).\n" "char(4,19).\n" "char(p,20).\n"
"char(o,21).\n" "char(p,22).\n" "char(o,23).\n" "char(p,24).\n"
"char(2,25).\n" "char(c,26).\n" "char(c,27).\n" "char(c,28).\n"
"char(c,29).\n" "char(p,30).\n" "char(o,31).\n" "char(o,32).\n"
"char(m,33).\n" "char(6,34).\n" "char(p,35).\n" "char(1,36).\n"
"char(c,37).\n" "char(c,38).\n" "char(g,39).\n" "char(m,40).\n"
"char(1,41).\n" "char(6,42).\n";
}
std::string strategicA1() {
return
"controlled_by(1,5,2,2).\n"
"controlled_by(1,5,3,3).\n"
"controlled_by(2,6,3,5).\n"
"controlled_by(2,6,3,1).\n"
"controlled_by(3,4,1,5).\n"
"controlled_by(3,4,1,6).\n"
"controlled_by(4,2,6,6).\n"
"controlled_by(4,2,5,5).\n"
"controlled_by(5,1,1,1).\n"
"controlled_by(6,4,4,4).\n"
"produced_by(p1, 4,2).\n"
"produced_by(p2, 5,1).\n"
"produced_by(p3, 2,6).\n"
"produced_by(p4, 4,2).\n"
"produced_by(p5, 5,6).\n"
"produced_by(p6, 2,4).\n"
"produced_by(p7, 4,3).\n"
"produced_by(p8, 5,2).\n"
"produced_by(p9, 5,5).\n"
"produced_by(p10, 6,2).\n"
"produced_by(p11, 4,4).\n"
"produced_by(p12, 4,3).\n"
"produced_by(p13, 4,6).\n"
"produced_by(p14, 4,4).\n"
"produced_by(p15, 6,4).\n"
"produced_by(p16, 1,1).\n"
"produced_by(p17, 5,5).\n"
"produced_by(p18, 1,6).\n"
"produced_by(p19, 2,5).\n"
"produced_by(p20, 1,6).\n"
"produced_by(p21, 4,6).\n"
"produced_by(p22, 2,5).\n"
"produced_by(p23, 2,6).\n"
"produced_by(p24, 6,6).\n";
}
std::string strategicB1() {
return
"controlled_by(c1,1,(5;2;2)).\n"
"controlled_by(c2,1,(5;3;3)).\n"
"controlled_by(c3,2,(6;3;5)).\n"
"controlled_by(c4,2,(6;3;1)).\n"
"controlled_by(c5,3,(4;1;5)).\n"
"controlled_by(c6,3,(4;1;6)).\n"
"controlled_by(c7,4,(2;6;6)).\n"
"controlled_by(c8,4,(2;5;5)).\n"
"controlled_by(c9,5,(1;1;1)).\n"
"controlled_by(c10,6,(4;4;4)).\n"
"produced_by(p1, (4;2)).\n"
"produced_by(p2, (5;1)).\n"
"produced_by(p3, (2;6)).\n"
"produced_by(p4, (4;2)).\n"
"produced_by(p5, (5;6)).\n"
"produced_by(p6, (2;4)).\n"
"produced_by(p7, (4;3)).\n"
"produced_by(p8, (5;2)).\n"
"produced_by(p9, (5;5)).\n"
"produced_by(p10,(6;2)).\n"
"produced_by(p11,(4;4)).\n"
"produced_by(p12,(4;3)).\n"
"produced_by(p13,(4;6)).\n"
"produced_by(p14,(4;4)).\n"
"produced_by(p15,(6;4)).\n"
"produced_by(p16,(1;1)).\n"
"produced_by(p17,(5;5)).\n"
"produced_by(p18,(1;6)).\n"
"produced_by(p19,(2;5)).\n"
"produced_by(p20,(1;6)).\n"
"produced_by(p21,(4;6)).\n"
"produced_by(p22,(2;5)).\n"
"produced_by(p23,(2;6)).\n"
"produced_by(p24,(6;6)).\n";
}
}
TEST_CASE("ground-instantiation", "[ground]") {
SECTION("instantiateRec") {
REQUIRE(
"a(0).\n"
"a(1).\n"
"a(2).\n"
"a(3).\n"
"a(4).\n"
"b(0).\n"
"b(1).\n"
"b(2).\n"
"b(3).\n"
"b(4).\n"
"c(0).\n"
"c(1).\n"
"c(2).\n"
"c(3).\n"
"c(4).\n"
"d(0).\n"
"d(1).\n"
"d(2).\n"
"d(3).\n"
"d(4).\n"
"p(0).\n"
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"p(5).\n" == ground(
"p(0).\n"
"a(X) :- p(X), X < 5.\n"
"b(X) :- a(X).\n"
"c(X) :- b(X), a(X).\n"
"d(X) :- c(X), b(X), a(X).\n"
"p(X+1) :- a(X), b(X), c(X), d(X).\n"));
}
SECTION("instantiate") {
REQUIRE(
"e(1,2).\n"
"e(2,1).\n"
"r(1).\n"
"r(2).\n"
"v(1).\n" == ground("v(1).e(1,2).e(2,1).r(X):-v(X).r(Y):-r(X),e(X,Y)."));
REQUIRE(
"p(1,2).\n" "p(1,3).\n" "p(1,4).\n" "p(1,5).\n" "p(1,6).\n" "p(1,7).\n"
"p(2,3).\n" "p(2,4).\n" "p(2,5).\n" "p(2,6).\n" "p(2,7).\n"
"p(3,4).\n" "p(3,5).\n" "p(3,6).\n" "p(3,7).\n"
"p(4,5).\n" "p(4,6).\n" "p(4,7).\n"
"p(5,6).\n" "p(5,7).\n"
"p(6,7).\n" == ground(
"p(1,2)."
"p(2,3)."
"p(3,4)."
"p(4,5)."
"p(5,6)."
"p(6,7)."
"p(X,Z) :- p(X,Y), p(Y,Z)."));
REQUIRE(
"x.\n"
"y.\n"
"z.\n" == ground(
"x :- y, z."
"x :- not v."
"y."
"z."
"v :- not x."));
REQUIRE(
"p(f(1)).\n"
"p(f(2)).\n"
"p(g(1)):-not p(f(3)).\n"
"p(g(2)):-not p(f(3)).\n" == ground(
"p(f(1)).\n"
"p(f(2)).\n"
"p(Y):-p(f(X)),Y=g(X),not p(f(3)).\n"));
REQUIRE(
"p(f(1)).\n"
"p(f(2)).\n"
"p(g(1)).\n"
"p(g(2)).\n" == ground(
"p(f(1)).\n"
"p(f(2)).\n"
"p(g(X)):-p(f(X)),not p(f(3)).\n"));
REQUIRE(
"0>=#count{0,a:#true}.\n"
"a.\n" == ground(
"a.\n"
"0 { a } 0 :- a, #false : #false.\n"));
}
SECTION("bodyaggregate") {
REQUIRE(
"company(c1).\n" "company(c2).\n" "company(c3).\n" "company(c4).\n"
"controls(c1,c2).\n" "controls(c1,c3).\n" "controls(c1,c4).\n" "controls(c3,c4).\n"
"owns(c1,c2,60).\n" "owns(c1,c3,20).\n" "owns(c2,c3,35).\n" "owns(c3,c4,51).\n" == ground(
"controls(X,Y) :- 51 #sum+ { S: owns(X,Y,S); S: owns(Z,Y,S), controls(X,Z), X != Y }, company(X), company(Y), X != Y."
"company(c1)."
"company(c2)."
"company(c3)."
"company(c4)."
"owns(c1,c2,60)."
"owns(c1,c3,20)."
"owns(c2,c3,35)."
"owns(c3,c4,51)."));
}
SECTION("bodyaggregate2") {
REQUIRE(
"company(c1).\n" "company(c2).\n" "company(c3).\n" "company(c4).\n"
"controls(c1,c2):-#sum{60:}.\n"
"controls(c1,c3):-51<=#sum{20:;35:controls(c1,c2)}.\n"
"controls(c1,c4):-51<=#sum{51:controls(c1,c3)}.\n"
"controls(c3,c4):-#sum{51:}.\n"
"owns(c1,c2,60).\n" "owns(c1,c3,20).\n" "owns(c2,c3,35).\n" "owns(c3,c4,51).\n" == ground(
"controls(X,Y) :- 51 #sum { S: owns(X,Y,S); S: owns(Z,Y,S), controls(X,Z), X != Y }, company(X), company(Y), X != Y."
"company(c1)."
"company(c2)."
"company(c3)."
"company(c4)."
"owns(c1,c2,60)."
"owns(c1,c3,20)."
"owns(c2,c3,35)."
"owns(c3,c4,51)."));
}
SECTION("bodyaggregate3") {
REQUIRE(
"a:-#true,not c.\n"
"c.\n" == ground(
"a :- not { c } >= 1, not c."
"b :- a, #false."
"c :- not b, {b; not b} >= 1."
));
REQUIRE(
"a:-#false,not c.\n"
"c.\n" == ground(
"a :- not not { c } >= 1, not c."
"b :- a, #false."
"c :- not b, {b; not b} >= 1."
));
}
SECTION("min_fail") {
REQUIRE(
"c.\n"
"p(1):-not r(1).\n"
"p(2):-not r(2).\n"
"r(1):-not p(1).\n"
"r(2):-not p(2).\n"
"-:27:42-43: info: atom does not occur in any rule head:\n b\n"
== ground(
"p(X) :- not r(X), X=1..2.\n"
"r(X) :- not p(X), X=1..2.\n"
"c.\n"
"fmin(1) :- 1 #max {}.\n"
"fmin(1) :- not not 1 #max {}.\n"
"fmin(2) :- not #max {} 1.\n"
"fmin(3) :- #min {} 1.\n"
"fmin(3) :- not not #min {} 1.\n"
"fmin(4) :- not 1 #min {}.\n"
"fmin(5) :- not 1 #max {1:c} 2.\n"
"fmin(5) :- 1 #max {c:c} 2.\n"
"fmin(5) :- not not 1 #max {c:c} 2.\n"
"fmin(6) :- not 1 #min {1:c} 2.\n"
"fmin(6) :- 1 #min {c:c} 2.\n"
"fmin(6) :- not not 1 #min {c:c} 2.\n"
"fmin(7) :- 3 #max {2:p(1); 1:r(1)}.\n"
"fmin(7) :- not not 3 #max {2:p(1); 1:r(1)}.\n"
"fmin(8) :- #min {2:p(1); 1:r(1)} 0.\n"
"fmin(8) :- not not #min {2:p(1); 1:r(1)} 0.\n"
"fmin(9) :- not #max {2:p(1); 1:r(1)} 2.\n"
"fmin(10) :- not 0 #min {2:p(1); 1:r(1)}.\n"
"fmin(11) :- 1 #max {2:p(1); 1:r(1); 3:c} 1.\n"
"fmin(11) :- not not 1 #max {2:p(1); 1:r(1); 3:c} 1.\n"
"fmin(12) :- not 1 #max {2:p(1); 1:r(1); 3:c}.\n"
"fmin(13) :- 3 #min {2:p(1); 1:r(1); 1,c:c} 3.\n"
"fmin(13) :- not not 3 #min {2:p(1); 1:r(1); 1,c:c} 3.\n"
"fmin(14) :- not #min {2:p(1); 3:b; 1:c} 1.\n"
));
}
SECTION("min_true") {
REQUIRE(
"c.\n"
"p(1):-not r(1).\n"
"p(2):-not r(2).\n"
"r(1):-not p(1).\n"
"r(2):-not p(2).\n"
"tmin(1).\n" "tmin(10).\n" "tmin(11).\n" "tmin(12).\n"
"tmin(13).\n" "tmin(14).\n" "tmin(15).\n" "tmin(16).\n"
"tmin(17).\n" "tmin(18).\n" "tmin(19).\n" "tmin(2).\n"
"tmin(20).\n" "tmin(21).\n" "tmin(22).\n" "tmin(23).\n"
"tmin(24).\n" "tmin(3).\n" "tmin(4).\n" "tmin(5).\n"
"tmin(6).\n" "tmin(7).\n" "tmin(8).\n" "tmin(9).\n"
"-:26:39-40: info: atom does not occur in any rule head:\n b\n"
"-:27:39-40: info: atom does not occur in any rule head:\n b\n"
== ground(
"p(X) :- not r(X), X=1..2.\n"
"r(X) :- not p(X), X=1..2.\n"
"c.\n"
"tmin(1) :- not 1 #max {}.\n"
"tmin(2) :- #max {} 1.\n"
"tmin(3) :- not not #max {} 1.\n"
"tmin(4) :- not #min {} 1.\n"
"tmin(5) :- 1 #min {}.\n"
"tmin(6) :- not not 1 #min {}.\n"
"tmin(7) :- 1 #max {1:c} 2.\n"
"tmin(8) :- not not 1 #max {1:c} 2.\n"
"tmin(9) :- not 1 #max {c:c} 2.\n"
"tmin(10) :- 1 #min {1:c} 2.\n"
"tmin(11) :- not not 1 #min {1:c} 2.\n"
"tmin(12) :- not 1 #min {c:c} 2.\n"
"tmin(13) :- not 3 #max {2:p(1); 1:r(1)}.\n"
"tmin(14) :- not #min {2:p(1); 1:r(1)} 0.\n"
"tmin(15) :- #max {2:p(1); 1:r(1)} 2.\n"
"tmin(16) :- not not #max {2:p(1); 1:r(1)} 2.\n"
"tmin(17) :- 0 #min {2:p(1); 1:r(1)}.\n"
"tmin(18) :- not not 0 #min {2:p(1); 1:r(1)}.\n"
"tmin(19) :- not 1 #max {2:p(1); 1:r(1); 3:c} 1.\n"
"tmin(20) :- 1 #max {2:p(1); 1:r(1); 3:c}.\n"
"tmin(21) :- not not 1 #max {2:p(1); 1:r(1); 3:c}.\n"
"tmin(22) :- not 3 #min {2:p(1); 1:r(1); 1,c:c} 3.\n"
"tmin(23) :- #min {2:p(1); 3:b; 1:c} 1.\n"
"tmin(24) :- not not #min {2:p(1); 3:b; 1:c} 1.\n"
));
}
SECTION("min_open") {
REQUIRE(
"c.\n"
"mfmin(10):-3<=#min{2:p(1);1:r(1)}<=3.\n"
"mfmin(5):-0<=#max{2:p(1);1:r(1)}<=0.\n"
"mmin(1):-2<=#max{2:p(1);1:r(1)}.\n"
"mmin(11):-1>=#min{1:p(1);2:p(2)}.\n"
"mmin(12,1):-0>=#min{0:r(1)}.\n"
"mmin(12,2):-1>=#min{1:r(2)}.\n"
"mmin(2):-1>=#max{2:p(1);1:r(1)}.\n"
"mmin(3):-1<=#max{2:p(1);1:r(1)}<=1.\n"
"mmin(4):-1<=#max{2:p(1);1:r(1)}.\n"
"mmin(6):-2<=#min{2:p(1);1:r(1)}.\n"
"mmin(7):-1>=#min{2:p(1);1:r(1)}.\n"
"mmin(8):-1>=#min{2:p(1);1:r(1)}.\n"
"mmin(9):-2>=#min{2:p(1);1:r(1)}.\n"
"p(1):-not r(1).\n"
"p(2):-not r(2).\n"
"r(1):-not p(1).\n"
"r(2):-not p(2).\n" ==
ground(
"p(X) :- not r(X), X=1..2.\n"
"r(X) :- not p(X), X=1..2.\n"
"c.\n"
"mmin(1) :- 2 #max {2:p(1); 1:r(1)}.\n"
"mmin(2) :- #max {2:p(1); 1:r(1)} 1.\n"
"mmin(3) :- 1 #max {2:p(1); 1:r(1), c} 1.\n"
"mmin(4) :- 1 #max {2:p(1); 1:r(1)} 2.\n"
"mfmin(5) :- 0 #max {2:p(1); 1:r(1)} 0.\n"
"mmin(6) :- 2 #min {2:p(1); 1:r(1)}.\n"
"mmin(7) :- #min {2:p(1); 1:r(1)} 1.\n"
"mmin(8) :- 1 #min {2:p(1); 1:r(1), c} 1.\n"
"mmin(9) :- 1 #min {2:p(1); 1:r(1)} 2.\n"
"mfmin(10) :- 3 #min {2:p(1); 1:r(1)} 3.\n"
"mmin(11) :- 1 #min {X:p(X),X=1..2} 1.\n"
"mmin(12,X) :- X-1 #min {X-1:r(X)} X-1, X=1..2.\n"
));
}
SECTION("assign_min") {
REQUIRE(
"p(-1).\n"
"p(-2).\n"
"p(-3).\n"
"p(0).\n"
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"s(-3).\n" == ground(
"p(X) :- X=-3..4.\n"
"s(S) :- S=#min { X:p(X) }.\n"
));
}
SECTION("assign_max") {
REQUIRE(
"p(-1).\n"
"p(-2).\n"
"p(-3).\n"
"p(0).\n"
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"s(4).\n" == ground(
"p(X) :- X=-3..4.\n"
"s(S) :- S=#max { X:p(X) }.\n"
));
}
SECTION("assign_sump") {
REQUIRE(
"p(-1).\n"
"p(-2).\n"
"p(-3).\n"
"p(0).\n"
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"s(10).\n"
"-:2:19-20: info: tuple ignored:\n -3\n"
"-:2:19-20: info: tuple ignored:\n -2\n"
"-:2:19-20: info: tuple ignored:\n -1\n"
== ground(
"p(X) :- X=-3..4.\n"
"s(S) :- S=#sum+ { X:p(X) }.\n"
));
}
SECTION("assign_count") {
REQUIRE(
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"p(5).\n"
"p(6).\n"
"p(7).\n"
"s(1,8).\n"
"s(2,8).\n"
"s(3,8).\n" == ground(
"p(X) :- X=1..7.\n"
"s(Y,S) :- S=#count { X,a:p(X); Y,b }, Y=1..3.\n"
));
}
SECTION("assign_sum") {
REQUIRE(
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"p(5).\n"
"p(6).\n"
"p(7).\n"
"s(1,29).\n"
"s(2,30).\n"
"s(3,31).\n" == ground(
"p(X) :- X=1..7.\n"
"s(Y,S) :- S=#sum { X,a:p(X); Y,b }, Y=1..3.\n"
));
REQUIRE(
"p(-1).\n"
"p(-2).\n"
"p(-3).\n"
"p(0).\n"
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"s(4).\n" == ground(
"p(X) :- X=-3..4.\n"
"s(S) :- S=#sum { X:p(X) }.\n"
));
}
SECTION("rec_count") {
REQUIRE(
"edge(1,3).\n" "edge(2,3).\n" "edge(3,4).\n" "edge(3,6).\n" "edge(4,5).\n" "edge(4,6).\n" "edge(6,7).\n" "edge(6,8).\n"
"inlink(3,2).\n" "inlink(4,3).\n" "inlink(6,4).\n"
"inner(3).\n" "inner(4).\n" "inner(6).\n"
"irreducible(3,s(s(s(z)))).\n" "irreducible(3,s(s(z))).\n" "irreducible(3,s(z)).\n" "irreducible(6,s(z)).\n"
"link(1,3).\n" "link(2,3).\n" "link(3,4).\n" "link(3,6).\n" "link(4,5).\n" "link(4,6).\n" "link(6,7).\n" "link(6,8).\n"
"linked(1,3).\n" "linked(1,3,s(s(s(z)))).\n" "linked(1,3,s(s(z))).\n" "linked(1,3,s(z)).\n" "linked(1,4).\n" "linked(1,6).\n"
"linked(2,3).\n" "linked(2,3,s(s(s(z)))).\n" "linked(2,3,s(s(z))).\n" "linked(2,3,s(z)).\n" "linked(2,4).\n" "linked(2,6).\n"
"linked(3,4).\n" "linked(3,4,s(z)).\n" "linked(3,5).\n" "linked(3,5,s(s(s(z)))).\n" "linked(3,5,s(s(z))).\n" "linked(3,6).\n"
"linked(3,6,s(s(z))).\n" "linked(3,6,s(z)).\n" "linked(3,7).\n" "linked(3,7,s(s(s(z)))).\n" "linked(3,8).\n" "linked(3,8,s(s(s(z)))).\n"
"linked(4,5).\n" "linked(4,5,s(z)).\n" "linked(4,6).\n" "linked(4,6,s(z)).\n" "linked(4,7).\n" "linked(4,8).\n" "linked(6,7).\n"
"linked(6,7,s(s(z))).\n" "linked(6,7,s(z)).\n" "linked(6,8).\n" "linked(6,8,s(s(z))).\n" "linked(6,8,s(z)).\n"
"oulink(3,5).\n" "oulink(4,4).\n" "oulink(6,2).\n"
"outedge(1,3).\n" "outedge(2,3).\n" "outedge(3,5).\n" "outedge(3,7).\n" "outedge(3,8).\n"
"outvertex(1).\n" "outvertex(2).\n" "outvertex(3).\n" "outvertex(5).\n" "outvertex(7).\n" "outvertex(8).\n"
"prefer(3,0).\n" "prefer(4,1).\n" "prefer(6,2).\n"
"reduced(4,s(z)).\n" "reduced(6,s(s(z))).\n" "reduced(s(s(z))).\n" "reduced(s(z)).\n"
"reducible(4,s(z)).\n" "reducible(6,s(s(z))).\n" "unlinked(1,4,s(z)).\n"
"unlinked(1,6,s(s(z))).\n" "unlinked(1,6,s(z)).\n" "unlinked(2,4,s(z)).\n" "unlinked(2,6,s(s(z))).\n" "unlinked(2,6,s(z)).\n"
"unlinked(3,4,s(s(s(z)))).\n" "unlinked(3,4,s(s(z))).\n" "unlinked(3,5,s(z)).\n" "unlinked(3,6,s(s(s(z)))).\n" "unlinked(3,7,s(s(z))).\n"
"unlinked(3,7,s(z)).\n" "unlinked(3,8,s(s(z))).\n" "unlinked(3,8,s(z)).\n" "unlinked(4,6,s(s(z))).\n" "unlinked(4,7,s(z)).\n" "unlinked(4,8,s(z)).\n"
"unreduced(3,s(s(s(z)))).\n" "unreduced(3,s(s(z))).\n" "unreduced(3,s(z)).\n" "unreduced(4,s(z)).\n" "unreduced(6,s(s(z))).\n" "unreduced(6,s(z)).\n"
"vertex(1).\n" "vertex(2).\n" "vertex(3).\n" "vertex(4).\n" "vertex(5).\n" "vertex(6).\n" "vertex(7).\n" "vertex(8).\n" == ground(
"%%%%%%%%%%%%%%%%%%%%\n"
"% INPUT PREDICATES %\n"
"%%%%%%%%%%%%%%%%%%%%\n"
"\n"
"vertex(1). vertex(2). vertex(3). vertex(4). vertex(5). vertex(6). vertex(7). vertex(8).\n"
"edge(1,3). edge(2,3). edge(3,4). edge(3,6). edge(4,5). edge(4,6). edge(6,7). edge(6,8).\n"
"\n"
"% 1-+ 4-+-5\n"
"% | | |\n"
"% 3-+-6-+-7\n"
"% | |\n"
"% 2-+ 8\n"
"\n"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
"% INNER VERTICES WITHOUT SELF-LOOP ARE REDUCIBLE %\n"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
"\n"
"inner(V) :- edge(U,V), edge(V,W), not edge(V,V).\n"
"\n"
"link(U,V) :- edge(U,V), 1 #sum+{ 1 : inner(U); 1 : inner(V) }.\n"
"\n"
"linked(U,V) :- link(U,V).\n"
"linked(U,V) :- link(U,W), linked(W,V), inner(W), 1 #sum+ { 1 : inner(U); 1 : inner(V) }.\n"
"\n"
"inlink(V,N) :- inner(V), N = #sum+{ 1,U : linked(U,V), U != V }.\n"
"oulink(V,N) :- inner(V), N = #sum+{ 1,W : linked(V,W), V != W }.\n"
"\n"
"prefer(V,N) :- inner(V), N = #sum+{ 1,U : inner(U), U < V }.\n"
"\n"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
"% ITERATIVELY REDUCE INNER VERTICES AS LONG AS SOME HAS ONE PREDECESSOR/SUCCESSOR %\n"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
"\n"
"unreduced(V,s(z)) :- inner(V).\n"
"unreduced(V,s(I)) :- unreduced(V,I), reduced(W,I), V != W.\n"
"\n"
"linked(U,V,s(z)) :- link(U,V).\n"
"linked(U,V,s(I)) :- linked(U,W,I), linked(W,V,I), reduced(W,I).\n"
"linked(U,V,s(I)) :- linked(U,V,I), reduced(I),\n"
" 2 #sum+{ 1,a : unreduced(U,s(I)); 1,b : unreduced(V,s(I)); 1,a : not inner(U); 1,b : not inner(V) }.\n"
"\n"
"irreducible(V,I) :- unreduced(V,I), linked(V,V,I).\n"
"irreducible(V,I) :- unreduced(V,I),\n"
" 2 #sum+{ 1,U : linked(U,V,I), U != V }, 2 #sum+{ 1,W : linked(V,W,I), V != W }.\n"
"\n"
"unlinked(U,V,s(z)) :- linked(U,V), not link(U,V).\n"
"unlinked(U,V,s(I)) :- linked(U,V,I), reduced(U,I), inner(V).\n"
"unlinked(U,V,s(I)) :- linked(U,V,I), reduced(V,I), inner(U).\n"
"unlinked(U,V,s(I)) :- unlinked(U,V,I), reduced(U,J), J <= I, unreduced(V,s(I)).\n"
"unlinked(U,V,s(I)) :- unlinked(U,V,I), reduced(V,J), J <= I, unreduced(U,s(I)).\n"
"unlinked(U,V,s(I)) :- unlinked(U,V,I), reduced(W,I), U != W, V != W,\n"
" 1 #sum+{ 1 : unlinked(U,W,I); 1 : unlinked(W,V,I); 1 : not linked(U,W); 1 : not linked(W,V) }.\n"
"\n"
"reducible(V,I) :- unreduced(V,I), inlink(V,N),\n"
" N #sum+{ 1; 1,U : unlinked(U,V,I), U != V }, 1 #sum+{ 1 : unlinked(V,V,I); 1 : not linked(V,V) }.\n"
"reducible(V,I) :- unreduced(V,I), oulink(V,N),\n"
" N #sum+{ 1; 1,W : unlinked(V,W,I), V != W }, 1 #sum+{ 1 : unlinked(V,V,I); 1 : not linked(V,V) }.\n"
"\n"
"reduced(V,I) :- reducible(V,I), prefer(V,N),\n"
" N #sum+{ 1,U : irreducible(U,I), U < V; 1,W,J : reduced(W,J), W < V, J < I }.\n"
"reduced(I) :- reduced(V,I).\n"
"\n"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
"% FINAL RESULT OF ITERATIVE REDUCTION %\n"
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
"\n"
"outvertex(V) :- vertex(V), not inner(V).\n"
"outvertex(V) :- unreduced(V,I), not reduced(I).\n"
"\n"
"outedge(U,V) :- edge(U,V), not link(U,V).\n"
"outedge(U,V) :- linked(U,V,I), not reduced(I).\n"));
}
SECTION("rec_count2") {
REQUIRE("a:-1!=#count{0,a:a}.\n" == ground("a:-{a}!=1.\n"));
}
SECTION("rec_conj") {
REQUIRE(
"edge(2,3).\n" "edge(2,5).\n" "edge(3,1).\n" "edge(3,4).\n"
"edge(3,6).\n" "edge(7,8).\n" "edge(8,9).\n"
"input(1).\n" "input(3).\n" "input(4).\n" "input(6).\n" "input(7).\n" "input(8).\n"
"observed(5).\n" "observed(9).\n" == ground(
"% example instance\n"
"\n"
"edge(2,3).\n"
"edge(3,1). edge(3,4). edge(3,6).\n"
"edge(2,5).\n"
"edge(7,8).\n"
"edge(8,9).\n"
"\n"
"input(7).\n"
"observed(5). observed(9).\n"
"\n"
"% a vertex is an input vertex if all its outgoing edges\n"
"% lead to input vertices and the vertex itself is no observation\n"
"% example:\n"
"% edges - from left to right\n"
"% x - some vertex\n"
"% i - input vertex\n"
"% o - observation vertex\n"
"%\n"
"% i\n"
"% /\n"
"% x---i---i\n"
"% \\ \\\n"
"% o i\n"
"input(V) :- edge(U,V), input(W) : edge(V,W); not observed(V).\n"
"\n"
"% An unobserved input vertex can explain any single non-input target.\n"
"% example:\n"
"% edges - from left to right\n"
"% (i) - explicitly marked input vertex\n"
"% i - input vertex\n"
"% o - observation vertex\n"
"%\n"
"% (i)---i---o\n"
"input(V) :- input(U); edge(U,V); input(W) : edge(U,W), V != W; not observed(U), not observed(V).\n"));
}
SECTION("conj") {
REQUIRE(
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"p(5).\n"
"p(6).\n"
"p(7).\n"
"s(1,2).\n"
"s(2,3).\n"
"s(3,4).\n"
"s(4,5).\n"
"s(5,6).\n"
"s(6,7).\n" == ground(
"p(1..7).\n"
"s(X,Z) :- p(X), #false : p(Y), X < Y, Y < Z; p(Z), X < Z.\n"));
REQUIRE(
"p(1):-not not p(1).\n"
"p(2):-not not p(2).\n"
"p(3):-not not p(3).\n"
"p(4):-not not p(4).\n"
"s(1,2):-p(2),p(1).\n"
"s(1,3):-p(3),p(1),#false:p(2).\n"
"s(1,4):-p(4),p(1),#false:p(2)|p(3).\n"
"s(2,3):-p(3),p(2).\n"
"s(2,4):-p(4),p(2),#false:p(3).\n"
"s(3,4):-p(4),p(3).\n" == ground(
"p(X) :- not not p(X), X=1..4.\n"
"s(X,Z) :- p(X), #false : p(Y), X < Y, Y < Z; p(Z), X < Z.\n"));
REQUIRE(
"p(1):-not not p(1).\n"
"p(2):-not not p(2).\n"
"p(3):-not not p(3).\n"
"p(4):-not not p(4).\n"
"s(1,2):-p(2),p(1).\n"
"s(1,3):-p(3),p(1),not p(2):p(2).\n"
"s(1,4):-p(4),p(1),not p(2):p(2);not p(3):p(3).\n"
"s(2,3):-p(3),p(2).\n"
"s(2,4):-p(4),p(2),not p(3):p(3).\n"
"s(3,4):-p(4),p(3).\n" == ground(
"p(X) :- not not p(X), X=1..4.\n"
"s(X,Z) :- p(X), not p(Y) : p(Y), X < Y, Y < Z; p(Z), X < Z.\n"
));
}
SECTION("meta") {
REQUIRE(
"hold(atom(p)):-hold(conjunction(0)).\n"
"hold(atom(q)):-hold(conjunction(2)).\n"
"hold(atom(r)):-hold(conjunction(2)).\n"
"hold(atom(s)):-hold(conjunction(1)).\n"
"hold(atom(t)):-hold(conjunction(0)).\n"
"hold(conjunction(0)):-hold(sum(1,0,2)).\n"
"hold(conjunction(1)):-not hold(atom(q)),not hold(atom(r)).\n"
"hold(conjunction(2)):-hold(sum(1,1,2)).\n"
"hold(conjunction(3)):-hold(atom(r)),hold(atom(q)).\n"
"hold(sum(1,0,2)):-1<=#sum{1,2:not hold(atom(t));1,1:hold(atom(s));1,0:hold(atom(r))}<=2.\n"
"hold(sum(1,1,2)):-1<=#sum{1,1:hold(atom(t));1,0:hold(atom(p))}.\n" == ground(
"wlist(0,0,pos(atom(r)),1).\n"
"wlist(0,1,pos(atom(s)),1).\n"
"wlist(0,2,neg(atom(t)),1).\n"
"set(0,pos(sum(1,0,2))).\n"
"rule(pos(atom(p)),pos(conjunction(0))).\n"
"rule(pos(atom(t)),pos(conjunction(0))).\n"
"set(1,neg(atom(q))).\n"
"set(1,neg(atom(r))).\n"
"rule(pos(atom(s)),pos(conjunction(1))).\n"
"wlist(1,0,pos(atom(p)),1).\n"
"wlist(1,1,pos(atom(t)),1).\n"
"set(2,pos(sum(1,1,2))).\n"
"rule(pos(atom(q)),pos(conjunction(2))).\n"
"rule(pos(atom(r)),pos(conjunction(2))).\n"
"set(3,pos(atom(r))).\n"
"set(3,pos(atom(q))).\n"
"rule(pos(false),pos(conjunction(3))).\n"
"scc(0,pos(atom(t))).\n"
"scc(0,pos(atom(r))).\n"
"scc(0,pos(sum(1,0,2))).\n"
"scc(0,pos(conjunction(0))).\n"
"scc(0,pos(atom(p))).\n"
"scc(0,pos(sum(1,1,2))).\n"
"scc(0,pos(conjunction(2))).\n"
"\n"
"litb(B) :- rule(_,B).\n"
"litb(E) :- litb(pos(conjunction(S))), set(S,E).\n"
"litb(E) :- eleb(sum(_,S,_)), wlist(S,_,E,_).\n"
"litb(E) :- eleb(min(_,S,_)), wlist(S,_,E,_).\n"
"litb(E) :- eleb(max(_,S,_)), wlist(S,_,E,_).\n"
"\n"
"eleb(P) :- litb(pos(P)).\n"
"eleb(N) :- litb(neg(N)).\n"
"\n"
"hold(conjunction(S)) :- eleb(conjunction(S)),\n"
" hold(P) : set(S,pos(P));\n"
" not hold(N) : set(S,neg(N)).\n"
"hold(sum(L,S,U)) :- eleb(sum(L,S,U)),\n"
" L #sum { W,Q : hold(P), wlist(S,Q,pos(P),W);\n"
" W,Q : not hold(N), wlist(S,Q,neg(N),W) } U.\n"
"hold(min(L,S,U)) :- eleb(min(L,S,U)),\n"
" L #max { W,Q : hold(P), wlist(S,Q,pos(P),W);\n"
" W,Q : not hold(N), wlist(S,Q,neg(N),W) } U.\n"
"hold(max(L,S,U)) :- eleb(max(L,S,U)),\n"
" L #min { W,Q : hold(P), wlist(S,Q,pos(P),W);\n"
" W,Q : not hold(N), wlist(S,Q,neg(N),W) } U.\n"
"\n"
"hold(atom(A)) :- rule(pos(atom(A)), pos(B)), hold(B).\n", {"hold("}));
}
SECTION("head") {
REQUIRE(
"2<=#count{q,1:q(1);q,2:q(2);q,3:q(3);r,3:r(3);r,3:#true:not r(3);r,4:r(4);r,4:#true:not r(4);r,5:r(5);r,5:#true:not r(5)}<=4.\n"
"out(q(1)):-q(1).\n" "out(q(2)):-q(2).\n" "out(q(3)):-q(3).\n"
"out(r(3)):-r(3).\n" "out(r(4)):-r(4).\n" "out(r(5)):-r(5).\n"
"p(1).\n" "p(2).\n" "p(3).\n" "p(4).\n" "p(5).\n" == ground(
"p(1..5).\n"
"2 #count { q,X : q(X) : p(X), X <= 3; r,X : r(X) : p(X), X >= 3; r,X : not r(X) : p(X), X >= 3 } 4.\n"
"out(q(X)):-q(X).\n"
"out(r(X)):-r(X).\n"));
}
SECTION("head2") {
REQUIRE(
"#count{0,d:d;0,e:e}.\n"
"a.\n"
"b.\n"
"c.\n"
"f:-d,e.\n" == ground(
"a.\n"
"b.\n"
"c.\n"
"{d:a;e:b}:-c.\n"
"f:-e,d.\n"
));
REQUIRE(
"#count{0,r(a):#true}:-r(d).\n"
"#count{0,r(b):r(b)}:-r(e).\n"
"#count{0,r(e):r(e)}:-r(b).\n"
"1>=#count{0,r(b):r(b);0,r(c):r(c)}.\n"
"1>=#count{0,r(d):r(d);0,r(e):r(e)}:-r(c).\n"
"p(a,b).\n"
"p(a,c).\n"
"p(b,e).\n"
"p(c,d).\n"
"p(c,e).\n"
"p(d,a).\n"
"p(e,b).\n"
"r(a).\n" == ground(
"p(a,b).\n"
"p(a,c).\n"
"p(c,d).\n"
"p(c,e).\n"
"p(d,a).\n"
"p(b,e).\n"
"p(e,b).\n"
"\n"
"r(a).\n"
"{ r(Y) : p(X,Y) } 1 :- r(X).\n"
));
REQUIRE(
"a.\n"
"b.\n"
"c.\n"
"d;e.\n"
"f:-d,e.\n" == ground(
"a.\n"
"b.\n"
"c.\n"
"d:a | e:b :- c.\n"
"f :- e;d.\n"
));
REQUIRE(
"#true:-r(d).\n"
"p(a,b).\n"
"p(a,c).\n"
"p(b,e).\n"
"p(c,d).\n"
"p(c,e).\n"
"p(d,a).\n"
"p(e,b).\n"
"r(a).\n"
"r(b):-r(e).\n"
"r(b);r(c).\n"
"r(d);r(e):-r(c).\n"
"r(e):-r(b).\n" == ground(
"p(a,b).\n"
"p(a,c).\n"
"p(c,d).\n"
"p(c,e).\n"
"p(d,a).\n"
"p(b,e).\n"
"p(e,b).\n"
"\n"
"r(a).\n"
"r(Y) : p(X,Y) :- r(X).\n"
));
}
SECTION("disjunction") {
REQUIRE(
"out(q(1)):-q(1).\n" "out(q(2)):-q(2).\n" "out(q(3)):-q(3).\n"
"out(r(3)):-r(3).\n" "out(r(4)):-r(4).\n" "out(r(5)):-r(5).\n"
"p(1).\n" "p(2).\n" "p(3).\n" "p(4).\n" "p(5).\n"
"q(1);q(2);q(3);r(3);r(4);r(5);not r(3);not r(4);not r(5).\n" == ground(
"p(1..5).\n"
"q(X) : p(X), X <= 3; r(X) : p(X), X >= 3; not r(X) : p(X), X >= 3.\n"
"out(q(X)):-q(X).\n"
"out(r(X)):-r(X).\n"));
}
SECTION("gbie") {
REQUIRE("gt(-3,-4).\n" == ground(gbie()+gbie1(), {"gt(", "le("}));
REQUIRE("le(-18,-16).\n" == ground(gbie()+gbie2(), {"gt(", "le("}));
}
SECTION("strategicA") {
REQUIRE(
"strategic(1):-strategic(2),strategic(2),strategic(5).\n"
"strategic(1):-strategic(3),strategic(3),strategic(5).\n"
"strategic(1);strategic(1).\n"
"strategic(1);strategic(5).\n"
"strategic(2):-strategic(1),strategic(3),strategic(6).\n"
"strategic(2):-strategic(5),strategic(3),strategic(6).\n"
"strategic(2);strategic(4).\n"
"strategic(2);strategic(4).\n"
"strategic(2);strategic(5).\n"
"strategic(2);strategic(6).\n"
"strategic(3):-strategic(5),strategic(1),strategic(4).\n"
"strategic(3):-strategic(6),strategic(1),strategic(4).\n"
"strategic(3);strategic(4).\n"
"strategic(3);strategic(4).\n"
"strategic(4):-strategic(5),strategic(5),strategic(2).\n"
"strategic(4):-strategic(6),strategic(6),strategic(2).\n"
"strategic(4);strategic(2).\n"
"strategic(4);strategic(4).\n"
"strategic(4);strategic(4).\n"
"strategic(4);strategic(6).\n"
"strategic(5):-strategic(1),strategic(1),strategic(1).\n"
"strategic(5);strategic(2).\n"
"strategic(5);strategic(2).\n"
"strategic(5);strategic(5).\n"
"strategic(5);strategic(5).\n"
"strategic(6):-strategic(4),strategic(4),strategic(4).\n"
"strategic(6);strategic(1).\n"
"strategic(6);strategic(1).\n"
"strategic(6);strategic(2).\n"
"strategic(6);strategic(2).\n"
"strategic(6);strategic(4).\n"
"strategic(6);strategic(4).\n"
"strategic(6);strategic(5).\n"
"strategic(6);strategic(6).\n" == ground(
strategicA1() +
"strategic(X2); strategic(X1) :- produced_by(P,X1,X2).\n"
"strategic(W) :- controlled_by(W,X1,X2,X3), strategic(X1), strategic(X2), strategic(X3).\n", {"strategic("}));
}
SECTION("strategicB") {
REQUIRE(
"strategic(1).\n"
"strategic(1):-strategic(5),strategic(2).\n"
"strategic(1):-strategic(5),strategic(3).\n"
"strategic(1);strategic(6).\n"
"strategic(1);strategic(6).\n"
"strategic(2):-strategic(6),strategic(3),strategic(1).\n"
"strategic(2):-strategic(6),strategic(3),strategic(5).\n"
"strategic(2);strategic(4).\n"
"strategic(2);strategic(5).\n"
"strategic(2);strategic(5).\n"
"strategic(2);strategic(6).\n"
"strategic(2);strategic(6).\n"
"strategic(3):-strategic(4),strategic(1),strategic(5).\n"
"strategic(3):-strategic(4),strategic(1),strategic(6).\n"
"strategic(4).\n"
"strategic(4).\n"
"strategic(4):-strategic(2),strategic(5).\n"
"strategic(4):-strategic(2),strategic(6).\n"
"strategic(4);strategic(2).\n"
"strategic(4);strategic(2).\n"
"strategic(4);strategic(3).\n"
"strategic(4);strategic(3).\n"
"strategic(4);strategic(6).\n"
"strategic(4);strategic(6).\n"
"strategic(5).\n"
"strategic(5).\n"
"strategic(5):-strategic(1).\n"
"strategic(5);strategic(1).\n"
"strategic(5);strategic(2).\n"
"strategic(5);strategic(6).\n"
"strategic(6).\n"
"strategic(6):-strategic(4).\n"
"strategic(6);strategic(2).\n"
"strategic(6);strategic(4).\n" == ground(
strategicB1() +
"strategic(X) : produced_by(P,X) :- produced_by(P,_).\n"
"strategic(X) :- controlled_by(C,X,_), strategic(Y) : controlled_by(C,X,Y).\n", {"strategic("}));
}
SECTION("optimize") {
REQUIRE(
":~p(1).[1@0]\n"
":~p(2).[2@0]\n"
":~p(3).[3@0]\n"
":~p(4).[4@0]\n"
"{p(1)}.\n"
"{p(2)}.\n"
"{p(3)}.\n"
"{p(4)}.\n" == ground(
"{p((1..4))}."
":~p(X).[X@0]"));
REQUIRE(
":~p(1).[1@0]\n"
":~p(2).[2@0]\n"
":~p(3).[3@0]\n"
":~p(4).[4@0]\n"
"{p(1)}.\n"
"{p(2)}.\n"
"{p(3)}.\n"
"{p(4)}.\n" == ground(
"{p((1..4))}."
"#minimize{X@0:p(X)}."));
REQUIRE(
":~p(1).[-1@0]\n"
":~p(2).[-2@0]\n"
":~p(3).[-3@0]\n"
":~p(4).[-4@0]\n"
"{p(1)}.\n"
"{p(2)}.\n"
"{p(3)}.\n"
"{p(4)}.\n" == ground(
"{p((1..4))}."
"#maximize{X@0:p(X)}."));
REQUIRE(
":~.[1@1]\n"
":~p(1),p(1).[1@1,f,g]\n"
":~p(1).[1@0]\n"
":~p(1).[1@2]\n"
":~p(2),p(2).[2@2,f,g]\n"
":~p(2).[2@0]\n"
":~p(2).[2@2]\n"
":~p(3),p(3).[3@3,f,g]\n"
":~p(3).[3@0]\n"
":~p(3).[3@2]\n"
":~p(4),p(4).[4@4,f,g]\n"
":~p(4).[4@0]\n"
":~p(4).[4@2]\n"
"{p(1)}.\n"
"{p(2)}.\n"
"{p(3)}.\n"
"{p(4)}.\n"
"-:1:41-42: info: tuple ignored:\n f@f\n"
== ground(
"{p((1..4))}."
"#minimize{X:p(X); X@2:p(X); f@f; 1@1; X@X,f,g:p(X),p(X)}."));
}
SECTION("neg") {
REQUIRE(
"-q(1):-not not -q(1).\n"
"-q(2):-not not -q(2).\n"
"-q(3):-not not -q(3).\n"
"-q(4):-not not -q(4).\n"
":-q(1),-q(1).\n"
":-q(2),-q(2).\n"
":-q(3),-q(3).\n"
":-q(4),-q(4).\n"
"p(1).\n"
"p(2).\n"
"p(3).\n"
"p(4).\n"
"q(1):-not not q(1).\n"
"q(2):-not not q(2).\n"
"q(3):-not not q(3).\n"
"q(4):-not not q(4).\n" == ground(
"p(1..4).\n"
"-q(X):-not not -q(X), p(X).\n"
" q(X):-not not q(X), p(X).\n"));
}
SECTION("two aggregates") {
REQUIRE(
"p:-#count{0,a:a}=0.\n"
"p:-#count{0,a:a}=1,1<=#count{0,b:b}.\n"
"{a;b}.\n" == ground(
"{a;b}.\n"
"p :- X = { a }, X { b }.\n"));
}
SECTION("tuple") {
REQUIRE("p(((),())).\n" == ground("p(((),())).\n"));
}
}
} } } // namespace Test Ground Gringo
| [
"kaminski@cs.uni-potsdam.de"
] | kaminski@cs.uni-potsdam.de |
74437dc8b2f8c9db4944c8b44e232ec9d196714f | 6d0c31e156fe0dd9d05c21ad53215956ba876a6f | /threadlib/test/Thread_test.cpp | b9872e0bdf5502ad655557a9c3e48a38f0c5b6eb | [] | no_license | weetee/tdynet | 801d6c95a8d99c598c535b09447850ba71a82e28 | 56ff16b54a2456627a8afdc43f32710826a67f6d | refs/heads/master | 2021-01-20T23:03:56.802865 | 2017-09-22T05:06:21 | 2017-09-22T05:06:21 | 101,837,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | #include "../Thread.h"
#include "../Mutex.h"
#include <cstdint>
#define MAX_LOOP_COUNT 100
using namespace tdy;
//定义互斥锁
Mutex mutex = Mutex();
void *PrintThread(void *p_data)
{
long i = (long)(p_data);
char c = (char)i;
mutex.LockMutex();
for (int i = 0; i < MAX_LOOP_COUNT; ++i)
{
cout << c;
cout.flush();
usleep(1);
}
cout << endl;
mutex.UnlockMutex();
return (void *)0;
}
int main(void)
{
Thread tobj = Thread();
t_thread td1, td2;
//创建线程
td1 = tobj.Create(PrintThread, (void *)'a');
td2 = tobj.Create(PrintThread, (void *)'b');
//等待线程结束
tobj.WaitThreadFinish(td1);
tobj.WaitThreadFinish(td2);
cout << "end" << endl;
return 0;
}
| [
"weitaoee@gmail.com"
] | weitaoee@gmail.com |
3b3dc246e0c803cfdeaad8665b44624b011069e9 | 5464c7ca393dfd6f25f77bc8781ee86f2efa7b83 | /src/qt/qtipcserver.cpp | 8ec3d9e9af33fa7da1e42f7ad4f6734fb6b0f082 | [
"MIT"
] | permissive | traiborg/Agrolifecoin | 12f0bc35cdcd6190ff09c8abd0dd772131d3ec7d | c53bf4d40bac59cc8cb835adfe484ecbea2b791d | refs/heads/master | 2021-01-17T20:13:04.472148 | 2017-04-01T11:25:36 | 2017-04-01T11:25:36 | 86,873,518 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,935 | cpp | // Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/version.hpp>
#if defined(WIN32) && BOOST_VERSION == 104900
#define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME
#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME
#endif
#include "qtipcserver.h"
#include "guiconstants.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/version.hpp>
#if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900)
#warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392
#endif
using namespace boost;
using namespace boost::interprocess;
using namespace boost::posix_time;
#if defined MAC_OSX || defined __FreeBSD__
// URI handling not implemented on OSX yet
void ipcScanRelay(int argc, char *argv[]) { }
void ipcInit(int argc, char *argv[]) { }
#else
static void ipcThread2(void* pArg);
static bool ipcScanCmd(int argc, char *argv[], bool fRelay)
{
// Check for URI in argv
bool fSent = false;
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "Agrolifecoin:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if (mq.try_send(strURI, strlen(strURI), 0))
fSent = true;
else if (fRelay)
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
// don't log the "file not found" exception, because that's normal for
// the first start of the first instance
if (ex.get_error_code() != boost::interprocess::not_found_error || !fRelay)
{
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
}
return fSent;
}
void ipcScanRelay(int argc, char *argv[])
{
if (ipcScanCmd(argc, argv, true))
exit(0);
}
static void ipcThread(void* pArg)
{
// Make this thread recognisable as the GUI-IPC thread
RenameThread("Agrolifecoin-gui-ipc");
try
{
ipcThread2(pArg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ipcThread()");
} catch (...) {
PrintExceptionContinue(NULL, "ipcThread()");
}
printf("ipcThread exited\n");
}
static void ipcThread2(void* pArg)
{
printf("ipcThread started\n");
message_queue* mq = (message_queue*)pArg;
char buffer[MAX_URI_LENGTH + 1] = "";
size_t nSize = 0;
unsigned int nPriority = 0;
while (true)
{
ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100);
if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
{
uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
MilliSleep(1000);
}
if (fShutdown)
break;
}
// Remove message queue
message_queue::remove(BITCOINURI_QUEUE_NAME);
// Cleanup allocated memory
delete mq;
}
void ipcInit(int argc, char *argv[])
{
message_queue* mq = NULL;
char buffer[MAX_URI_LENGTH + 1] = "";
size_t nSize = 0;
unsigned int nPriority = 0;
try {
mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);
// Make sure we don't lose any bitcoin: URIs
for (int i = 0; i < 2; i++)
{
ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1);
if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
{
uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
}
else
break;
}
// Make sure only one bitcoin instance is listening
message_queue::remove(BITCOINURI_QUEUE_NAME);
delete mq;
mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);
}
catch (interprocess_exception &ex) {
printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
return;
}
if (!NewThread(ipcThread, mq))
{
delete mq;
return;
}
ipcScanCmd(argc, argv, false);
}
#endif
| [
"user@gmail.com"
] | user@gmail.com |
e46ec5c5cbe9a8de7ff3c896d2a3e2b0deac5f66 | 7d5593b9bbaf6bb8eaacca88449d90c9c305c36e | /problems/297-serialize-and-deserialize-binary-tree/297.cc | 67f3374727c106139e84c816c1ca1fd881884129 | [] | no_license | yottacto/leetcode | fc98052ed9d643be8a79116d28540596bcc7c26b | 9a41e41c0982c1a313803d1d8288d086fbdbd5b6 | refs/heads/master | 2021-04-25T12:05:55.671066 | 2019-12-15T03:07:31 | 2019-12-15T03:07:31 | 111,814,868 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34 | cc | #include "297.hh"
int main()
{
}
| [
"yotta.w.cto@gmail.com"
] | yotta.w.cto@gmail.com |
1436f3e236b1c745472fdff09080b156beb4bc7d | 931e3c281938a4476646ba3bdc987440793686f4 | /sys/Thing.cpp | bd9df898f3088b2e1d471e372d3256e23d9bde79 | [] | no_license | antoniopessotti/praat | 32bd58450c477ac0bc7a90a94c2bcc6636bcaa90 | 4026b1a4d5609277a037895414131e50eda8ce10 | refs/heads/master | 2021-01-17T15:44:50.849862 | 2015-06-01T00:00:00 | 2015-06-03T20:19:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,169 | cpp | /* Thing.cpp
*
* Copyright (C) 1992-2012 Paul Boersma
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdarg.h>
#include <time.h>
#include "Thing.h"
static long theTotalNumberOfThings;
void structThing :: v_info ()
{
MelderInfo_writeLine (L"Object type: ", Thing_className (this));
MelderInfo_writeLine (L"Object name: ", this -> name ? this -> name : L"<no name>");
time_t today = time (NULL);
MelderInfo_writeLine (L"Date: ", Melder_peekUtf8ToWcs (ctime (& today))); /* Includes a newline. */
}
/*
* Instead of the Thing_implement macro.
*/
struct structClassInfo theClassInfo_Thing = {
L"Thing",
NULL, // no parent class
sizeof (class structThing),
NULL, // no _new function (not needed; plus, it would have to be called "_Thing_new", but that name has been given to something else)
0, // version
0, // sequentialUniqueIdOfReadableClass
NULL // dummyObject
};
ClassInfo classThing = & theClassInfo_Thing;
const wchar_t * Thing_className (Thing me) { return my classInfo -> className; }
Any _Thing_new (ClassInfo classInfo) {
Thing me = (Thing) classInfo -> _new ();
trace ("created %ls", classInfo -> className);
theTotalNumberOfThings += 1;
my classInfo = classInfo;
Melder_assert (my name == NULL); // check that _new called calloc
if (Melder_debug == 40) Melder_casual ("created %ls (%p, %p)", classInfo -> className, classInfo, me);
return me;
}
static int theNumberOfReadableClasses = 0;
static ClassInfo theReadableClasses [1 + 1000];
static void _Thing_addOneReadableClass (ClassInfo readableClass) {
if (++ theNumberOfReadableClasses > 1000)
Melder_fatal ("(Thing_recognizeClassesByName:) Too many (1001) readable classes.");
theReadableClasses [theNumberOfReadableClasses] = readableClass;
readableClass -> sequentialUniqueIdOfReadableClass = theNumberOfReadableClasses;
}
void Thing_recognizeClassesByName (ClassInfo readableClass, ...) {
va_list arg;
if (readableClass == NULL) return;
va_start (arg, readableClass);
_Thing_addOneReadableClass (readableClass);
ClassInfo klas;
while ((klas = va_arg (arg, ClassInfo)) != NULL) {
_Thing_addOneReadableClass (klas);
}
va_end (arg);
}
long Thing_listReadableClasses (void) {
Melder_clearInfo ();
MelderInfo_open ();
for (long iclass = 1; iclass <= theNumberOfReadableClasses; iclass ++) {
ClassInfo klas = theReadableClasses [iclass];
MelderInfo_writeLine (Melder_integer (klas -> sequentialUniqueIdOfReadableClass), L"\t", klas -> className);
}
MelderInfo_close ();
return theNumberOfReadableClasses;
}
static int theNumberOfAliases = 0;
static struct {
ClassInfo readableClass;
const wchar_t *otherName;
} theAliases [1 + 100];
void Thing_recognizeClassByOtherName (ClassInfo readableClass, const wchar_t *otherName) {
theAliases [++ theNumberOfAliases]. readableClass = readableClass;
theAliases [theNumberOfAliases]. otherName = otherName;
}
long Thing_version; // global variable!
ClassInfo Thing_classFromClassName (const wchar_t *klas) {
static wchar_t buffer [1+100];
wcsncpy (buffer, klas ? klas : L"", 100);
wchar_t *space = wcschr (buffer, ' ');
if (space) {
*space = '\0'; // strip version number
Thing_version = wcstol (space + 1, NULL, 10);
} else {
Thing_version = 0;
}
/*
* First try the class names that were registered with Thing_recognizeClassesByName.
*/
for (int i = 1; i <= theNumberOfReadableClasses; i ++) {
ClassInfo classInfo = theReadableClasses [i];
if (wcsequ (buffer, classInfo -> className)) {
return classInfo;
}
}
/*
* Then try the aliases that were registered with Thing_recognizeClassByOtherName.
*/
for (int i = 1; i <= theNumberOfAliases; i ++) {
if (wcsequ (buffer, theAliases [i]. otherName)) {
ClassInfo classInfo = theAliases [i]. readableClass;
return classInfo;
}
}
Melder_throw ("Class \"", buffer, "\" not recognized.");
}
Any Thing_newFromClassNameA (const char *className) {
try {
ClassInfo classInfo = Thing_classFromClassName (Melder_peekUtf8ToWcs (className));
return _Thing_new (classInfo);
} catch (MelderError) {
Melder_throw (className, " not created.");
}
}
Any Thing_newFromClassName (const wchar_t *className) {
try {
ClassInfo classInfo = Thing_classFromClassName (className);
return _Thing_new (classInfo);
} catch (MelderError) {
Melder_throw (className, " not created.");
}
}
Thing _Thing_dummyObject (ClassInfo classInfo) {
if (classInfo -> dummyObject == NULL) {
classInfo -> dummyObject = (Thing) classInfo -> _new ();
}
Melder_assert (classInfo -> dummyObject != NULL);
return classInfo -> dummyObject;
}
void _Thing_forget_nozero (Thing me) {
if (! me) return;
if (Melder_debug == 40) Melder_casual ("destroying %ls", my classInfo -> className);
my v_destroy ();
theTotalNumberOfThings -= 1;
}
void _Thing_forget (Thing me) {
if (! me) return;
if (Melder_debug == 40) Melder_casual ("destroying %ls", my classInfo -> className);
my v_destroy ();
trace ("destroying %ls", my classInfo -> className);
//Melder_free (me);
delete me;
theTotalNumberOfThings -= 1;
}
bool Thing_subclass (ClassInfo klas, ClassInfo ancestor) {
while (klas != ancestor && klas != NULL) klas = klas -> parent;
return klas != NULL;
}
bool Thing_member (Thing me, ClassInfo klas) {
if (! me) Melder_fatal ("(Thing_member:) Found NULL object.");
return Thing_subclass (my classInfo, klas);
}
void * _Thing_check (Thing me, ClassInfo klas, const char *fileName, int line) {
if (! me) Melder_fatal ("(_Thing_check:) NULL object passed to a function\n"
"in file %.100s at line %d.", fileName, line);
ClassInfo classInfo = my classInfo;
while (classInfo != klas && classInfo != NULL) classInfo = classInfo -> parent;
if (! classInfo)
Melder_fatal ("(_Thing_check:) Object of wrong class (%.50s) passed to a function\n"
"in file %.100s at line %d.", Melder_peekWcsToUtf8 (my classInfo -> className), fileName, line);
return me;
}
void Thing_infoWithIdAndFile (Thing me, unsigned long id, MelderFile file) {
//Melder_assert (me != NULL);
Melder_clearInfo ();
MelderInfo_open ();
if (id != 0) MelderInfo_writeLine (L"Object id: ", Melder_integer (id));
if (! MelderFile_isNull (file)) MelderInfo_writeLine (L"Associated file: ", Melder_fileToPath (file));
my v_info ();
MelderInfo_close ();
}
void Thing_info (Thing me) {
Thing_infoWithIdAndFile (me, 0, NULL);
}
wchar_t * Thing_getName (Thing me) { return my name; }
wchar_t * Thing_messageName (Thing me) {
static MelderString buffers [11];
static int ibuffer = 0;
if (++ ibuffer == 11) ibuffer = 0;
MelderString_empty (& buffers [ibuffer]);
if (my name) {
MelderString_append (& buffers [ibuffer], my classInfo -> className, L" \"", my name, L"\"");
} else {
MelderString_append (& buffers [ibuffer], my classInfo -> className);
}
return buffers [ibuffer]. string;
}
void Thing_setName (Thing me, const wchar_t *name) {
/*
* First check without change.
*/
autostring newName = Melder_wcsdup_f (name); // BUG: that's no checking
/*
* Then change without error.
*/
Melder_free (my name);
my name = newName.transfer();
my v_nameChanged ();
}
long Thing_getTotalNumberOfThings (void) { return theTotalNumberOfThings; }
void Thing_swap (Thing me, Thing thee) {
Melder_assert (my classInfo == thy classInfo);
int n = my classInfo -> size;
char *p, *q;
int i;
for (p = (char *) me, q = (char *) thee, i = n; i > 0; i --, p ++, q ++) {
char tmp = *p;
*p = *q;
*q = tmp;
}
}
/* End of file Thing.cpp */
| [
"jjatria@gmail.com"
] | jjatria@gmail.com |
8366f31f5d0ef9cdc8dbf2abf40fda61de9594c8 | faa9926ca6294f1c032c1482f8b7a1e03b0a22ed | /Dungeons-Mazes/Graphics/ColorShaderClass.hpp | c750971b4f837abb32ab1b529ba00f57c38147c5 | [] | no_license | jacekard/Projekt_PR | b521949814ed41c12e373e9f2937d0cf9958895c | 2ca77c63ecb003e454d5b849697709e1ebf3fefb | refs/heads/master | 2021-04-15T08:52:55.016702 | 2019-03-11T18:14:40 | 2019-03-11T18:14:40 | 126,695,498 | 1 | 2 | null | 2019-03-11T18:14:42 | 2018-03-25T12:31:23 | JavaScript | UTF-8 | C++ | false | false | 891 | hpp | #pragma once
#include "GraphicsConf.hpp"
class ColorShaderClass
{
private:
struct MatrixBufferType
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
public:
ColorShaderClass();
ColorShaderClass(const ColorShaderClass&);
~ColorShaderClass();
bool Initialize(ID3D11Device*, HWND);
void Shutdown();
bool Render(ID3D11DeviceContext*, int, XMMATRIX, XMMATRIX, XMMATRIX);
private:
bool InitializeShader(ID3D11Device*, HWND, LPCSTR, LPCSTR);
void ShutdownShader();
void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX);
void RenderShader(ID3D11DeviceContext*, int);
private:
ID3D11VertexShader * m_vertexShader;
ID3D11PixelShader* m_pixelShader;
ID3D11InputLayout* m_layout;
ID3D11Buffer* m_matrixBuffer;
}; | [
"jacekard@gmail.com"
] | jacekard@gmail.com |
e8e7cb2ad045b2e94c0affd68b2a9c8ad36b11dd | 09eaf2b22ad39d284eea42bad4756a39b34da8a2 | /ojs/opentrains/1454/G/G.cpp | ad12eabe1b823f7dbced4319809bf3f49151cc82 | [] | no_license | victorsenam/treinos | 186b70c44b7e06c7c07a86cb6849636210c9fc61 | 72a920ce803a738e25b6fc87efa32b20415de5f5 | refs/heads/master | 2021-01-24T05:58:48.713217 | 2018-10-14T13:51:29 | 2018-10-14T13:51:29 | 41,270,007 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,539 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pii;
#define pb push_back
const ll modn = 1000000007;
inline ll mod(ll x) { return x % modn; }
const ll i2 = (modn + 1ll) / 2ll;
const int N = 512345;
ll mul[N], ct[N], fat[N];
int p[N], seen[N];
int n;
ll memo[N][2];
ll solve(int i, int p) {
if(i == n + 1) return (p == 0);
ll &r = memo[i][p];
if(r != -1) return r;
//printf("solve(%d, %d)\n", i, p);
//printf("ct[%d] = %d\n", i, ct[i]);
r = 0;
if(ct[i] == 0) {
r = solve(i + 1, p);
} else if(!(i & 1) || ct[i] > 1) {
r = mod(mod(mod(solve(i + 1, p) * mul[i]) * fat[ct[i]]) * i2);
r = mod(r + mod(mod(mod(solve(i + 1, !p) * mul[i]) * fat[ct[i]]) * i2));
} else{
r = mod(mod(solve(i + 1, p) * mul[i]) * fat[ct[i]]);
}
//if(ct[i] == 0) {
// r = solve(i + 1, p);
//} else if((i & 1) || (ct[i] == 1)) {
// r = mod(mod(solve(i + 1, p) * mul[i]) * fat[ct[i]]);
//} else {
// r = mod(mod(solve(i + 1, p) * fat[ct[i]]) * i2);
// r = mod(r + mod(solve(i + 1, !p) * fat[ct[i]]) * i2);
// r = mod(r * mul[i]);
//}
//printf("solve(%d, %d) = %lld\n", i, p, r);
return r;
}
int main() {
scanf("%d", &n);
fat[0] = 1;
int i;
for(i = 1; i <= n; i++) {
fat[i] = mod(fat[i - 1] * ll(i));
scanf("%d", &p[i]);
mul[i] = 1;
}
for(i = 1; i <= n; i++) {
if(seen[i]) continue;
int sz = 1; seen[i] = 1;
for(int j = p[i]; j != i; j = p[j], sz++) seen[j] = 1;
ct[sz]++;
mul[sz] = mod(mul[sz] * ll(sz));
}
memset(memo, -1, sizeof memo);
printf("%lld\n", solve(1, 0));
}
| [
"victorsenam@gmail.com"
] | victorsenam@gmail.com |
b14ab7c95385832fff2bffbbfe43b53d591dda32 | 5b6092f32f36009efd32bb3e296f9060a1675d9e | /main.cpp | b43873180c8e7c398eaf7ed4e0a86132a73adefd | [] | no_license | ahmedgoda24/Algorithm-and-DS-Tower-of-Hanoi-linkedlist | 84ef28ff95c51dc08c105b70376afc30353f4b9a | 285d1ec3171b1d42fcba914c14b543d5034f7745 | refs/heads/main | 2023-07-02T04:56:25.347889 | 2021-08-08T18:50:01 | 2021-08-08T18:50:01 | 394,044,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | cpp | #include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is " << squareroot << endl;
return 0;
}
| [
"goda242424@gmail.com"
] | goda242424@gmail.com |
becb5aac3cb2c5cd26ff497cd1e050e2e9193df0 | aededd389dcb74d5d2bdcd106d11fa7103d59319 | /Book_Project/Intermediate/Build/Win64/UE4Editor/Inc/Book_Project/EnemyAI.generated.h | 1fcf7c8a6ba0d601c5998add0dd54e6146a2ecb8 | [] | no_license | BrennanK/Project_Clockwork | f062850cc88fed79470cb59369858fa325f1dc9c | bcf6e0beed5f32929db2a5e297de3b799e99fc67 | refs/heads/master | 2022-12-04T21:19:05.060681 | 2020-08-23T20:59:29 | 2020-08-23T20:59:29 | 218,882,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,830 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef BOOK_PROJECT_EnemyAI_generated_h
#error "EnemyAI.generated.h already included, missing '#pragma once' in EnemyAI.h"
#endif
#define BOOK_PROJECT_EnemyAI_generated_h
#define Book_Project_Source_Book_Project_EnemyAI_h_15_RPC_WRAPPERS
#define Book_Project_Source_Book_Project_EnemyAI_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define Book_Project_Source_Book_Project_EnemyAI_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesAEnemyAI(); \
friend struct Z_Construct_UClass_AEnemyAI_Statics; \
public: \
DECLARE_CLASS(AEnemyAI, AAIController, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Book_Project"), NO_API) \
DECLARE_SERIALIZER(AEnemyAI)
#define Book_Project_Source_Book_Project_EnemyAI_h_15_INCLASS \
private: \
static void StaticRegisterNativesAEnemyAI(); \
friend struct Z_Construct_UClass_AEnemyAI_Statics; \
public: \
DECLARE_CLASS(AEnemyAI, AAIController, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/Book_Project"), NO_API) \
DECLARE_SERIALIZER(AEnemyAI)
#define Book_Project_Source_Book_Project_EnemyAI_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API AEnemyAI(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AEnemyAI) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AEnemyAI); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AEnemyAI); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AEnemyAI(AEnemyAI&&); \
NO_API AEnemyAI(const AEnemyAI&); \
public:
#define Book_Project_Source_Book_Project_EnemyAI_h_15_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AEnemyAI(AEnemyAI&&); \
NO_API AEnemyAI(const AEnemyAI&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AEnemyAI); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AEnemyAI); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(AEnemyAI)
#define Book_Project_Source_Book_Project_EnemyAI_h_15_PRIVATE_PROPERTY_OFFSET \
FORCEINLINE static uint32 __PPO__BlackboardComp() { return STRUCT_OFFSET(AEnemyAI, BlackboardComp); } \
FORCEINLINE static uint32 __PPO__BehaviorComp() { return STRUCT_OFFSET(AEnemyAI, BehaviorComp); }
#define Book_Project_Source_Book_Project_EnemyAI_h_12_PROLOG
#define Book_Project_Source_Book_Project_EnemyAI_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Book_Project_Source_Book_Project_EnemyAI_h_15_PRIVATE_PROPERTY_OFFSET \
Book_Project_Source_Book_Project_EnemyAI_h_15_RPC_WRAPPERS \
Book_Project_Source_Book_Project_EnemyAI_h_15_INCLASS \
Book_Project_Source_Book_Project_EnemyAI_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Book_Project_Source_Book_Project_EnemyAI_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Book_Project_Source_Book_Project_EnemyAI_h_15_PRIVATE_PROPERTY_OFFSET \
Book_Project_Source_Book_Project_EnemyAI_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
Book_Project_Source_Book_Project_EnemyAI_h_15_INCLASS_NO_PURE_DECLS \
Book_Project_Source_Book_Project_EnemyAI_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> BOOK_PROJECT_API UClass* StaticClass<class AEnemyAI>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Book_Project_Source_Book_Project_EnemyAI_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"bjkersey@student.fullsail.edu"
] | bjkersey@student.fullsail.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.